@utk09/ui-observability 0.11.0 → 0.12.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 (383) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +273 -102
  3. package/bin/uiobs.mjs +1 -1
  4. package/dist/{batch-CL9uWYY3.js → batch-BjQUwjA6.js} +4 -4
  5. package/dist/batch-BjQUwjA6.js.map +1 -0
  6. package/dist/{batch-C8OcWR2L.cjs → batch-D5LlU4Q9.cjs} +2 -2
  7. package/dist/batch-D5LlU4Q9.cjs.map +1 -0
  8. package/dist/bus/bus.d.ts +48 -47
  9. package/dist/bus/links.d.ts +4 -4
  10. package/dist/bus/validation.d.ts +1 -1
  11. package/dist/bus-D_7pd7RN.cjs +2 -0
  12. package/dist/bus-D_7pd7RN.cjs.map +1 -0
  13. package/dist/{bus-BZ0GldpT.js → bus-ecxUNTja.js} +91 -91
  14. package/dist/bus-ecxUNTja.js.map +1 -0
  15. package/dist/capture/console.d.ts +10 -10
  16. package/dist/capture/errors.d.ts +6 -6
  17. package/dist/capture/interactions.d.ts +14 -14
  18. package/dist/capture/lifecycle.d.ts +3 -3
  19. package/dist/capture/long-frames.d.ts +6 -6
  20. package/dist/capture/network.d.ts +17 -17
  21. package/dist/capture/profiler-frames.d.ts +44 -0
  22. package/dist/capture/replay-buffer.d.ts +46 -0
  23. package/dist/capture/replay-upload.d.ts +74 -0
  24. package/dist/capture/replay.d.ts +114 -0
  25. package/dist/capture/reports.d.ts +2 -2
  26. package/dist/capture/resource-timing.d.ts +1 -1
  27. package/dist/capture/server-timing.d.ts +3 -3
  28. package/dist/capture/storm.d.ts +3 -3
  29. package/dist/capture/types.d.ts +45 -33
  30. package/dist/capture/unclean-exit.d.ts +8 -8
  31. package/dist/capture/user-timing.d.ts +3 -3
  32. package/dist/capture/web-socket.d.ts +11 -11
  33. package/dist/capture/web-vitals.d.ts +20 -7
  34. package/dist/compression-AJJCMBOa.js +11 -0
  35. package/dist/compression-AJJCMBOa.js.map +1 -0
  36. package/dist/compression-lD9abCcO.cjs +2 -0
  37. package/dist/compression-lD9abCcO.cjs.map +1 -0
  38. package/dist/{console-BPZCuSLc.cjs → console-CLz_PvFn.cjs} +2 -2
  39. package/dist/console-CLz_PvFn.cjs.map +1 -0
  40. package/dist/{console-BeCF7n59.js → console-cwgHKXvM.js} +4 -4
  41. package/dist/console-cwgHKXvM.js.map +1 -0
  42. package/dist/constants-Bwl_YtQi.js +349 -0
  43. package/dist/constants-Bwl_YtQi.js.map +1 -0
  44. package/dist/constants-DakMxVB2.cjs +2 -0
  45. package/dist/constants-DakMxVB2.cjs.map +1 -0
  46. package/dist/constants.d.ts +150 -103
  47. package/dist/context-storage-BjzeBSxH.cjs.map +1 -1
  48. package/dist/context-storage-BzkoHzkQ.js.map +1 -1
  49. package/dist/core/breadcrumbs.d.ts +16 -15
  50. package/dist/core/config.d.ts +3 -3
  51. package/dist/core/context.d.ts +7 -7
  52. package/dist/core/debug-buffer.d.ts +10 -10
  53. package/dist/core/debug-bundle.d.ts +3 -3
  54. package/dist/core/deferred.d.ts +2 -2
  55. package/dist/core/diagnostics.d.ts +24 -21
  56. package/dist/core/drops.d.ts +7 -7
  57. package/dist/core/hold-buffer.d.ts +1 -1
  58. package/dist/core/journey.d.ts +22 -23
  59. package/dist/core/logger.d.ts +22 -21
  60. package/dist/core/measure.d.ts +7 -7
  61. package/dist/core/meter.d.ts +25 -21
  62. package/dist/core/pipeline.d.ts +42 -41
  63. package/dist/core/profile-buckets.d.ts +31 -0
  64. package/dist/core/profiler.d.ts +218 -0
  65. package/dist/core/record.d.ts +23 -23
  66. package/dist/core/remote-rules.d.ts +4 -4
  67. package/dist/core/remote-sampling.d.ts +21 -20
  68. package/dist/core/runtime.d.ts +206 -137
  69. package/dist/core/sampling.d.ts +18 -18
  70. package/dist/core/sender.d.ts +22 -20
  71. package/dist/core/spans.d.ts +5 -5
  72. package/dist/{deadline-BOjOxNHj.js → deadline-C4ccAuk5.js} +3 -6
  73. package/dist/deadline-C4ccAuk5.js.map +1 -0
  74. package/dist/deadline-CUGbto-y.cjs +2 -0
  75. package/dist/deadline-CUGbto-y.cjs.map +1 -0
  76. package/dist/{debug-bundle-C7UkHZ-q.js → debug-bundle-BOdYmCeV.js} +10 -3
  77. package/dist/debug-bundle-BOdYmCeV.js.map +1 -0
  78. package/dist/debug-bundle-Ex4L_LSP.cjs +2 -0
  79. package/dist/debug-bundle-Ex4L_LSP.cjs.map +1 -0
  80. package/dist/doctor.cjs +1 -1
  81. package/dist/doctor.cjs.map +1 -1
  82. package/dist/doctor.d.ts +16 -6
  83. package/dist/doctor.js +147 -52
  84. package/dist/doctor.js.map +1 -1
  85. package/dist/{emergency-queue-Zy6lNafo.js → emergency-queue-B9WZxanZ.js} +4 -4
  86. package/dist/emergency-queue-B9WZxanZ.js.map +1 -0
  87. package/dist/{emergency-queue-CNTRui5t.cjs → emergency-queue-HBpL5r3V.cjs} +2 -2
  88. package/dist/emergency-queue-HBpL5r3V.cjs.map +1 -0
  89. package/dist/error-like-B11pB4aL.js.map +1 -1
  90. package/dist/error-like-gGRx2s36.cjs.map +1 -1
  91. package/dist/{errors-Dh7kef0i.js → errors-D6bwgJtO.js} +3 -3
  92. package/dist/errors-D6bwgJtO.js.map +1 -0
  93. package/dist/{errors-tfEr48bS.cjs → errors-DCOCRdSi.cjs} +2 -2
  94. package/dist/errors-DCOCRdSi.cjs.map +1 -0
  95. package/dist/{factory-CJXVYp0R.cjs → factory-DLFDjdLv.cjs} +2 -2
  96. package/dist/factory-DLFDjdLv.cjs.map +1 -0
  97. package/dist/{factory-BonqI3NL.js → factory-e9Qo3K0z.js} +13 -13
  98. package/dist/factory-e9Qo3K0z.js.map +1 -0
  99. package/dist/fixed-window-CvESpFYV.cjs.map +1 -1
  100. package/dist/fixed-window-Dq3MLUUv.js.map +1 -1
  101. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  102. package/dist/global-scope-D9I8s-oN.js.map +1 -1
  103. package/dist/guards-Cidk71ME.js.map +1 -1
  104. package/dist/guards-nJ70syPt.cjs.map +1 -1
  105. package/dist/{identity-Cxgj6pZX.cjs → identity-BlvlgjrU.cjs} +2 -2
  106. package/dist/identity-BlvlgjrU.cjs.map +1 -0
  107. package/dist/{identity-DT5VmvXy.js → identity-BrQp_5J5.js} +19 -19
  108. package/dist/identity-BrQp_5J5.js.map +1 -0
  109. package/dist/index.cjs +1 -1
  110. package/dist/index.cjs.map +1 -1
  111. package/dist/index.d.ts +112 -79
  112. package/dist/index.js +783 -635
  113. package/dist/index.js.map +1 -1
  114. package/dist/{indexeddb-storage-CIoW21Xd.cjs → indexeddb-storage-CtLvZH1r.cjs} +2 -2
  115. package/dist/indexeddb-storage-CtLvZH1r.cjs.map +1 -0
  116. package/dist/{indexeddb-storage-BJVtiQKm.js → indexeddb-storage-DLXQzAGh.js} +4 -4
  117. package/dist/indexeddb-storage-DLXQzAGh.js.map +1 -0
  118. package/dist/{interactions-DTgKy_6K.js → interactions-B6z2I4tU.js} +3 -3
  119. package/dist/interactions-B6z2I4tU.js.map +1 -0
  120. package/dist/{interactions-fEN6FbVo.cjs → interactions-P6pz08Jn.cjs} +2 -2
  121. package/dist/interactions-P6pz08Jn.cjs.map +1 -0
  122. package/dist/{journey-CuJrHzEg.js → journey-35yCMNFo.js} +20 -19
  123. package/dist/journey-35yCMNFo.js.map +1 -0
  124. package/dist/journey-DAGh5h9k.cjs +2 -0
  125. package/dist/journey-DAGh5h9k.cjs.map +1 -0
  126. package/dist/keys-BHhw_0Wh.cjs.map +1 -1
  127. package/dist/keys-BU9j5YqW.js.map +1 -1
  128. package/dist/{library-console-D2GY9Or6.cjs → library-console-BFWEuQsl.cjs} +2 -2
  129. package/dist/library-console-BFWEuQsl.cjs.map +1 -0
  130. package/dist/{library-console-C1m6g1BR.js → library-console-Dl_Ly6DQ.js} +2 -2
  131. package/dist/library-console-Dl_Ly6DQ.js.map +1 -0
  132. package/dist/{library-request-1BX_UlaX.cjs → library-request-Da-CHKzT.cjs} +2 -2
  133. package/dist/library-request-Da-CHKzT.cjs.map +1 -0
  134. package/dist/{library-request-BQBT9N9Q.js → library-request-nI6pvI6I.js} +2 -2
  135. package/dist/library-request-nI6pvI6I.js.map +1 -0
  136. package/dist/{lifecycle-2EtUaRpo.cjs → lifecycle-BGGOcN4N.cjs} +2 -2
  137. package/dist/lifecycle-BGGOcN4N.cjs.map +1 -0
  138. package/dist/{lifecycle-BaKx_-32.js → lifecycle-CZ6RRXc6.js} +2 -2
  139. package/dist/lifecycle-CZ6RRXc6.js.map +1 -0
  140. package/dist/{log-record-i9zOTkpQ.cjs → log-record-D7bA1RPb.cjs} +2 -2
  141. package/dist/log-record-D7bA1RPb.cjs.map +1 -0
  142. package/dist/{log-record-CAoGBBf3.js → log-record-DIA6McNr.js} +2 -2
  143. package/dist/log-record-DIA6McNr.js.map +1 -0
  144. package/dist/{long-frames-Czk7IupC.js → long-frames-430_85Da.js} +8 -6
  145. package/dist/long-frames-430_85Da.js.map +1 -0
  146. package/dist/long-frames-Dd8tsi2U.cjs +2 -0
  147. package/dist/long-frames-Dd8tsi2U.cjs.map +1 -0
  148. package/dist/models/batch.d.ts +14 -15
  149. package/dist/models/bus.d.ts +24 -24
  150. package/dist/models/config.d.ts +402 -216
  151. package/dist/models/drop.d.ts +13 -11
  152. package/dist/models/health.d.ts +13 -13
  153. package/dist/models/log-record.d.ts +13 -14
  154. package/dist/models/metric.d.ts +82 -17
  155. package/dist/models/plugin.d.ts +13 -13
  156. package/dist/models/replay.d.ts +60 -0
  157. package/dist/models/serializer.d.ts +2 -3
  158. package/dist/models/stats.d.ts +2 -2
  159. package/dist/models/storage.d.ts +12 -11
  160. package/dist/{network-DBNwApoF.js → network-C7SkLf4v.js} +12 -12
  161. package/dist/network-C7SkLf4v.js.map +1 -0
  162. package/dist/{network-xbbuvG_6.cjs → network-pEX3PAJv.cjs} +2 -2
  163. package/dist/network-pEX3PAJv.cjs.map +1 -0
  164. package/dist/openfin-Bxelt0yg.js.map +1 -1
  165. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  166. package/dist/otlp-2MCrC3kd.cjs +2 -0
  167. package/dist/otlp-2MCrC3kd.cjs.map +1 -0
  168. package/dist/{otlp-BTJdIa6F.js → otlp-COq033e3.js} +25 -32
  169. package/dist/otlp-COq033e3.js.map +1 -0
  170. package/dist/patch-BX8KrPCT.cjs.map +1 -1
  171. package/dist/patch-UdPz1ea8.js.map +1 -1
  172. package/dist/{platform-C2Ez5kDc.cjs → platform-12uR7kBQ.cjs} +2 -2
  173. package/dist/platform-12uR7kBQ.cjs.map +1 -0
  174. package/dist/{platform-DkcuXwe-.js → platform-CVewe4wQ.js} +7 -7
  175. package/dist/platform-CVewe4wQ.js.map +1 -0
  176. package/dist/profiler-BVWIOgnq.js +310 -0
  177. package/dist/profiler-BVWIOgnq.js.map +1 -0
  178. package/dist/profiler-eVCknCzS.cjs +2 -0
  179. package/dist/profiler-eVCknCzS.cjs.map +1 -0
  180. package/dist/profiler-frames-CLXlT_xL.js +86 -0
  181. package/dist/profiler-frames-CLXlT_xL.js.map +1 -0
  182. package/dist/profiler-frames-Dg2OebB2.cjs +2 -0
  183. package/dist/profiler-frames-Dg2OebB2.cjs.map +1 -0
  184. package/dist/{remote-rules-Cfb4K-Nl.js → remote-rules-BJGDJGwA.js} +27 -27
  185. package/dist/remote-rules-BJGDJGwA.js.map +1 -0
  186. package/dist/{remote-rules-vzvk7aKf.cjs → remote-rules-CJD3ToVk.cjs} +2 -2
  187. package/dist/remote-rules-CJD3ToVk.cjs.map +1 -0
  188. package/dist/replay-0zAJv9T3.js +338 -0
  189. package/dist/replay-0zAJv9T3.js.map +1 -0
  190. package/dist/replay-DomJpXqW.cjs +2 -0
  191. package/dist/replay-DomJpXqW.cjs.map +1 -0
  192. package/dist/{reports-Dk2YhKIh.cjs → reports-BsbqmP8h.cjs} +2 -2
  193. package/dist/reports-BsbqmP8h.cjs.map +1 -0
  194. package/dist/{reports-TA-zInnq.js → reports-BuXekPOS.js} +3 -3
  195. package/dist/reports-BuXekPOS.js.map +1 -0
  196. package/dist/{resource-timing-BLv3EA2A.js → resource-timing-CXGHwFRD.js} +4 -4
  197. package/dist/resource-timing-CXGHwFRD.js.map +1 -0
  198. package/dist/{resource-timing-Cysw1S1f.cjs → resource-timing-DkycFGDa.cjs} +2 -2
  199. package/dist/resource-timing-DkycFGDa.cjs.map +1 -0
  200. package/dist/{sampling-Ckh2yW9k.cjs → sampling-Dd0wllyq.cjs} +2 -2
  201. package/dist/sampling-Dd0wllyq.cjs.map +1 -0
  202. package/dist/{sampling-C4VV-1MS.js → sampling-UUDbi3K0.js} +9 -9
  203. package/dist/sampling-UUDbi3K0.js.map +1 -0
  204. package/dist/{sanitize-6ymPlVvP.js → sanitize-CNmsD9r3.js} +2 -2
  205. package/dist/sanitize-CNmsD9r3.js.map +1 -0
  206. package/dist/{sanitize-BAWzkZt0.cjs → sanitize-ChLn97Ch.cjs} +2 -2
  207. package/dist/sanitize-ChLn97Ch.cjs.map +1 -0
  208. package/dist/{select-ZF4by-lF.cjs → select-CTk-K5mG.cjs} +3 -3
  209. package/dist/select-CTk-K5mG.cjs.map +1 -0
  210. package/dist/{select-xtQaenIi.js → select-DPv_j6wq.js} +61 -61
  211. package/dist/select-DPv_j6wq.js.map +1 -0
  212. package/dist/{sender-CiMHC9YG.js → sender-15zEsZpr.js} +61 -60
  213. package/dist/sender-15zEsZpr.js.map +1 -0
  214. package/dist/sender-Bfpv9tad.cjs +2 -0
  215. package/dist/sender-Bfpv9tad.cjs.map +1 -0
  216. package/dist/storage/context-storage.d.ts +34 -33
  217. package/dist/storage/emergency-queue.d.ts +9 -9
  218. package/dist/storage/eviction.d.ts +12 -12
  219. package/dist/storage/factory.d.ts +8 -7
  220. package/dist/storage/gap.d.ts +6 -6
  221. package/dist/storage/idb-driver.d.ts +31 -32
  222. package/dist/storage/indexeddb-storage.d.ts +26 -27
  223. package/dist/storage/keys.d.ts +7 -7
  224. package/dist/storage/local-storage.d.ts +38 -38
  225. package/dist/storage/memory-storage.d.ts +21 -22
  226. package/dist/storage/persistence.d.ts +1 -1
  227. package/dist/storage-BA9RqRO-.cjs.map +1 -1
  228. package/dist/storage-DZwed89z.js.map +1 -1
  229. package/dist/{storm-VR024_QN.js → storm-BTSNTIWI.js} +2 -2
  230. package/dist/storm-BTSNTIWI.js.map +1 -0
  231. package/dist/{storm-CYi9Swpx.cjs → storm-D0_qZOEg.cjs} +2 -2
  232. package/dist/storm-D0_qZOEg.cjs.map +1 -0
  233. package/dist/transport/compression.d.ts +2 -2
  234. package/dist/transport/errors.d.ts +7 -7
  235. package/dist/transport/exit-flush.d.ts +39 -39
  236. package/dist/transport/headers.d.ts +2 -2
  237. package/dist/transport/http-transport.d.ts +28 -27
  238. package/dist/transport/memory-transport.d.ts +6 -6
  239. package/dist/transport/retry-engine.d.ts +35 -34
  240. package/dist/transport/serializers/ecs.d.ts +1 -1
  241. package/dist/transport/serializers/otlp-metrics.d.ts +1 -1
  242. package/dist/transport/serializers/otlp-traces.d.ts +1 -1
  243. package/dist/transport/serializers/otlp.d.ts +16 -16
  244. package/dist/transport/serializers/select.d.ts +7 -7
  245. package/dist/transport/status-transport.d.ts +20 -20
  246. package/dist/transport/worker-protocol.d.ts +3 -3
  247. package/dist/types-BAerHgCq.js.map +1 -1
  248. package/dist/types-C7WNpnG1.cjs.map +1 -1
  249. package/dist/{unclean-exit-DFUN57wY.cjs → unclean-exit-ClGzrc2A.cjs} +2 -2
  250. package/dist/unclean-exit-ClGzrc2A.cjs.map +1 -0
  251. package/dist/{unclean-exit-CwcUhFOn.js → unclean-exit-Cob_jyTv.js} +2 -2
  252. package/dist/unclean-exit-Cob_jyTv.js.map +1 -0
  253. package/dist/unref-CU9Nyz_9.cjs +2 -0
  254. package/dist/unref-CU9Nyz_9.cjs.map +1 -0
  255. package/dist/unref-DgHPQeWv.js +7 -0
  256. package/dist/unref-DgHPQeWv.js.map +1 -0
  257. package/dist/user-timing-CdYqx3PF.cjs +2 -0
  258. package/dist/user-timing-CdYqx3PF.cjs.map +1 -0
  259. package/dist/{user-timing-_jZIhDKI.js → user-timing-DgHubxCI.js} +5 -3
  260. package/dist/user-timing-DgHubxCI.js.map +1 -0
  261. package/dist/utils/console.d.ts +2 -2
  262. package/dist/utils/deadline.d.ts +4 -4
  263. package/dist/utils/error-like.d.ts +7 -7
  264. package/dist/utils/fixed-window.d.ts +9 -8
  265. package/dist/utils/global-scope.d.ts +8 -8
  266. package/dist/utils/guards.d.ts +2 -2
  267. package/dist/utils/identity.d.ts +17 -17
  268. package/dist/utils/library-console.d.ts +4 -4
  269. package/dist/utils/library-request.d.ts +10 -10
  270. package/dist/utils/lock.d.ts +10 -9
  271. package/dist/utils/openfin.d.ts +5 -5
  272. package/dist/utils/patch.d.ts +6 -6
  273. package/dist/utils/platform.d.ts +13 -11
  274. package/dist/utils/sanitize.d.ts +4 -4
  275. package/dist/utils/timer.d.ts +1 -1
  276. package/dist/utils/tracing.d.ts +38 -38
  277. package/dist/utils/unref.d.ts +3 -3
  278. package/dist/{web-socket-BWUoqBh8.cjs → web-socket-BTuvYoJI.cjs} +2 -2
  279. package/dist/web-socket-BTuvYoJI.cjs.map +1 -0
  280. package/dist/{web-socket-CV7yIMnm.js → web-socket-DthJuSAg.js} +4 -4
  281. package/dist/web-socket-DthJuSAg.js.map +1 -0
  282. package/dist/web-vitals-Ch5BpDmo.cjs +2 -0
  283. package/dist/web-vitals-Ch5BpDmo.cjs.map +1 -0
  284. package/dist/web-vitals-CsGCWnUr.js +77 -0
  285. package/dist/web-vitals-CsGCWnUr.js.map +1 -0
  286. package/dist/{worker-protocol-CrsdSDLn.js → worker-protocol-B0_8rWy5.js} +4 -4
  287. package/dist/worker-protocol-B0_8rWy5.js.map +1 -0
  288. package/dist/{worker-protocol-Bai7GAIA.cjs → worker-protocol-BjzFORfq.cjs} +2 -2
  289. package/dist/worker-protocol-BjzFORfq.cjs.map +1 -0
  290. package/dist/worker-server-4en-Lt-3.cjs +2 -0
  291. package/dist/worker-server-4en-Lt-3.cjs.map +1 -0
  292. package/dist/{worker-server-Dp5HYm4b.js → worker-server-Cne9MX9I.js} +8 -8
  293. package/dist/{worker-server-Dp5HYm4b.js.map → worker-server-Cne9MX9I.js.map} +1 -1
  294. package/dist/worker-transport-B-GF4Aqn.cjs +2 -0
  295. package/dist/worker-transport-B-GF4Aqn.cjs.map +1 -0
  296. package/dist/{worker-transport-D6jtgpqN.js → worker-transport-C3SjJAEC.js} +62 -61
  297. package/dist/worker-transport-C3SjJAEC.js.map +1 -0
  298. package/package.json +8 -2
  299. package/dist/batch-C8OcWR2L.cjs.map +0 -1
  300. package/dist/batch-CL9uWYY3.js.map +0 -1
  301. package/dist/bus-BZ0GldpT.js.map +0 -1
  302. package/dist/bus-VWlmM5xs.cjs +0 -2
  303. package/dist/bus-VWlmM5xs.cjs.map +0 -1
  304. package/dist/console-BPZCuSLc.cjs.map +0 -1
  305. package/dist/console-BeCF7n59.js.map +0 -1
  306. package/dist/constants-DqKJH_MP.cjs +0 -2
  307. package/dist/constants-DqKJH_MP.cjs.map +0 -1
  308. package/dist/constants-zyrqveN4.js +0 -304
  309. package/dist/constants-zyrqveN4.js.map +0 -1
  310. package/dist/deadline-BOjOxNHj.js.map +0 -1
  311. package/dist/deadline-XSnm95pg.cjs +0 -2
  312. package/dist/deadline-XSnm95pg.cjs.map +0 -1
  313. package/dist/debug-bundle-BzJNpbF0.cjs +0 -2
  314. package/dist/debug-bundle-BzJNpbF0.cjs.map +0 -1
  315. package/dist/debug-bundle-C7UkHZ-q.js.map +0 -1
  316. package/dist/emergency-queue-CNTRui5t.cjs.map +0 -1
  317. package/dist/emergency-queue-Zy6lNafo.js.map +0 -1
  318. package/dist/errors-Dh7kef0i.js.map +0 -1
  319. package/dist/errors-tfEr48bS.cjs.map +0 -1
  320. package/dist/factory-BonqI3NL.js.map +0 -1
  321. package/dist/factory-CJXVYp0R.cjs.map +0 -1
  322. package/dist/identity-Cxgj6pZX.cjs.map +0 -1
  323. package/dist/identity-DT5VmvXy.js.map +0 -1
  324. package/dist/indexeddb-storage-BJVtiQKm.js.map +0 -1
  325. package/dist/indexeddb-storage-CIoW21Xd.cjs.map +0 -1
  326. package/dist/interactions-DTgKy_6K.js.map +0 -1
  327. package/dist/interactions-fEN6FbVo.cjs.map +0 -1
  328. package/dist/journey-CuJrHzEg.js.map +0 -1
  329. package/dist/journey-pffMVMfa.cjs +0 -2
  330. package/dist/journey-pffMVMfa.cjs.map +0 -1
  331. package/dist/library-console-C1m6g1BR.js.map +0 -1
  332. package/dist/library-console-D2GY9Or6.cjs.map +0 -1
  333. package/dist/library-request-1BX_UlaX.cjs.map +0 -1
  334. package/dist/library-request-BQBT9N9Q.js.map +0 -1
  335. package/dist/lifecycle-2EtUaRpo.cjs.map +0 -1
  336. package/dist/lifecycle-BaKx_-32.js.map +0 -1
  337. package/dist/log-record-CAoGBBf3.js.map +0 -1
  338. package/dist/log-record-i9zOTkpQ.cjs.map +0 -1
  339. package/dist/long-frames-BVg4i5SC.cjs +0 -2
  340. package/dist/long-frames-BVg4i5SC.cjs.map +0 -1
  341. package/dist/long-frames-Czk7IupC.js.map +0 -1
  342. package/dist/network-DBNwApoF.js.map +0 -1
  343. package/dist/network-xbbuvG_6.cjs.map +0 -1
  344. package/dist/otlp-BDvFrLnc.cjs +0 -2
  345. package/dist/otlp-BDvFrLnc.cjs.map +0 -1
  346. package/dist/otlp-BTJdIa6F.js.map +0 -1
  347. package/dist/platform-C2Ez5kDc.cjs.map +0 -1
  348. package/dist/platform-DkcuXwe-.js.map +0 -1
  349. package/dist/remote-rules-Cfb4K-Nl.js.map +0 -1
  350. package/dist/remote-rules-vzvk7aKf.cjs.map +0 -1
  351. package/dist/reports-Dk2YhKIh.cjs.map +0 -1
  352. package/dist/reports-TA-zInnq.js.map +0 -1
  353. package/dist/resource-timing-BLv3EA2A.js.map +0 -1
  354. package/dist/resource-timing-Cysw1S1f.cjs.map +0 -1
  355. package/dist/sampling-C4VV-1MS.js.map +0 -1
  356. package/dist/sampling-Ckh2yW9k.cjs.map +0 -1
  357. package/dist/sanitize-6ymPlVvP.js.map +0 -1
  358. package/dist/sanitize-BAWzkZt0.cjs.map +0 -1
  359. package/dist/select-ZF4by-lF.cjs.map +0 -1
  360. package/dist/select-xtQaenIi.js.map +0 -1
  361. package/dist/sender-CiMHC9YG.js.map +0 -1
  362. package/dist/sender-D5wBoXA8.cjs +0 -2
  363. package/dist/sender-D5wBoXA8.cjs.map +0 -1
  364. package/dist/storm-CYi9Swpx.cjs.map +0 -1
  365. package/dist/storm-VR024_QN.js.map +0 -1
  366. package/dist/unclean-exit-CwcUhFOn.js.map +0 -1
  367. package/dist/unclean-exit-DFUN57wY.cjs.map +0 -1
  368. package/dist/user-timing-C9kfRq3J.cjs +0 -2
  369. package/dist/user-timing-C9kfRq3J.cjs.map +0 -1
  370. package/dist/user-timing-_jZIhDKI.js.map +0 -1
  371. package/dist/web-socket-BWUoqBh8.cjs.map +0 -1
  372. package/dist/web-socket-CV7yIMnm.js.map +0 -1
  373. package/dist/web-vitals-Bq4WFHQo.js +0 -52
  374. package/dist/web-vitals-Bq4WFHQo.js.map +0 -1
  375. package/dist/web-vitals-DFuoTQbZ.cjs +0 -2
  376. package/dist/web-vitals-DFuoTQbZ.cjs.map +0 -1
  377. package/dist/worker-protocol-Bai7GAIA.cjs.map +0 -1
  378. package/dist/worker-protocol-CrsdSDLn.js.map +0 -1
  379. package/dist/worker-server-BrIYkfoa.cjs +0 -2
  380. package/dist/worker-server-BrIYkfoa.cjs.map +0 -1
  381. package/dist/worker-transport-Bwej4N2e.cjs +0 -2
  382. package/dist/worker-transport-Bwej4N2e.cjs.map +0 -1
  383. package/dist/worker-transport-D6jtgpqN.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["DURATION_PRECISION","timeSync","timeAsync","DEFER_IDLE_TIMEOUT_MS","DEFER_QUEUE_LIMIT","CAPTURE_NAMESPACE","STORAGE_NAMESPACE","DIAGNOSTICS_NAMESPACE","isErrorLike","ERROR_OWN_KEYS","isDataField","isObject","DEFAULT_METRIC_UNIT","METRIC_KEYS","timeSync","timeAsync","nowUnixNano","currentUrl","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","METRIC_KEYS","METRIC_DEFAULT_BOUNDARIES","ATTR_METRIC_OVERFLOW","RECORD_LIMITS","LEVEL_ORDER","isLibraryConsole","sanitize","randomHex","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","LEVEL_ORDER","BEACON_LIMIT_BYTES","isObject","SERIALIZER_NAME_OTLP","CONSOLE_DEFAULT_STYLES","CONSOLE_DEFAULT_LEVEL","REMOTE_CAPTURE_FLAGS","RESOURCE_SLOW_MS","recordedUrl","DEFAULT_CONFIG","UNKNOWN_SERVICE_NAME","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","ATTR_DEBUG_BUFFER","DIAGNOSTIC_THROTTLE_MS","LIBRARY_LOG_PREFIX","attributeOf","ATTR_JOURNEY_ID","isActionRecord","isActionRecord","METRIC_DEFAULT_BOUNDARIES","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","METRIC_KEYS","SPAN_KEYS","LEVEL_BYPASS_TYPES","levelFor","LEVEL_ORDER","shouldSampleInput","currentUrl","recordedUrl","sanitizeWithSize","ATTR_SANITIZE_FAILED","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_JOURNEY_PARENT_ID","truncate","nowUnixNano","SEVERITY_NUMBER","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","isLogRecord","isLogLevel","isObject","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","SPAN_KEYS","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","isObject","recordedUrl","TELEMETRY_SDK_VERSION","DIAGNOSTICS_NAMESPACE","detectPlatform","newId","memoryStores","BROWSER_STORES","resolveIdentity","SessionTouch","sampleKey","JOURNEY_OPTIONS","JourneyEngine","truncate","sanitize","TRACE_NAMESPACE","METRIC_NAMESPACE","REMOTE_CAPTURE_FLAGS","CAPTURE_NAMESPACE","runAsLibraryRequest","isLogRecord","shouldSample","STORAGE_NAMESPACE","ATTR_BREADCRUMBS","ATTR_PAGE_URL","isObject","TRANSPORT_WORKER_TYPE","TRANSPORT_WORKER_REFUSAL","require_constants","require_log_record","require_error_like","require_guards","require_deadline","require_platform","require_library_console","require_sanitize","require_identity","require_library_request","require_batch","require_journey","require_sampling","elapsed","startedAt","finish","logger","label","duration","attributes","fail","error","timeSync$1","result","fn","timeAsync$1","queues","cancel","idle","queue","schedule","drain","owner","deadline","work","index","deferWrite","capacity","limit","diagnostics","drainDeferred","cancelDeferred","_work","LIBRARY_NAMESPACES","toError","known","value","copy","text","consoleError","reason","errorData","source","errorLike","data","count","key","field","isPlainObject","proto","levelTypeFor","namespace","own","copyPayload","payload","OneLogger","bind","options","message","name","runtime","copied","unit","type","snapshot","level","body","journey","input","hooks","keepsCrumb","protectedCrumb","dropped","safe","record","crumb","ships","asPayload","asError","shown","clean","OVERFLOW_KEY","RECORD_KEYS","cleanAttributes","copyBounds","bounds","i","isAscending","bound","fieldsOf","point","def","start","series","makeCounter","makeHistogram","Meter","intervalMs","emit","policy","instrument","instruments","one","found","valid","set","size","buckets","METHOD","ConsoleSink","settings","limits","prefix","method","details","styles","Sequence","TRACE_ID_PATTERN","SPAN_ID_PATTERN","NON_ZERO","isUsableSpanContext","context","newTraceId","newSpanId","mintAmbient","traceparent","traceId","spanId","traceFlags","toTraceContext","ambient","TraceEngine","maxAgeMs","load","spans","otel","span","spanContext","old","next","carrier","\"traceparent\"","fromOtel","ctx","kept","flags","client","BreadcrumbBuffer","recent","LEVEL_NAMES","COMPRESSION_VALUES","CREDENTIALS_VALUES","STORAGE_VALUES","IDENTITY_VALUES","BUS_MODE_VALUES","OPENFIN_ROLE_VALUES","JOURNEY_SCOPE_VALUES","CONSOLE_METHOD_VALUES","RETENTION_MODE_VALUES","BATCHING_RANGES","RETENTION_RANGES","LIMIT_RANGES","JOURNEY_AGE_RANGE","DURATION_RANGE","COUNT_RANGE","POSITIVE_RANGE","CLICK_WAIT_RANGE","POLICY_RULES","resolveDiagnosticRecords","CAPTURE_FLAG_KEYS","SANDBOX_ORIGIN","LEVEL_EXPECTED","listOf","CONSOLE_CAPTURE_EXPECTED","PATTERN_LIST_EXPECTED","TARGET_LIST_EXPECTED","ORIGIN_LIST_EXPECTED","STRING_LIST_EXPECTED","DIAGNOSTIC_RECORDS_EXPECTED","quoted","values","describeValue","reportInvalid","expected","resolveChoice","fallback","match","accepted","entry","resolveBoolean","resolveNonNegative","resolveInteger","min","max","range","resolveCacheLimit","previous","resolveRanges","given","keys","ranges","section","base","toLevel","upper","resolveLevel","resolveMinLevels","levels","raw","resolveList","entries","accept","toProcessor","toPlugin","toStringEntry","toPattern","toConsoleMethod","toOrigin","origin","toTarget","isStringRecord","resolveHeaders","isSerializer","resolveSerializer","requested","CONSOLE_STYLE_KEYS","validStyles","resolveConsoleLevel","resolveConsole","resolveSampling","resolveBus","resolveJourney","resolveRetention","resolveCaptureConsole","resolveCapture","capture","resolveResourceTiming","resolveInteractions","ignore","ignoreSelector","actionAttribute","SIGNAL_OFF","resolveSignalEndpoint","url","serializer","resolvePolicy","rules","choice","custom","resolved","resolveConfig","policies","merged","rate","maxRate","rates","ns","r","reportUnknownKeys","sectionKeys","applyResolvedConfig","target","ContextStore","DebugBuffer","enabled","maxRecords","oldest","Diagnostics","handler","throttleMs","consoleFallback","total","code","by","now","event","addCapped","list","DropReporter","config","records","batchIds","summary","id","summaries","onDrop","HoldBuffer","action","TOTAL_DURATION","PHASE_DURATION","createMeasure","startMs","open","ended","epoch","at","closePhase","sinks","outcome","fields","ERROR_ATTR_PREFIX","REDACTABLE_INDEX_KEYS","HOOK_STAGES","FIXED_KEYS","fixedOf","asAttributes","RecordBuilder","deps","minLevel","debug","forConsole","traceCtx","tracing","activeJourney","sampled","remote","seq","sequence","pageUrl","bytes","fromContext","fromProvider","fromScope","fromPayload","stages","hook","keptBytes","breadcrumbs","crumbBytes","redact","current","stage","remeasured","fixed","changed","candidate","provider","platform","identity","US_PER_MS","ROOT_NAMES","unixNano","ms","rootSpan","spanFields","CAPTURE_LOADERS","pluginIds","lastPluginId","pluginId","plugin","RUNTIME_KEY","STOPPED_KEY","SENDER_SECTIONS","DELIVERY_RESET","ROUTING_KEYS","NOTICE_CODES","captureKey","recordDetail","detail","consoleOnly","sends","ownVersion","ObservabilityRuntime","locked","mismatch","keeps","points","bus","reply","local","pinned","stopped","implicit","foundText","sameConfig","processors","probe","refused","sections","built","captures","journeyReady","Bus","rotating","shared","sender","Sender","storage","state","wire","generation","names","classes","WebSocketCapture","CaptureModule","plugins","metric","cancelled","detach","worker","frame","closing","redacted","buffered","batch","fresh","sessionId","pending","timeoutMs","update","nextId","delivery","before","oldUrls","newUrls","held","retired","live","stored","crumbs","configSummary","issues","scope","backing","createStorage","storageName","storageLimits","store","ContextStorage","clearEmergencyContext","a","b","seen","ak","bk","active","serveTransportWorker","port","onMessage","incoming","module","stop","createMemoryTransport","sent","answer","request","retryAfterMs","loggers","requireRuntime","clearPersistedLogs","configure","trimLoggerCache","setConfigurationLocked","rotateSecurityContext","getHealth","collectDebugBundle","health","getLogger","root","trace","info","warn","err","fatal","logAction","logEvent","logMetric","counter","histogram","startMeasure","timeSync","timeAsync","addBreadcrumb","setContext","setContextMap","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","token","registerWorker","registerFrame","startTrace","getTraceHeaders","flush","getQueueDepth","getStats","newSession","getDiagnosticCounters","shutdown"],"sources":["../src/utils/timer.ts","../src/core/deferred.ts","../src/core/logger.ts","../src/core/meter.ts","../src/utils/console.ts","../src/utils/sequence.ts","../src/utils/tracing.ts","../src/core/breadcrumbs.ts","../src/core/config.ts","../src/core/context.ts","../src/core/debug-buffer.ts","../src/core/diagnostics.ts","../src/core/drops.ts","../src/core/hold-buffer.ts","../src/core/measure.ts","../src/core/record.ts","../src/core/spans.ts","../src/core/runtime.ts","../src/transport/worker-entry.ts","../src/transport/memory-transport.ts","../src/index.ts"],"sourcesContent":["// src/utils/timer.ts\n//\n// Logs the duration of synchronous and asynchronous operations as metrics.\n\nimport type { CaptureLogger } from \"../capture/types\";\nimport { DURATION_PRECISION } from \"../constants\";\n\n/**\n * Calculates elapsed milliseconds rounded to configured precision.\n * @param startedAt Performance timestamp recorded at operation start.\n * @returns Elapsed duration in milliseconds.\n */\nfunction elapsed(startedAt: number): number {\n return Math.round((performance.now() - startedAt) * DURATION_PRECISION) / DURATION_PRECISION;\n}\n\n/**\n * Logs the operation duration as a histogram metric, for each outcome.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param duration Elapsed duration in milliseconds.\n * @param status Outcome status string.\n * @param attributes Optional contextual attributes.\n */\nfunction finish(\n logger: CaptureLogger,\n label: string,\n duration: number,\n status: string,\n attributes?: Record<string, unknown>,\n): void {\n logger.logMetric(`${label}.duration`, duration, \"ms\", \"histogram\", {\n status,\n ...attributes,\n });\n}\n\n/**\n * Logs an operation failure and its FAILURE duration histogram.\n * @param logger Target telemetry logger.\n * @param label Operation label.\n * @param startedAt Performance timestamp recorded at operation start.\n * @param error Caught error instance or thrown value.\n * @param attributes Optional contextual attributes.\n */\nfunction fail(\n logger: CaptureLogger,\n label: string,\n startedAt: number,\n error: unknown,\n attributes?: Record<string, unknown>,\n): void {\n // Read the duration one time. The error record and the metric then give the same value.\n const duration = elapsed(startedAt);\n logger.error(`${label} failed`, error, {\n \"action.duration_ms\": duration,\n status: \"FAILURE\",\n ...attributes,\n });\n finish(logger, label, duration, \"FAILURE\", attributes);\n}\n\n/**\n * Executes and measures the duration of a synchronous function.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param fn Synchronous function to execute.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the wrapped function.\n */\nexport function timeSync<T>(\n logger: CaptureLogger,\n label: string,\n fn: () => T,\n attributes?: Record<string, unknown>,\n): T {\n const startedAt = performance.now();\n try {\n const result = fn();\n finish(logger, label, elapsed(startedAt), \"SUCCESS\", attributes);\n return result;\n } catch (error) {\n // Throw the error again. The caller keeps its control flow.\n fail(logger, label, startedAt, error, attributes);\n throw error;\n }\n}\n\n/**\n * Executes and measures the duration of an asynchronous promise-returning function.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to execute.\n * @param attributes Optional contextual attributes.\n * @returns Promise that resolves to the result of the wrapped function.\n */\nexport async function timeAsync<T>(\n logger: CaptureLogger,\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n): Promise<T> {\n const startedAt = performance.now();\n try {\n const result = await fn();\n finish(logger, label, elapsed(startedAt), \"SUCCESS\", attributes);\n return result;\n } catch (error) {\n // Throw the error again. The caller keeps its control flow.\n fail(logger, label, startedAt, error, attributes);\n throw error;\n }\n}\n","import { DEFER_IDLE_TIMEOUT_MS, DEFER_QUEUE_LIMIT } from \"../constants\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Pending logger calls of one runtime. A stopped runtime releases each payload reference. */\ninterface DeferredQueue {\n work: (() => void)[];\n diagnostics: Diagnostics;\n draining: boolean;\n idle?: number;\n timer?: ReturnType<typeof setTimeout>;\n}\n\nconst queues = new WeakMap<object, DeferredQueue>();\n\n/** Cancels the scheduled callback before a synchronous drain or a shutdown. */\nfunction cancel(queue: DeferredQueue): void {\n const idle = queue.idle;\n if (idle !== undefined) {\n queue.diagnostics.guard(\"pipeline.crashed\", \"The idle callback could not be cancelled.\", () => {\n cancelIdleCallback(idle);\n });\n queue.idle = undefined;\n }\n\n clearTimeout(queue.timer);\n queue.timer = undefined;\n}\n\n/** Schedules one idle callback. A timer supports browsers without the idle API. */\nfunction schedule(owner: object, queue: DeferredQueue): void {\n if (typeof requestIdleCallback === \"function\" && typeof cancelIdleCallback === \"function\") {\n queue.idle = queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The idle callback could not be scheduled.\",\n () =>\n requestIdleCallback(\n (deadline) => {\n drain(owner, queue, deadline);\n },\n { timeout: DEFER_IDLE_TIMEOUT_MS },\n ),\n );\n if (queue.idle !== undefined) {\n return;\n }\n }\n\n queue.timer = setTimeout(() => {\n drain(owner, queue);\n }, 0);\n unrefTimer(queue.timer);\n}\n\n/** Builds a bounded group of calls. Reentrant calls wait for the next callback. */\nfunction drain(owner: object, queue: DeferredQueue, deadline?: IdleDeadline): void {\n if (queues.get(owner) !== queue || queue.draining) {\n return;\n }\n\n cancel(queue);\n queue.draining = true;\n const work = queue.work;\n queue.work = [];\n let index = 0;\n\n while (\n index < work.length &&\n (!deadline || (deadline.didTimeout && index === 0) || deadline.timeRemaining() > 0)\n ) {\n queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The library could not build a deferred record.\",\n work[index],\n );\n index++;\n if (queues.get(owner) !== queue) {\n return;\n }\n }\n\n queue.work = [...work.slice(index), ...queue.work];\n queue.draining = false;\n if (queue.work.length > 0) {\n schedule(owner, queue);\n } else {\n queues.delete(owner);\n }\n}\n\n/** Queues a call without reading its payload. A full queue first builds its pending calls. */\nexport function deferWrite(\n owner: object,\n work: () => void,\n diagnostics: Diagnostics,\n limit: number,\n): void {\n let queue = queues.get(owner);\n const capacity = limit > 0 ? Math.min(limit, DEFER_QUEUE_LIMIT) : DEFER_QUEUE_LIMIT;\n if (queue && queue.work.length >= capacity && !queue.draining) {\n drain(owner, queue);\n queue = queues.get(owner);\n }\n\n if (queue) {\n if (queue.work.length >= capacity) {\n diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n queue.work.push(work);\n return;\n }\n\n queue = { work: [work], diagnostics, draining: false };\n queues.set(owner, queue);\n schedule(owner, queue);\n}\n\n/** Builds pending calls before a flush, a session change or a delivery identity change. */\nexport function drainDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n drain(owner, queue);\n }\n}\n\n/** Releases calls that a hook queues during shutdown. Those calls have no built records. */\nexport function cancelDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n cancel(queue);\n queues.delete(owner);\n for (const _work of queue.work) {\n queue.diagnostics.count(\"record.dropped_by_ceiling\");\n }\n queue.work = [];\n }\n}\n","// src/core/logger.ts\n//\n// This module gives a namespaced logger facade. It has scoped log methods and metric timers.\n\nimport {\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_SANITIZE_FAILED,\n CAPTURE_NAMESPACE,\n DEFAULT_METRIC_UNIT,\n DIAGNOSTICS_NAMESPACE,\n METRIC_KEYS,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport {\n type LogLevel,\n type LogRecord,\n type LogType,\n type MetricType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { ERROR_OWN_KEYS, isDataField, isErrorLike } from \"../utils/error-like\";\nimport { isObject } from \"../utils/guards\";\nimport { timeAsync, timeSync } from \"../utils/timer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { DropReason, RecordSnapshot } from \"./record\";\nimport { deferWrite } from \"./deferred\";\nimport { currentUrl } from \"../utils/platform\";\nimport type { ObservabilityRuntime } from \"./runtime\";\n\n/** Namespaces of the library. Their records have log.type \"system\". */\nconst LIBRARY_NAMESPACES: readonly string[] = [\n CAPTURE_NAMESPACE,\n STORAGE_NAMESPACE,\n DIAGNOSTICS_NAMESPACE,\n];\n\n/** Configuration options for a scoped OneLogger instance. */\nexport interface OneLoggerOptions {\n /** Contextual attributes merged into all records emitted by this logger. */\n scopedContext?: Record<string, unknown>;\n}\n\n/**\n * Normalizes an unknown thrown value into an Error instance.\n * An error becomes a copy with its name, message and stack.\n * @param value Caught error instance or primitive value.\n * @param diagnostics Diagnostics reporter.\n * @returns Normalized Error instance.\n */\nfunction toError(value: unknown, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof and from each property read. A Proxy around\n // an Error passes instanceof. Read its fields here, inside the guard.\n const known = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n (): Error | undefined => {\n if (!(value instanceof Error) && !isErrorLike(value)) {\n return undefined;\n }\n\n const copy = new Error(value.message);\n copy.name = value.name;\n copy.stack = value.stack;\n return copy;\n },\n );\n\n if (known) {\n return known;\n }\n\n // String() throws on a null-prototype object and on a toString that throws.\n // log.error() runs inside a consumer catch block. It must not throw out of it.\n const text = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not convert the error reason to text.\",\n () => String(value),\n );\n\n return new Error(text ?? typeof value);\n}\n\n/**\n * Gives the error that the console prints. The console shows the cause and the own fields\n * of a real Error. The record keeps the copy from toError().\n * @param reason Error reason.\n * @param copy Normalized copy of the reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The reason if it is an Error, or the copy.\n */\nfunction consoleError(reason: unknown, copy: Error, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof.\n const original = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n () => (reason instanceof Error ? reason : copy),\n );\n\n return original ?? copy;\n}\n\n/**\n * Reads the data of an error reason for the error.data attribute.\n * It keeps only the own fields with a string, number or boolean value.\n * @param value Error reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The fields of an object reason, a primitive reason, or undefined.\n * A string reason gives undefined. error.message already holds it.\n */\nfunction errorData(value: unknown, diagnostics: Diagnostics): unknown {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\") {\n return value;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n return diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the properties of the error reason.\",\n () => {\n const source = value as Record<string, unknown>;\n const errorLike = isErrorLike(value);\n const data: Record<string, unknown> = {};\n let count = 0;\n\n // An object field, for example the config of an AxiosError, holds credentials.\n for (const key of Object.keys(source)) {\n const field = source[key];\n if ((!errorLike || !ERROR_OWN_KEYS.has(key)) && isDataField(field)) {\n data[key] = field;\n count++;\n }\n }\n\n return count === 0 ? undefined : data;\n },\n );\n}\n\n/**\n * Tests if a value is an attribute bag, not an error reason. The test works across realms.\n * An object literal from an iframe has the Object.prototype of that realm.\n * The prototype of that Object.prototype is also null.\n * @param value Value found in the error slot.\n * @returns True if the value is a plain object.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!isObject(value)) {\n return false;\n }\n if (value instanceof Error) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n\n/**\n * Selects the log.type of the level methods for a namespace.\n * @param namespace Logger namespace.\n * @returns \"system\" for a namespace of the library, \"log\" for each other namespace.\n */\nfunction levelTypeFor(namespace: string): LogType {\n const library = LIBRARY_NAMESPACES.some(\n (own) => namespace === own || namespace.startsWith(`${own}.`),\n );\n\n return library ? \"system\" : \"log\";\n}\n\n/**\n * Copies a caller payload. A Proxy with a throwing trap must not throw out of a log call.\n * @param payload Caller payload.\n * @param diagnostics Diagnostics reporter.\n * @returns The copy, or a marker attribute when the library cannot read the payload.\n */\nfunction copyPayload(\n payload: Record<string, unknown> | undefined,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n if (payload === undefined) {\n return {};\n }\n\n const copied = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the payload.\",\n () => ({ ...payload }),\n );\n\n return copied ?? { [ATTR_SANITIZE_FAILED]: true };\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /** log.type of the level methods. It is \"system\" only for the namespaces of the library. */\n private readonly levelType: LogType;\n\n /**\n * @param bind Returns the runtime for each write.\n * A logger that exists before configure() writes to the configured runtime.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context options.\n */\n constructor(\n private readonly bind: () => ObservabilityRuntime,\n readonly namespace: string,\n private readonly options: OneLoggerOptions = {},\n ) {\n this.levelType = levelTypeFor(namespace);\n }\n\n /**\n * Creates a child logger with a nested namespace and merged scoped context.\n * @param namespace Sub-namespace appended with dot notation.\n * @param options Additional scoped context attributes.\n * @returns Nested child OneLogger instance.\n */\n child(namespace: string, options: OneLoggerOptions = {}): OneLogger {\n return new OneLogger(this.bind, `${this.namespace}.${namespace}`, {\n scopedContext: {\n ...this.options.scopedContext,\n ...options.scopedContext,\n },\n });\n }\n\n /**\n * Logs a trace-level debug record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n trace = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"TRACE\", this.levelType, message, payload);\n };\n\n /**\n * Logs a debug-level record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n debug = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"DEBUG\", this.levelType, message, payload);\n };\n\n /**\n * Logs an informational record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n info = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", this.levelType, message, payload);\n };\n\n /**\n * Logs a warning record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n warn = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"WARN\", this.levelType, message, payload);\n };\n\n /**\n * Logs an error record with the breadcrumb history. If payload is absent, a plain\n * object in the error slot becomes the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n error = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"ERROR\", message, error, payload);\n };\n\n /**\n * Logs a fatal error record. If payload is absent, a plain object in the error slot\n * becomes the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n fatal = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"FATAL\", message, error, payload);\n };\n\n /**\n * Logs one user action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\n logAction = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"action\", name, payload);\n };\n\n /**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\n logEvent = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"event\", name, payload);\n };\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric identifier.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attributes Optional metric attributes.\n */\n logMetric = (\n name: string,\n value: number,\n unit = DEFAULT_METRIC_UNIT,\n type: MetricType = \"gauge\",\n attributes?: Record<string, unknown>,\n ): void => {\n // NaN and Infinity become null in JSON. A backend then reads a false zero.\n if (!Number.isFinite(value)) {\n this.bind().diagnostics.report(\n \"record.dropped_malformed\",\n \"The metric value is not a finite number. The library dropped the metric.\",\n { \"metric.name\": name },\n );\n return;\n }\n\n const runtime = this.bind();\n this.submit(runtime, \"INFO\", \"metric\", (snapshot) => {\n // Copy the caller attributes before adding metric fields. The metric fields must win.\n const copied = copyPayload(attributes, runtime.diagnostics);\n const payload = {\n ...copied,\n \"metric.name\": name,\n \"metric.value\": value,\n \"metric.unit\": unit,\n \"metric.type\": type,\n [METRIC_KEYS.attributeKeys]: Object.keys(copied),\n };\n this.writeNow(runtime, \"INFO\", \"metric\", name, payload, true, snapshot);\n });\n };\n\n /**\n * Times a synchronous function execution and records a duration metric.\n * @param label Metric name prefix.\n * @param fn Synchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the timed function.\n */\n timeSync = <T>(label: string, fn: () => T, attributes?: Record<string, unknown>): T =>\n timeSync(this, label, fn, attributes);\n\n /**\n * Times an asynchronous function execution and records a duration metric.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Promise that resolves to the result of the timed function.\n */\n timeAsync = <T>(\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n ): Promise<T> => timeAsync(this, label, fn, attributes);\n\n /**\n * Builds and emits a standard log record. It also prints the record to the console.\n * @param level Severity level.\n * @param type Record classification.\n * @param body Primary message.\n * @param payload Optional contextual attributes.\n */\n private write(\n level: LogLevel,\n type: LogType,\n body: string,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, type, (snapshot) => {\n this.writeNow(runtime, level, type, body, payload, false, snapshot);\n });\n }\n\n /** Runs a call at once or queues it without reading its payload. */\n private submit(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n work: (snapshot?: RecordSnapshot) => void,\n ): void {\n if (runtime.isDestroyed()) {\n return;\n }\n if (runtime.isRotating()) {\n runtime.diagnostics.count(\"record.dropped_during_rotation\");\n return;\n }\n\n if (\n runtime.config.payloadMode === \"defer\" &&\n runtime.config.enabled &&\n !runtime.config.debugBuffer.enabled &&\n // A deferred diagnostic record builds outside its loop guard. A hook failure then loops.\n this.namespace !== DIAGNOSTICS_NAMESPACE\n ) {\n if (\n !runtime.builder.isEnabled(level, this.namespace, type) &&\n !this.mirrors(runtime, level)\n ) {\n return;\n }\n\n const journey = runtime.journey.current();\n const snapshot: RecordSnapshot = {\n timeUnixNano: nowUnixNano(),\n trace: runtime.tracing.resolve(),\n journey: journey ? { ...journey } : null,\n context: runtime.context.getAll(),\n url: currentUrl(runtime.diagnostics),\n };\n deferWrite(\n runtime,\n () => {\n work(snapshot);\n },\n runtime.diagnostics,\n runtime.config.buffering.maxPendingRecords,\n );\n return;\n }\n\n work();\n }\n\n /** Builds a standard record from a call whose payload is now ready to read. */\n private writeNow(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n body: string,\n payload: Record<string, unknown> | undefined,\n copied: boolean,\n snapshot?: RecordSnapshot,\n ): void {\n // minLevel limits what the library sends. The console level limits what it prints.\n // minLevel does not apply to an action or a metric. The debug buffer keeps a record below it.\n const keepsDropped = runtime.config.enabled && runtime.config.debugBuffer.enabled;\n if (!keepsDropped && !runtime.builder.isEnabled(level, this.namespace, type)) {\n if (this.mirrors(runtime, level)) {\n this.print(runtime, level, body, payload, undefined, null, undefined, snapshot);\n }\n\n return;\n }\n\n const input = {\n snapshot,\n level,\n type,\n body,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: copied ? payload : copyPayload(payload, runtime.diagnostics),\n };\n const { record, dropped } = runtime.builder.build(input);\n const hooks = Boolean(runtime.config.redact) || runtime.config.processors.length > 0;\n // Run the hooks on a sampled-out record only if a breadcrumb keeps its message.\n const keepsCrumb = type !== \"metric\" && runtime.config.capturePolicy.breadcrumbs > 0;\n const protectedCrumb =\n dropped === \"sampling\" && hooks && keepsCrumb\n ? runtime.builder.build(input, true)\n : undefined;\n const safe = record ?? protectedCrumb?.record ?? null;\n const crumb = safe ? safe.body : dropped === \"sampling\" && !hooks ? body : undefined;\n if (keepsCrumb && crumb !== undefined) {\n runtime.breadcrumbs.push({\n t: snapshot ? Number(snapshot.timeUnixNano.slice(0, -6)) : Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: crumb,\n });\n }\n this.print(\n runtime,\n level,\n body,\n payload,\n undefined,\n safe,\n protectedCrumb?.dropped ?? dropped,\n snapshot,\n );\n runtime.emit(record);\n }\n\n /**\n * Builds and emits an error record with breadcrumbs. It also prints the record to the console.\n * @param level Severity level (\"ERROR\" or \"FATAL\").\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n private writeError(\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, this.levelType, (snapshot) => {\n this.writeErrorNow(runtime, level, message, error, payload, snapshot);\n });\n }\n\n /** Builds an error record after the deferred queue releases its payload. */\n private writeErrorNow(\n runtime: ObservabilityRuntime,\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload: Record<string, unknown> | undefined,\n snapshot?: RecordSnapshot,\n ): void {\n const ships = runtime.builder.isEnabled(level, this.namespace);\n\n if (!ships && !this.mirrors(runtime, level)) {\n return;\n }\n\n // All sibling methods take (name, payload?). Callers expect log.error(\"failed\", { id }).\n // As an error reason, that object puts \"[object Object]\" in error.message.\n // It also drops the caller fields. A Proxy in the error slot can throw on the test.\n const asPayload =\n payload === undefined &&\n (runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error slot.\",\n () => isPlainObject(error),\n ) ??\n false);\n const attributes = asPayload ? (error as Record<string, unknown>) : payload;\n const reason = asPayload ? undefined : error;\n const asError = reason === undefined ? undefined : toError(reason, runtime.diagnostics);\n const shown =\n asError === undefined ? undefined : consoleError(reason, asError, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, shown, null, undefined, snapshot);\n return;\n }\n\n const data = asError ? errorData(reason, runtime.diagnostics) : undefined;\n\n const { record, dropped } = runtime.builder.build({\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(attributes, runtime.diagnostics),\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n ...(data === undefined ? {} : { [ATTR_ERROR_DATA]: data }),\n [ATTR_BREADCRUMBS]: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, shown, record, dropped, snapshot);\n runtime.emit(record);\n }\n\n /**\n * Prints one log line. With a redact hook, the line shows only what redact returned.\n * A host can record console arguments. The console must not show what redact removes.\n * @param runtime Runtime of this write.\n * @param level Severity level.\n * @param message Primary message.\n * @param payload Caller payload.\n * @param error Error of an error call.\n * @param record Built record, or null if the library did not build it or redact dropped it.\n * @param dropped Reason of the drop when the builder dropped the record.\n */\n private print(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n message: string,\n payload: Record<string, unknown> | undefined,\n error: Error | undefined,\n record: LogRecord | null,\n dropped?: DropReason,\n snapshot?: RecordSnapshot,\n ): void {\n if (!runtime.config.redact && runtime.config.processors.length === 0) {\n runtime.console.write(this.namespace, level, message, payload, error);\n return;\n }\n\n // The record attributes hold the error fields after redact.\n if (record) {\n runtime.console.write(this.namespace, level, record.body, record.attributes);\n return;\n }\n\n // A record that a hook or the shape check dropped prints no line. Its text did not pass redact.\n if (dropped === \"processor\" || dropped === \"redact\" || dropped === \"malformed\") {\n return;\n }\n\n if (!runtime.config.enabled || !runtime.console.accepts(level)) return;\n // Use the record builder without the delivery level and sampling checks. Do not process\n // a record again if a hook refused it. Do not send this record or add it as a breadcrumb.\n const clean = runtime.builder.build(\n {\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(payload, runtime.diagnostics),\n ...(error\n ? {\n \"error.type\": error.name,\n \"error.message\": error.message,\n \"error.stack_trace\": error.stack,\n }\n : {}),\n },\n },\n true,\n ).record;\n if (clean) runtime.console.write(this.namespace, level, clean.body, clean.attributes);\n }\n\n /**\n * Tests if the console prints a level that the library does not send.\n * @param runtime Runtime of this write.\n * @param level Severity level.\n * @returns True if logging is on and the console accepts the level.\n */\n private mirrors(runtime: ObservabilityRuntime, level: LogLevel): boolean {\n return runtime.config.enabled && runtime.console.accepts(level);\n }\n}\n","// src/core/meter.ts\n//\n// This module sums counter and histogram values in memory. At each interval, it gives one point\n// for each instrument and attribute set. A thousand adds then give one record, not a thousand.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_METRIC_OVERFLOW,\n ATTR_PAGE_URL,\n DEFAULT_METRIC_UNIT,\n METRIC_DEFAULT_BOUNDARIES,\n METRIC_KEYS,\n} from \"../constants\";\nimport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentDef,\n InstrumentOptions,\n MetricAttributes,\n} from \"../models/metric\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Sums of one attribute set in the current interval. */\ninterface Series {\n /** Attribute set of the series. */\n attributes: MetricAttributes;\n /** Number of values. */\n count: number;\n /** Sum of the values. */\n sum: number;\n /** Smallest value. */\n min: number;\n /** Largest value. */\n max: number;\n /** Count of each histogram bucket. A counter has none. */\n buckets: number[];\n}\n\n/** Series of one instrument in the current interval. */\ninterface Instrument {\n /** Definition from the first value of the interval. */\n def: InstrumentDef;\n /** Series by attribute set key. */\n series: Map<string, Series>;\n}\n\n/** Key of the overflow series. The key of an attribute set is JSON text. It starts with \"{\". */\nconst OVERFLOW_KEY = \"overflow\";\n\n/** Keys that the record builder sets. It replaces a call attribute of the same name. */\nconst RECORD_KEYS = new Set<string>([\n ATTR_LOG_TYPE,\n ATTR_LOG_SEQ,\n ATTR_APP_NAMESPACE,\n ATTR_PAGE_URL,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n]);\n\n/**\n * Keeps the string, finite number and boolean attributes in key order. Two calls with one set in\n * another key order then share one series.\n * @param attributes Attribute set of the call.\n * @returns The clean attribute set.\n */\nfunction cleanAttributes(attributes: MetricAttributes = {}): MetricAttributes {\n const clean: MetricAttributes = {};\n\n for (const key of Object.keys(attributes).sort()) {\n // The builder and the serializer replace or remove these keys. Each value then makes a\n // series with the same output.\n if (key.startsWith(\"metric.\") || RECORD_KEYS.has(key)) {\n continue;\n }\n\n const value: unknown = attributes[key];\n const finite = typeof value === \"number\" && Number.isFinite(value);\n if (typeof value === \"string\" || typeof value === \"boolean\" || finite) {\n clean[key] = value;\n }\n }\n\n return clean;\n}\n\n/**\n * Copies a list of boundaries by index. A custom iterator of the array of the app has no effect.\n * @param bounds Value of the boundaries option.\n * @returns A plain array with at most one value more than the limit, or null for a value that is\n * not an array.\n */\nfunction copyBounds(bounds: unknown, limit: number): unknown[] | null {\n if (!Array.isArray(bounds)) {\n return null;\n }\n\n // One value more than the limit. isAscending then refuses a list that is too long.\n const count = limit === 0 ? bounds.length : Math.min(bounds.length, limit + 1);\n return Array.from({ length: count }, (_unused, i): unknown => bounds[i]);\n}\n\n/**\n * Tests a list of histogram boundaries.\n * @param bounds Value of the boundaries option.\n * @returns True for at most 50 finite numbers in ascending order.\n */\nfunction isAscending(bounds: unknown, limit: number): bounds is number[] {\n return (\n Array.isArray(bounds) &&\n (limit === 0 || bounds.length <= limit) &&\n bounds.every(\n (bound: unknown, i) =>\n typeof bound === \"number\" &&\n Number.isFinite(bound) &&\n (i === 0 || bound > (bounds[i - 1] as number)),\n )\n );\n}\n\n/**\n * Builds the metric fields of one point. The attributes of the call stay out.\n * @param def Definition of the instrument.\n * @param series Sums of the attribute set.\n * @param start Start of the interval, in Unix nanoseconds.\n * @returns The metric fields of the point.\n */\nfunction fieldsOf(def: InstrumentDef, series: Series, start: string): Record<string, unknown> {\n const point: Record<string, unknown> = {\n \"metric.name\": def.name,\n \"metric.unit\": def.unit,\n \"metric.type\": def.kind,\n [METRIC_KEYS.start]: start,\n [METRIC_KEYS.attributeKeys]: Object.keys(series.attributes),\n };\n\n if (def.kind === \"counter\") {\n point[\"metric.value\"] = series.sum;\n return point;\n }\n\n return {\n ...point,\n [METRIC_KEYS.count]: series.count,\n [METRIC_KEYS.sum]: series.sum,\n [METRIC_KEYS.min]: series.min,\n [METRIC_KEYS.max]: series.max,\n [METRIC_KEYS.bounds]: def.boundaries,\n [METRIC_KEYS.buckets]: series.buckets,\n };\n}\n\n/** Adds a value to an instrument of the runtime. */\nexport type RecordMetric = (\n def: InstrumentDef,\n value: number,\n attributes?: MetricAttributes,\n) => void;\n\n/**\n * Makes a counter handle.\n * @param name Metric name.\n * @param options Unit of the values.\n * @param record Adds a value to the instrument.\n * @returns The counter.\n */\nexport function makeCounter(\n name: string,\n options: InstrumentOptions,\n record: RecordMetric,\n): Counter {\n const def: InstrumentDef = {\n name,\n kind: \"counter\",\n unit: options.unit ?? DEFAULT_METRIC_UNIT,\n boundaries: [],\n };\n\n return {\n add: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/**\n * Makes a histogram handle.\n * @param name Metric name.\n * @param options Unit of the values and the bucket boundaries.\n * @param record Adds a value to the instrument.\n * @returns The histogram.\n */\nexport function makeHistogram(\n name: string,\n options: HistogramOptions,\n record: RecordMetric,\n): Histogram {\n const def: InstrumentDef = {\n name,\n kind: \"histogram\",\n unit: options.unit ?? DEFAULT_METRIC_UNIT,\n boundaries: options.boundaries ?? METRIC_DEFAULT_BOUNDARIES,\n };\n\n return {\n record: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/** Sums the values of the counter and histogram instruments for one interval. */\nexport class Meter {\n /** Instruments with a value in the current interval. */\n private readonly instruments = new Map<string, Instrument>();\n\n /** Timer of the current interval. It runs only while a value waits. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Time of the first value of the interval, in epoch milliseconds. */\n private startedAt = 0;\n\n /**\n * @param intervalMs Gives the interval length, in milliseconds.\n * @param emit Builds and sends the record of one point from the call attributes and the\n * metric fields.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly intervalMs: () => number,\n private readonly emit: (\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ) => void,\n private readonly diagnostics: Diagnostics,\n private readonly policy = { maxSeries: 100, maxInstruments: 1000, maxHistogramBoundaries: 50 },\n ) {}\n\n /**\n * Adds a value to the series of its attribute set. It never throws into the call of the app.\n * @param def Definition of the instrument.\n * @param value Value to add.\n * @param attributes Attribute set of the value.\n */\n record(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // NaN and Infinity become null in JSON. A negative add breaks the sum of a counter.\n if (!Number.isFinite(value) || (def.kind === \"counter\" && value < 0)) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The value of the metric ${def.name} is not valid. The library dropped it.`,\n { \"metric.name\": def.name },\n );\n return;\n }\n\n // A getter or a Proxy trap of the attributes can throw.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n `The library could not read the attributes of the metric ${def.name}.`,\n () => {\n const instrument = this.instrumentOf(def);\n if (instrument) {\n this.add(instrument, value, cleanAttributes(attributes));\n this.arm();\n }\n },\n );\n }\n\n /** Sends one point for each series of the interval. It then starts a new interval. */\n collect(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n const start = `${String(this.startedAt)}000000`;\n const instruments = [...this.instruments.values()];\n this.instruments.clear();\n\n for (const { def, series } of instruments) {\n for (const one of series.values()) {\n this.emit(def.name, one.attributes, fieldsOf(def, one, start));\n }\n }\n }\n\n /**\n * Finds the instrument of the interval. The first value of the interval sets its definition.\n * @param def Definition of the call.\n * @returns The instrument, or null when the name has another kind.\n */\n private instrumentOf(def: InstrumentDef): Instrument | null {\n const found = this.instruments.get(def.name);\n\n if (found) {\n if (found.def.kind === def.kind) {\n return found;\n }\n\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The metric ${def.name} is a counter and a histogram. The library dropped the value.`,\n { \"metric.name\": def.name },\n );\n return null;\n }\n\n if (this.policy.maxInstruments && this.instruments.size >= this.policy.maxInstruments) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return null;\n }\n // Copy before the check. A later change of the array of the app must not change the buckets.\n const copy = copyBounds(def.boundaries, this.policy.maxHistogramBoundaries);\n const valid = isAscending(copy, this.policy.maxHistogramBoundaries);\n if (def.kind === \"histogram\" && !valid) {\n this.diagnostics.report(\n \"config.invalid\",\n `The boundaries of the metric ${def.name} must meet metrics.maxHistogramBoundaries and contain finite numbers in ascending order. The library uses the default boundaries.`,\n );\n }\n\n const instrument: Instrument = {\n def: { ...def, boundaries: valid ? copy : [...METRIC_DEFAULT_BOUNDARIES] },\n series: new Map(),\n };\n this.instruments.set(def.name, instrument);\n return instrument;\n }\n\n /**\n * Adds a value to the series of an attribute set.\n * @param instrument Instrument of the value.\n * @param value Value to add.\n * @param attributes Clean attribute set.\n */\n private add(instrument: Instrument, value: number, attributes: MetricAttributes): void {\n let key = JSON.stringify(attributes);\n let series = instrument.series.get(key);\n let set = attributes;\n\n // A storm of attribute sets cannot grow the memory and the payload without a limit.\n if (!series && this.policy.maxSeries > 0 && instrument.series.size >= this.policy.maxSeries) {\n key = OVERFLOW_KEY;\n series = instrument.series.get(key);\n set = { [ATTR_METRIC_OVERFLOW]: true };\n }\n\n if (!series) {\n // A histogram has one bucket more than boundaries. The last bucket has no upper bound.\n const size = instrument.def.kind === \"histogram\" ? instrument.def.boundaries.length + 1 : 0;\n const buckets = new Array<number>(size).fill(0);\n series = { attributes: set, count: 0, sum: 0, min: value, max: value, buckets };\n instrument.series.set(key, series);\n }\n\n series.count += 1;\n series.sum += value;\n series.min = Math.min(series.min, value);\n series.max = Math.max(series.max, value);\n\n if (series.buckets.length > 0) {\n const index = instrument.def.boundaries.findIndex((bound) => value <= bound);\n series.buckets[index === -1 ? series.buckets.length - 1 : index] += 1;\n }\n }\n\n /** Starts the timer of the interval at its first value. An idle meter has no timer. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n this.startedAt = Date.now();\n this.timer = setTimeout(() => {\n this.collect();\n }, this.intervalMs());\n unrefTimer(this.timer);\n }\n}\n","// src/utils/console.ts\n//\n// Formats and mirrors log records to the developer console during local execution\n\nimport { LEVEL_ORDER, RECORD_LIMITS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConsole } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { isLibraryConsole, runAsLibraryConsole } from \"./library-console\";\nimport { type SanitizeLimits, sanitize } from \"./sanitize\";\n\n/** Maps log levels to corresponding console method names. */\nconst METHOD: Record<LogLevel, \"debug\" | \"info\" | \"warn\" | \"error\"> = {\n TRACE: \"debug\",\n DEBUG: \"debug\",\n INFO: \"info\",\n WARN: \"warn\",\n ERROR: \"error\",\n FATAL: \"error\",\n};\n\n/** Mirrors log records directly to browser or Node console methods based on severity. */\nexport class ConsoleSink {\n /**\n * @param settings Console level and styles. A null level prints nothing.\n * @param diagnostics Diagnostics reporter.\n * @param limits Size limits of the printed payload. They are the record limits.\n */\n constructor(\n private settings: ResolvedConsole,\n private diagnostics: Diagnostics,\n private readonly limits: SanitizeLimits = RECORD_LIMITS,\n ) {}\n\n /**\n * Replaces the console level and styles.\n * @param settings Console level and styles. A null level prints nothing.\n */\n update(settings: ResolvedConsole): void {\n this.settings = settings;\n }\n\n /**\n * Tests if a level clears the console threshold.\n * @param level Severity level of the record.\n * @returns True if the sink prints this level.\n */\n accepts(level: LogLevel): boolean {\n if (this.settings.level === null) {\n return false;\n }\n\n // Guard against a level that is not a key of LEVEL_ORDER, for example \"toString\".\n if (!Object.hasOwn(LEVEL_ORDER, this.settings.level)) {\n return false;\n }\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[this.settings.level];\n }\n\n /**\n * Prints a styled log line if the level clears the console threshold.\n * @param namespace Logger namespace, shown in the prefix.\n * @param level Severity level of the record.\n * @param message Primary log message.\n * @param payload Caller payload. The sink prints a sanitized copy.\n * @param error Error to print before the payload.\n */\n write(\n namespace: string,\n level: LogLevel,\n message: string,\n payload?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.accepts(level)) {\n return;\n }\n // Guard against a missing console. Some worker realms do not define it.\n if (typeof console === \"undefined\") {\n return;\n }\n\n // Guard against a loop. A host console wrapper can call the logger. The logger then prints again.\n // The console capture also records inside this scope. Its line is already in devtools.\n if (isLibraryConsole()) {\n return;\n }\n\n // Pass the namespace as a %s argument. Then a %o or %c in the namespace prints as text.\n // The last %c resets the style. The message then prints in the default style.\n const prefix = `%c[%s]%c[${level}]%c`;\n const { styles } = this.settings;\n const method = METHOD[level];\n\n // A host can replace console methods with methods that throw. The guard stops that\n // error from breaking the log call of the caller.\n this.diagnostics.guard(\n \"handler.threw\",\n `The library could not print to console.${method}.`,\n () => {\n const details: unknown[] = [];\n\n if (error !== undefined) {\n details.push(error);\n }\n\n // Devtools keeps a reference to each logged object. A copy releases the caller's object.\n if (payload !== undefined) {\n details.push(sanitize(payload, this.limits, this.diagnostics));\n }\n\n // The console capture skips a call in this scope. It must not record a mirrored line.\n runAsLibraryConsole(() => {\n console[method](\n prefix,\n styles.namespace,\n namespace,\n styles[level],\n \"\",\n message,\n ...details,\n );\n });\n },\n );\n }\n}\n","// src/utils/sequence.ts\n//\n// Generates monotonic sequence numbers that order the records of each context.\n// Timestamps cannot order records. A clock can step, and two records can share a\n// millisecond. Each context has its own counter. A shared counter shows gaps, and\n// a gap looks like a lost record. The counter does not reset. A reset repeats\n// numbers in one context.\n\n/** Monotonic sequence counter establishing total record ordering within an execution context. */\nexport class Sequence {\n /** Last emitted sequence counter value. */\n private value = 0;\n\n /**\n * Increments and returns the next monotonic sequence number starting at 1.\n * @returns Next sequence number.\n */\n next(): number {\n return ++this.value;\n }\n}\n","// src/utils/tracing.ts\n//\n// Manages ambient distributed trace contexts, OpenTelemetry span integration, and W3C\n// traceparent headers. Consecutive records share one trace id. A new trace id for each\n// record gives each trace only one span.\n\nimport {\n SPAN_ID_BYTES,\n TRACE_FLAGS_MASK,\n TRACE_FLAGS_SAMPLED,\n TRACE_ID_BYTES,\n TRACE_MAX_AGE_MS,\n TRACEPARENT_HEADER,\n TRACEPARENT_VERSION,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { OtelApi, OtelLoader, OtelSpanContext } from \"../models/config\";\nimport { randomHex } from \"./identity\";\n\n/** The W3C format sets these hex widths. A span context with a different width is not usable. */\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\n/** Matches a digit that is not zero. A span that has not started reports an all-zero id. */\nconst NON_ZERO = /[1-9a-f]/;\n\n/**\n * Tests if a span context can carry correlation. It replaces isSpanContextValid\n * from the peer package. That function is not available when the peer is not installed.\n * @param context Span context reported by the host.\n * @returns True if both ids have the W3C width and neither is all zeros.\n */\nfunction isUsableSpanContext(context: OtelSpanContext): boolean {\n return (\n TRACE_ID_PATTERN.test(context.traceId) &&\n NON_ZERO.test(context.traceId) &&\n SPAN_ID_PATTERN.test(context.spanId) &&\n NON_ZERO.test(context.spanId)\n );\n}\n\n/** W3C trace context fields attached to log records and network headers. */\nexport interface TraceContext {\n /** Hexadecimal 32-character W3C trace identifier. */\n traceId: string;\n /** Hexadecimal 16-character W3C span identifier. */\n spanId: string;\n /** Bitfield byte containing W3C trace flags. */\n traceFlags: number;\n}\n\n/** Cause of a rotation of the ambient trace context. */\nexport type RotateReason = \"start\" | \"interaction\" | \"navigation\" | \"explicit\" | \"maxAge\";\n\n/** Ambient trace that ended. Its root span covers it. */\nexport interface EndedTrace {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the root span. */\n spanId: string;\n /** Cause of the start of the trace. */\n reason: RotateReason;\n /** Start time in epoch milliseconds. */\n startedAt: number;\n /** End time in epoch milliseconds. */\n endedAt: number;\n}\n\n/** Client span that a traceparent header names. */\nexport interface ClientSpan {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the client span. */\n spanId: string;\n /** Span ID of the root span of the trace. */\n parentSpanId: string;\n}\n\n/** Headers of one request, and the client span that they name. */\nexport interface RequestTrace {\n /** Header map containing traceparent. */\n headers: Record<string, string>;\n /** Client span of the request. It is undefined when the library records no span for it. */\n span?: ClientSpan;\n}\n\n/** Span decisions of the runtime. */\nexport interface SpanHooks {\n /**\n * Tests if the library records spans.\n * @returns True with a traces endpoint.\n */\n enabled(): boolean;\n /**\n * Tests if sampling keeps the spans of a trace.\n * @param traceId Trace ID.\n * @returns True if the library sends the spans of the trace.\n */\n keeps(traceId: string): boolean;\n /**\n * Receives an ambient trace that ended.\n * @param ended The trace.\n */\n onEnd(ended: EndedTrace): void;\n}\n\n/** Internal trace context tracking creation timestamp for expiration. */\ninterface AmbientTrace extends TraceContext {\n /** Creation timestamp in epoch milliseconds. */\n startedAt: number;\n /** Cause of the start of the trace. */\n reason: RotateReason;\n /** True after the root span ended. It ends one time. */\n ended: boolean;\n}\n\n/**\n * Generates a random 32-character hex string in the W3C trace ID format.\n * Use it to start your own trace. The backend drops an id with the wrong width\n * and reports no error.\n * @returns 32-character hexadecimal trace ID.\n */\nexport function newTraceId(): string {\n return randomHex(TRACE_ID_BYTES);\n}\n\n/**\n * Generates a random 16-character hex string conforming to W3C span ID format.\n * @returns 16-character hexadecimal span ID.\n */\nexport function newSpanId(): string {\n return randomHex(SPAN_ID_BYTES);\n}\n\n/**\n * Creates a new AmbientTrace instance with the sampled trace flag set. It always sets\n * the flag. Sampling runs before the library builds the record.\n * @param reason Cause of the start of the trace.\n * @returns Initialized AmbientTrace object.\n */\nfunction mintAmbient(reason: RotateReason): AmbientTrace {\n return {\n traceId: newTraceId(),\n spanId: newSpanId(),\n traceFlags: TRACE_FLAGS_SAMPLED,\n startedAt: Date.now(),\n reason,\n ended: false,\n };\n}\n\n/**\n * Formats a W3C traceparent value.\n * @param traceId Trace ID.\n * @param spanId Span ID of the caller.\n * @param traceFlags Trace flags.\n * @returns The traceparent value.\n */\nfunction traceparent(traceId: string, spanId: string, traceFlags: number): string {\n // Mask the trace flags to a 2-digit hex byte, as the W3C specification requires.\n // trace-flags is a bitfield, not a boolean. A fixed 00 or 01 discards upstream flags.\n const flags = (traceFlags & TRACE_FLAGS_MASK).toString(16).padStart(2, \"0\");\n return `${TRACEPARENT_VERSION}-${traceId}-${spanId}-${flags}`;\n}\n\n/**\n * Creates a defensive copy of a TraceContext from an AmbientTrace.\n * @param ambient Source ambient trace object.\n * @returns Defensive copy of TraceContext.\n */\nfunction toTraceContext(ambient: AmbientTrace): TraceContext {\n return {\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n traceFlags: ambient.traceFlags,\n };\n}\n\n/** Manages ambient distributed trace contexts and resolves active OpenTelemetry spans. */\nexport class TraceEngine {\n /**\n * Active ambient trace context. The instance keeps this state, not the module. Two\n * runtimes in one document must not share a trace id.\n */\n private ambient: AmbientTrace = mintAmbient(\"start\");\n\n /** The optional peer after it loads. It is undefined while it loads or when it is absent. */\n private otel: OtelApi | undefined;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it is not set, OTel is off.\n * Do not import the peer by name. The Vite dev server fails if the peer is not installed.\n * @param spans Span decisions of the runtime. Without them, the library records no span.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly maxAgeMs = TRACE_MAX_AGE_MS,\n private readonly load?: OtelLoader,\n private readonly spans?: SpanHooks,\n ) {}\n\n /**\n * Loads the OpenTelemetry API. Until the load completes, records use the ambient trace.\n * If there is no loader or the load fails, all records use the ambient trace.\n * @returns Promise that resolves when the attempt settles.\n */\n async loadOtel(): Promise<void> {\n if (!this.load) {\n return;\n }\n\n try {\n this.otel = await this.load();\n } catch (error) {\n this.diagnostics.report(\n \"trace.otel_failed\",\n \"The library could not load @opentelemetry/api. Records use the trace ids of the library.\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Resolves trace context, prioritizing active OpenTelemetry spans over the ambient trace.\n * @returns Active TraceContext.\n */\n resolve(): TraceContext {\n return this.activeSpanContext() ?? this.ambientContext();\n }\n\n /**\n * Reads the ambient trace. It rotates a trace that is too old.\n * @returns Ambient TraceContext.\n */\n private ambientContext(): TraceContext {\n // Rotate the ambient trace when its age exceeds maxAgeMs. The check runs on read,\n // not on a timer. A timer keeps this instance alive for the life of the document.\n if (Date.now() - this.ambient.startedAt > this.maxAgeMs) {\n this.rotate(\"maxAge\");\n }\n return toTraceContext(this.ambient);\n }\n\n /**\n * Reads the active span of the host if the peer module loaded and a span runs.\n * @returns Trace context of the active span, or undefined.\n */\n private activeSpanContext(): TraceContext | undefined {\n const otel = this.otel;\n if (!otel) {\n return undefined;\n }\n\n return this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not read the active OpenTelemetry span.\",\n (): TraceContext | undefined => {\n const span = otel.trace.getActiveSpan();\n if (span === undefined) {\n return undefined;\n }\n const spanContext = span.spanContext();\n if (!isUsableSpanContext(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n };\n },\n );\n }\n\n /**\n * Rotates the ambient trace context to mark the start of a new logical operation. It ends the\n * root span of the old trace.\n * @param reason Event reason triggering the rotation.\n * @returns Newly created TraceContext.\n */\n rotate(reason: RotateReason): TraceContext {\n // Set the new trace first. A record that a hook makes inside onEnd then joins the new trace.\n // If not, that record rotates again, and its trace gets no root span.\n const old = this.ambient;\n this.ambient = mintAmbient(reason);\n const next = toTraceContext(this.ambient);\n this.finish(old);\n return next;\n }\n\n /**\n * Ends the root span of the ambient trace one time. Later records can still use the trace.\n * The exit flush calls it. A closing document has no later rotation.\n */\n end(): void {\n this.finish(this.ambient);\n }\n\n /**\n * Ends the root span of a trace one time.\n * @param ambient Trace to end.\n */\n private finish(ambient: AmbientTrace): void {\n if (ambient.ended) {\n return;\n }\n\n ambient.ended = true;\n this.spans?.onEnd({\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n reason: ambient.reason,\n startedAt: ambient.startedAt,\n endedAt: Date.now(),\n });\n }\n\n /**\n * Generates W3C traceparent headers with the registered OpenTelemetry propagators.\n * Without a traceparent from OpenTelemetry, it uses the ambient trace.\n * @returns Header map containing traceparent.\n */\n headers(): Record<string, string> {\n return this.trace(false).headers;\n }\n\n /**\n * Generates the headers of one request of the network capture. With spans on, the traceparent\n * names a new client span of the ambient trace.\n * @returns The headers, and the client span that the library records.\n */\n request(): RequestTrace {\n return this.trace(true);\n }\n\n /**\n * Generates the trace headers.\n * @param client True to name a new client span in the traceparent.\n * @returns The headers, and the client span that the library records.\n */\n private trace(client: boolean): RequestTrace {\n const carrier: Record<string, string> = {};\n const otel = this.otel;\n if (otel) {\n this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not add the OpenTelemetry headers.\",\n () => {\n otel.propagation.inject(otel.context.active(), carrier);\n },\n );\n }\n if (carrier[TRACEPARENT_HEADER]) {\n return { headers: carrier };\n }\n\n // The peer keeps its own spans. The library records no span for a trace of the peer.\n const fromOtel = this.activeSpanContext();\n const ctx = fromOtel ?? this.ambientContext();\n const spans = fromOtel ? undefined : this.spans;\n\n if (!spans?.enabled()) {\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, ctx.spanId, ctx.traceFlags);\n return { headers: carrier };\n }\n\n // Clear the sampled flag of a trace that sampling drops. A downstream service then drops\n // its spans too. The whole trace stays or goes.\n const kept = spans.keeps(ctx.traceId);\n const flags = kept ? ctx.traceFlags : ctx.traceFlags & ~TRACE_FLAGS_SAMPLED;\n const spanId = client ? newSpanId() : ctx.spanId;\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, spanId, flags);\n\n if (!client || !kept) {\n return { headers: carrier };\n }\n\n return { headers: carrier, span: { traceId: ctx.traceId, spanId, parentSpanId: ctx.spanId } };\n }\n}\n","// src/core/breadcrumbs.ts\n//\n// This ring buffer keeps a bounded trail of recent user and system events in time order.\n// The buffer does not send breadcrumbs as records. Breadcrumbs go to the backend in the\n// payload of an error record. No function in this file throws.\n\nimport { BREADCRUMB_MIN_CAPACITY } from \"../constants\";\n\n/** Category of a breadcrumb event. */\nexport type BreadcrumbCategory =\n \"log\" | \"action\" | \"event\" | \"click\" | \"navigation\" | \"http\" | \"console\" | \"frame\" | \"custom\";\n\n/** Short summary of one event that the buffer keeps for an error record. */\nexport interface Breadcrumb {\n /** Timestamp in epoch milliseconds. */\n t: number;\n /** Category of the event. */\n category: BreadcrumbCategory;\n /** Description of the event for a person to read. */\n message: string;\n /** Optional contextual metadata. */\n data?: Record<string, unknown>;\n}\n\n/** Ring buffer of fixed size. It keeps recent breadcrumbs in time order. */\nexport class BreadcrumbBuffer {\n /** Storage array of the ring buffer. */\n private buffer: (Breadcrumb | undefined)[];\n\n /** Next write index in the circular buffer. */\n private pointer = 0;\n\n /**\n * It is true after the pointer wraps past the capacity. The pointer alone cannot\n * tell an empty ring from a ring that wrapped back to index 0.\n */\n private filled = false;\n\n /** Maximum number of breadcrumbs that the buffer keeps. */\n private capacity: number;\n\n /**\n * @param capacity Maximum number of breadcrumbs. A smaller value changes to the minimum size.\n */\n constructor(capacity: number) {\n this.capacity = capacity === 0 ? 0 : Math.max(capacity, BREADCRUMB_MIN_CAPACITY);\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n }\n\n /**\n * Changes the capacity and keeps the most recent breadcrumbs that fit.\n * @param capacity New capacity. Set 0 to remove and disable stored breadcrumbs.\n */\n resize(capacity: number): void {\n const recent = this.snapshot().slice(-capacity);\n this.capacity = capacity;\n this.buffer = new Array<Breadcrumb | undefined>(capacity);\n this.pointer = 0;\n this.filled = false;\n if (capacity) for (const crumb of recent) this.push(crumb);\n }\n\n /**\n * Adds a breadcrumb. When the buffer is full, the new breadcrumb replaces the oldest one.\n * @param crumb Breadcrumb to add.\n */\n push(crumb: Breadcrumb): void {\n if (this.capacity === 0) return;\n this.buffer[this.pointer] = crumb;\n this.pointer = (this.pointer + 1) % this.capacity;\n if (this.pointer === 0) {\n this.filled = true;\n }\n }\n\n /** Removes all breadcrumbs. A new session must not carry the trail of the previous user. */\n clear(): void {\n this.buffer.fill(undefined);\n this.pointer = 0;\n this.filled = false;\n }\n\n /**\n * Returns all stored breadcrumbs ordered from oldest to newest.\n * @returns List of breadcrumbs in time order.\n */\n snapshot(): Breadcrumb[] {\n const ordered = this.filled\n ? [...this.buffer.slice(this.pointer), ...this.buffer.slice(0, this.pointer)]\n : this.buffer.slice(0, this.pointer);\n return ordered.filter((crumb): crumb is Breadcrumb => crumb !== undefined);\n }\n}\n","// src/core/config.ts\n//\n// This module resolves partial consumer options into a validated config.\n// It also updates the live config. Obey the two rules below. A broken rule fails silently.\n// 1. Merge a reconfigure onto the config in force, not onto the defaults.\n// 2. Change the resolved object in place. Do not replace it. Subsystems keep the\n// reference from construction.\n// No function in this file throws to the caller.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n BEACON_LIMIT_BYTES,\n CONFIG_SECTIONS,\n CONSOLE_DEFAULT_LEVEL,\n CONSOLE_DEFAULT_STYLES,\n DEAD_CLICK_MS,\n DEFAULT_CONFIG,\n LEVEL_ORDER,\n REMOTE_CAPTURE_FLAGS,\n RESOURCE_SLOW_MS,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SAMPLING_RATE_FALLBACK,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n SERIALIZER_NAME_ECS,\n SERIALIZER_NAME_OTLP,\n UNDEFAULTED_CONFIG_KEYS,\n UNDEFAULTED_SECTION_KEYS,\n UNKNOWN_SERVICE_NAME,\n} from \"../constants\";\nimport type {\n BatchingOptions,\n BusOptions,\n CaptureOptions,\n CapturedConsoleMethod,\n ConsoleOption,\n ConsoleStyles,\n JourneyOptions,\n LimitOptions,\n ObservabilityConfig,\n ResolvedConfig,\n ResolvedConsole,\n RetentionOptions,\n SamplingOptions,\n SerializerChoice,\n} from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { CapturePlugin } from \"../models/plugin\";\nimport type { LogSerializer } from \"../models/serializer\";\nimport { isObject } from \"../utils/guards\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Level names in severity order. */\nconst LEVEL_NAMES = Object.keys(LEVEL_ORDER) as readonly LogLevel[];\n\n/** Accepted values of each choice option. */\nconst COMPRESSION_VALUES = [\"gzip\", \"none\"] as const;\nconst CREDENTIALS_VALUES = [\"omit\", \"same-origin\", \"include\"] as const;\nconst STORAGE_VALUES = [\"auto\", \"indexeddb\", \"localstorage\", \"memory\", \"none\"] as const;\nconst IDENTITY_VALUES = [\"storage\", \"memory\"] as const;\nconst BUS_MODE_VALUES = [\"auto\", \"sender\", \"forwarder\", \"off\"] as const;\nconst OPENFIN_ROLE_VALUES = [\"auto\", \"provider\", \"client\"] as const;\nconst JOURNEY_SCOPE_VALUES = [\"auto\", \"context\", \"tab\", \"origin\"] as const;\nconst CONSOLE_METHOD_VALUES = [\"error\", \"warn\", \"info\", \"log\"] as const;\nconst RETENTION_MODE_VALUES = [\"limited\", \"until-delivered\"] as const;\n\n/** Lowest and highest accepted value of an integer option. */\ntype Range = readonly [min: number, max: number];\n\n/** Accepted range of each batching key. */\nconst BATCHING_RANGES: Record<keyof BatchingOptions, Range> = {\n logFlushIntervalMs: [100, 60_000],\n logBatchSize: [1, 1000],\n metricFlushIntervalMs: [100, 60_000],\n metricBatchSize: [1, 1000],\n};\n\n/** Accepted range of each numeric retention key. */\nconst RETENTION_RANGES: Record<Exclude<keyof RetentionOptions, \"mode\">, Range> = {\n maxBatches: [1, 5000],\n maxAgeMs: [60_000, 7 * 24 * 60 * 60 * 1000],\n maxAttempts: [1, 20],\n};\n\n/**\n * Accepted range of each record limit. The maximum of maxRecordBytes is one beacon. The body and\n * the error fields are outside maxRecordBytes. An exit batch larger than one beacon goes to the\n * emergency queue.\n */\nconst LIMIT_RANGES: Record<keyof LimitOptions, Range> = {\n maxBodyChars: [256, 65_536],\n maxAttributeChars: [256, 65_536],\n maxAttributeCount: [1, 1024],\n maxStackChars: [256, 65_536],\n maxDepth: [1, 16],\n maxArrayLength: [1, 10_000],\n maxNodes: [100, 100_000],\n maxRecordBytes: [1024, BEACON_LIMIT_BYTES],\n};\n\n/** Accepted range of journey.maxAgeMs. */\nconst JOURNEY_AGE_RANGE: Range = [60_000, 24 * 60 * 60 * 1000];\n\n/** Range of a duration. The maximum is the largest delay that a browser timer accepts. */\nconst DURATION_RANGE: Range = [0, 2_147_483_647];\n\n/** Range of a count. Zero turns the limit off. */\nconst COUNT_RANGE: Range = [0, Number.MAX_SAFE_INTEGER];\n\n/** Range of a count that must be at least 1. */\nconst POSITIVE_RANGE: Range = [1, Number.MAX_SAFE_INTEGER];\n\n/** Range of the waits of rage click and dead click detection. */\nconst CLICK_WAIT_RANGE: Range = [100, 10_000];\n\n/** Keys of a policy section that have number values. */\ntype NumberKeys<T> = { [K in keyof T]: T[K] extends number ? K : never }[keyof T];\n\n/** Policy sections that resolvePolicy() checks. */\ntype PolicySection =\n | \"capturePolicy\"\n | \"metadata\"\n | \"persistence\"\n | \"diagnostics\"\n | \"correlation\"\n | \"metrics\"\n | \"buffering\"\n | \"delivery\"\n | \"debugBuffer\";\n\n/**\n * Reads one policy key that the generic checks cannot read, for example a list.\n * @param key Full config key for the diagnostic message.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value to use.\n */\ntype CustomResolver = (\n key: string,\n value: unknown,\n fallback: unknown,\n diagnostics: Diagnostics,\n) => unknown;\n\n/** Rules of one policy section. Each number key must have a range. */\ninterface PolicyRules<T> {\n /** Accepted range of each number key. */\n ranges: Record<NumberKeys<T>, Range>;\n /** Accepted values of each choice key. */\n choices?: Partial<Record<keyof T, readonly string[]>>;\n /** Resolver of each key with another value type. */\n custom?: Partial<Record<keyof T, CustomResolver>>;\n}\n\n/** Rules of each policy section. A new number key without a range does not compile. */\nconst POLICY_RULES: { [K in PolicySection]: PolicyRules<ResolvedConfig[K]> } = {\n capturePolicy: {\n ranges: {\n // A larger capacity gives an invalid array allocation.\n breadcrumbs: [0, 1_000_000],\n errorDedupeMs: DURATION_RANGE,\n maxErrorSignatures: COUNT_RANGE,\n errorsPerWindow: COUNT_RANGE,\n consolePerWindow: COUNT_RANGE,\n longFramesPerWindow: COUNT_RANGE,\n webSocketPerWindow: COUNT_RANGE,\n reportsPerWindow: COUNT_RANGE,\n resourcesPerWindow: COUNT_RANGE,\n lifecyclePerWindow: COUNT_RANGE,\n windowMs: DURATION_RANGE,\n errorCeiling: COUNT_RANGE,\n },\n },\n metadata: { ranges: {} },\n persistence: { ranges: {} },\n diagnostics: {\n ranges: { throttleMs: DURATION_RANGE },\n custom: { records: resolveDiagnosticRecords },\n },\n correlation: {\n ranges: {\n sessionIdleMs: DURATION_RANGE,\n sessionTouchMs: DURATION_RANGE,\n traceMaxAgeMs: DURATION_RANGE,\n },\n },\n metrics: {\n ranges: {\n maxSeries: COUNT_RANGE,\n maxInstruments: COUNT_RANGE,\n maxHistogramBoundaries: COUNT_RANGE,\n },\n },\n buffering: {\n ranges: { maxPendingRecords: COUNT_RANGE, maxPendingBytes: COUNT_RANGE },\n choices: { overflow: [\"drop-oldest\", \"drop-newest\", \"persist\"] },\n },\n delivery: {\n ranges: {\n requestTimeoutMs: [1, DURATION_RANGE[1]],\n maxConcurrentRequests: POSITIVE_RANGE,\n retryBaseDelayMs: DURATION_RANGE,\n retryMaxDelayMs: DURATION_RANGE,\n retryIdleDelayMs: DURATION_RANGE,\n batchesPerDrain: POSITIVE_RANGE,\n },\n choices: { priority: [\"low\", \"auto\", \"high\"] },\n },\n debugBuffer: { ranges: { maxRecords: [1, 10_000], maxAgeMs: DURATION_RANGE } },\n};\n\n/** Boolean keys of the capture section. */\nconst CAPTURE_FLAG_KEYS = [\n \"errors\",\n \"rejections\",\n \"resourceErrors\",\n \"fetch\",\n \"xhr\",\n \"httpMetrics\",\n \"navigation\",\n \"webVitals\",\n \"longFrames\",\n \"fullUrls\",\n \"webSocket\",\n \"uncleanExit\",\n \"userTiming\",\n \"serverTiming\",\n \"reports\",\n \"lifecycle\",\n] as const;\n\n/** Origin of a sandboxed frame without allow-same-origin. */\nconst SANDBOX_ORIGIN = \"null\";\n\n/** Text of each expected value in a config.invalid message. */\nconst LEVEL_EXPECTED = `a level name: ${listOf(LEVEL_NAMES)}`;\nconst CONSOLE_CAPTURE_EXPECTED = `true, false or a list of ${listOf(CONSOLE_METHOD_VALUES)}`;\nconst PATTERN_LIST_EXPECTED = \"a list of strings and RegExp patterns\";\nconst TARGET_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://api.example\" and RegExp patterns';\nconst ORIGIN_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://app.example\". For a sandboxed frame, set bus.mode: \"sender\" in the frame';\nconst STRING_LIST_EXPECTED = \"a list of strings\";\nconst DIAGNOSTIC_RECORDS_EXPECTED = \"true, false or a list of diagnostic codes\";\n\n/** Function form of the headers option. */\ntype HeadersFunction = () => Record<string, string> | Promise<Record<string, string>>;\n\n/** The headers option. */\ntype HeadersOption = ObservabilityConfig[\"headers\"];\n\n/**\n * Writes a list of values as text, for example `\"a\", \"b\" or \"c\"`.\n * @param values Values to list.\n * @returns The text.\n */\nfunction listOf(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`);\n return `${quoted.slice(0, -1).join(\", \")} or ${quoted[quoted.length - 1]}`;\n}\n\n/**\n * Describes a config value for a message. It does not print an object or a function.\n * @param value Value that the consumer passed.\n * @returns Short text for the value.\n */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"string\") {\n return `\"${value}\"`;\n }\n\n if (typeof value === \"function\") {\n return \"a function\";\n }\n\n if (typeof value === \"object\" && value !== null) {\n return \"an object\";\n }\n\n return String(value);\n}\n\n/**\n * Reports a value that the option does not accept.\n * @param diagnostics Diagnostics reporter.\n * @param key Config key, for example `bus.mode`.\n * @param expected Text of the accepted values.\n * @param value Value that the consumer passed.\n * @param kept Text of the value that stays in force.\n */\nfunction reportInvalid(\n diagnostics: Diagnostics,\n key: string,\n expected: string,\n value: unknown,\n kept: string,\n): void {\n diagnostics.report(\n \"config.invalid\",\n `${key} must be ${expected}. The value is ${describeValue(value)}. The library keeps ${kept}.`,\n );\n}\n\n/**\n * Reads an option that accepts one value from a fixed list.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param accepted Accepted values.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveChoice<T extends string>(\n key: string,\n value: unknown,\n accepted: readonly T[],\n fallback: T,\n diagnostics: Diagnostics,\n): T {\n if (value === undefined) {\n return fallback;\n }\n\n const match = accepted.find((entry) => entry === value);\n if (match !== undefined) {\n return match;\n }\n\n reportInvalid(diagnostics, key, listOf(accepted), value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads a boolean option.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not a boolean.\n */\nfunction resolveBoolean(\n key: string,\n value: unknown,\n fallback: boolean,\n diagnostics: Diagnostics,\n): boolean {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"true or false\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that accepts a finite number of 0 or more.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveNonNegative(\n key: string,\n value: unknown,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"a finite number of 0 or more\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that accepts an integer in a range.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param range Lowest and highest accepted value.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value is not accepted.\n */\nfunction resolveInteger(\n key: string,\n value: unknown,\n range: Range,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n const [min, max] = range;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max) {\n return value;\n }\n\n const expected = `an integer from ${String(min)} to ${String(max)}`;\n reportInvalid(diagnostics, key, expected, value, String(fallback));\n return fallback;\n}\n\n/**\n * Checks the logger cache limit. An invalid value keeps the limit in force, including null.\n * @param value Limit that the app supplied.\n * @param previous Limit in force. Null permits a cache with no limit.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid limit, or the limit in force.\n */\nfunction resolveCacheLimit(\n value: unknown,\n previous: number | null,\n diagnostics: Diagnostics,\n): number | null {\n if (value === undefined) return previous;\n if (value === null) return null;\n if (typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0) return value;\n reportInvalid(\n diagnostics,\n \"loggerCache.maxEntries\",\n \"a nonnegative safe integer or null\",\n value,\n String(previous),\n );\n return previous;\n}\n\n/**\n * Merges and checks a section of integer options. The keys come from `ranges` only.\n * @param section Section name, for example `batching`.\n * @param input Values that the consumer passed.\n * @param base Values in force.\n * @param ranges Accepted range of each key.\n * @param diagnostics Diagnostics reporter.\n * @returns The value of each key in `ranges`.\n */\nfunction resolveRanges<K extends string>(\n section: string,\n input: Partial<Record<NoInfer<K>, unknown>> | undefined,\n base: Record<NoInfer<K>, number>,\n ranges: Record<K, Range>,\n diagnostics: Diagnostics,\n): Record<K, number> {\n const given: Partial<Record<K, unknown>> = input ?? {};\n const keys = Object.keys(ranges) as K[];\n\n return Object.fromEntries(\n keys.map((key): [K, number] => [\n key,\n resolveInteger(`${section}.${key}`, given[key], ranges[key], base[key], diagnostics),\n ]),\n ) as Record<K, number>;\n}\n\n/**\n * Reads a level name in any case.\n * @param value Value that the consumer passed.\n * @returns The level, or undefined when the value is not a level name.\n */\nfunction toLevel(value: unknown): LogLevel | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const upper = value.toUpperCase();\n return LEVEL_NAMES.find((level) => level === upper);\n}\n\n/**\n * Reads a level option. Without this check, an unknown level drops each record with no message.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Level in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The level, or the fallback when the value is not a level name.\n */\nfunction resolveLevel(\n key: string,\n value: unknown,\n fallback: LogLevel,\n diagnostics: Diagnostics,\n): LogLevel {\n if (value === undefined) {\n return fallback;\n }\n\n const level = toLevel(value);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(diagnostics, key, LEVEL_EXPECTED, value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads the minLevels option. It keeps each valid prefix and reports each other entry. A new map\n * replaces the map in force.\n * @param value Value that the consumer passed.\n * @param fallback Levels in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The level for each namespace prefix.\n */\nfunction resolveMinLevels(\n value: unknown,\n fallback: Record<string, LogLevel>,\n diagnostics: Diagnostics,\n): Record<string, LogLevel> {\n if (value === undefined) {\n return fallback;\n }\n\n if (!isObject(value)) {\n reportInvalid(\n diagnostics,\n \"minLevels\",\n \"an object of level names\",\n value,\n \"the value in force\",\n );\n return fallback;\n }\n\n const levels: [string, LogLevel][] = [];\n for (const [prefix, raw] of Object.entries(value)) {\n const level = toLevel(raw);\n if (prefix !== \"\" && level !== undefined) {\n levels.push([prefix, level]);\n } else {\n reportInvalid(diagnostics, `minLevels[\"${prefix}\"]`, LEVEL_EXPECTED, raw, \"minLevel for it\");\n }\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(levels);\n}\n\n/**\n * Reads a list option. It keeps each accepted entry and reports each other entry.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback List in force.\n * @param expected Text of the accepted list.\n * @param accept Converts an entry, or returns undefined to reject it.\n * @param diagnostics Diagnostics reporter.\n * @returns The accepted entries, or the fallback when the value is not a list.\n */\nfunction resolveList<T>(\n key: string,\n value: unknown,\n fallback: T[],\n expected: string,\n accept: (entry: unknown) => T | undefined,\n diagnostics: Diagnostics,\n): T[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(diagnostics, key, expected, value, \"the list in force\");\n return fallback;\n }\n\n const kept: T[] = [];\n const entries: unknown[] = value;\n\n for (const entry of entries) {\n const accepted = accept(entry);\n if (accepted === undefined) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the ${key} entry ${describeValue(entry)}. ${key} must be ${expected}.`,\n );\n continue;\n }\n kept.push(accepted);\n }\n\n return kept;\n}\n\n/**\n * Accepts a function entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toProcessor(entry: unknown): ResolvedConfig[\"processors\"][number] | undefined {\n return typeof entry === \"function\" ? (entry as ResolvedConfig[\"processors\"][number]) : undefined;\n}\n\n/**\n * Accepts a capture plugin entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toPlugin(entry: unknown): CapturePlugin | undefined {\n const valid =\n isObject(entry) &&\n typeof entry.name === \"string\" &&\n entry.name !== \"\" &&\n typeof entry.install === \"function\" &&\n typeof entry.uninstall === \"function\";\n\n return valid ? (entry as unknown as CapturePlugin) : undefined;\n}\n\n/**\n * Reads diagnostics.records. A list keeps each string entry and reports each other entry.\n * @param key Full config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns True, false or the list of codes.\n */\nfunction resolveDiagnosticRecords(\n key: string,\n value: unknown,\n fallback: unknown,\n diagnostics: Diagnostics,\n): unknown {\n if (value === undefined || typeof value === \"boolean\") {\n return value ?? fallback;\n }\n\n if (Array.isArray(value)) {\n return resolveList(key, value, [], DIAGNOSTIC_RECORDS_EXPECTED, toStringEntry, diagnostics);\n }\n\n reportInvalid(diagnostics, key, DIAGNOSTIC_RECORDS_EXPECTED, value, \"the value in force\");\n return fallback;\n}\n\n/**\n * Accepts a string entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toStringEntry(entry: unknown): string | undefined {\n return typeof entry === \"string\" ? entry : undefined;\n}\n\n/**\n * Accepts a string or a RegExp entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toPattern(entry: unknown): string | RegExp | undefined {\n return typeof entry === \"string\" || entry instanceof RegExp ? entry : undefined;\n}\n\n/**\n * Accepts a console method name.\n * @param entry List entry.\n * @returns The method, or undefined.\n */\nfunction toConsoleMethod(entry: unknown): CapturedConsoleMethod | undefined {\n return CONSOLE_METHOD_VALUES.find((method) => method === entry);\n}\n\n/**\n * Reads an origin entry. A URL with a path gives its origin.\n * @param entry List entry.\n * @returns The origin, or undefined. resolveList reports the rejected entry.\n */\nfunction toOrigin(entry: unknown): string | undefined {\n if (typeof entry !== \"string\") {\n return undefined;\n }\n\n // Each sandboxed and data: document has the opaque origin \"null\". One entry trusts all of them.\n try {\n const { origin } = new URL(entry);\n return origin === SANDBOX_ORIGIN ? undefined : origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads a trace header target. A string gives its origin. A RegExp stays as it is.\n * @param entry List entry.\n * @returns The target, or undefined. resolveList reports the rejected entry.\n */\nfunction toTarget(entry: unknown): string | RegExp | undefined {\n return entry instanceof RegExp ? entry : toOrigin(entry);\n}\n\n/**\n * Tests if a value is an object of string values.\n * @param value Value to test.\n * @returns True for an object whose values are all strings.\n */\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n if (!isObject(value)) {\n return false;\n }\n\n const values: unknown[] = Object.values(value);\n return values.every((entry) => typeof entry === \"string\");\n}\n\n/**\n * Reads the headers option.\n * @param value Value that the consumer passed.\n * @param fallback Headers in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The headers, undefined for an explicit undefined, or the fallback for a bad value.\n */\nfunction resolveHeaders(\n value: unknown,\n fallback: HeadersOption,\n diagnostics: Diagnostics,\n): HeadersOption {\n // An explicit undefined clears the headers. After logout, the old token must not go on a send.\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value === \"function\") {\n return value as HeadersFunction;\n }\n\n if (isStringRecord(value)) {\n return value;\n }\n\n // The value can hold a token, and this message can become a record.\n diagnostics.report(\n \"config.invalid\",\n \"headers must be an object of strings or a function. The library keeps the headers in force.\",\n );\n return fallback;\n}\n\n/**\n * Checks if a value implements the LogSerializer interface.\n * @param value Value to check.\n * @returns True if value implements serialize.\n */\nfunction isSerializer(value: unknown): value is LogSerializer {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const serialize: unknown = Reflect.get(value, \"serialize\");\n return typeof serialize === \"function\";\n}\n\n/**\n * Validates the serializer option. It does not change a name into an implementation.\n * The transport selects the implementation.\n * @param requested Serializer name or custom serializer implementation.\n * @param previous Serializer option in force.\n * @param diagnostics Diagnostics reporter.\n * @returns Valid serializer option.\n */\nfunction resolveSerializer(\n requested: unknown,\n previous: SerializerChoice | undefined,\n diagnostics: Diagnostics,\n): SerializerChoice {\n if (requested === undefined) {\n return previous ?? SERIALIZER_NAME_OTLP;\n }\n if (requested === SERIALIZER_NAME_OTLP || requested === SERIALIZER_NAME_ECS) {\n return requested;\n }\n if (isSerializer(requested)) {\n return requested;\n }\n\n diagnostics.report(\n \"config.invalid\",\n `serializer must be \"${SERIALIZER_NAME_OTLP}\", \"${SERIALIZER_NAME_ECS}\" or an implementation. The library uses \"${SERIALIZER_NAME_OTLP}\".`,\n );\n return SERIALIZER_NAME_OTLP;\n}\n\n/** Style keys that the console option accepts. */\nconst CONSOLE_STYLE_KEYS = new Set(Object.keys(CONSOLE_DEFAULT_STYLES));\n\n/**\n * Keeps the valid entries of a console styles object. It reports each entry that it drops.\n * @param styles Styles that the consumer passed.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid styles.\n */\nfunction validStyles(styles: ConsoleStyles | undefined, diagnostics: Diagnostics): ConsoleStyles {\n const valid: Record<string, string> = {};\n const entries: [string, unknown][] = Object.entries(styles ?? {});\n\n for (const [key, value] of entries) {\n if (!CONSOLE_STYLE_KEYS.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown console.styles key \"${key}\". Check the spelling.`,\n );\n continue;\n }\n\n if (typeof value !== \"string\") {\n diagnostics.report(\n \"config.invalid\",\n `console.styles.${key} must be a string. The library keeps the style in force.`,\n );\n continue;\n }\n\n valid[key] = value;\n }\n\n return valid;\n}\n\n/**\n * Reads the level of the console object form.\n * @param requested Level that the consumer passed.\n * @param previous Console level in force. Null means the console is off.\n * @param diagnostics Diagnostics reporter.\n * @returns The level. An unknown level keeps the level in force.\n */\nfunction resolveConsoleLevel(\n requested: unknown,\n previous: LogLevel | null,\n diagnostics: Diagnostics,\n): LogLevel | null {\n if (requested === undefined) {\n return previous ?? CONSOLE_DEFAULT_LEVEL;\n }\n\n const level = toLevel(requested);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(\n diagnostics,\n \"console.level\",\n LEVEL_EXPECTED,\n requested,\n \"the console level in force\",\n );\n return previous;\n}\n\n/**\n * Normalizes the console option into a level and a set of styles.\n * @param requested Consumer console option.\n * @param previous Console settings in force.\n * @param diagnostics Diagnostics reporter.\n * @returns Console settings. The level is null when the console is off.\n */\nfunction resolveConsole(\n requested: ConsoleOption | undefined,\n previous: ResolvedConsole,\n diagnostics: Diagnostics,\n): ResolvedConsole {\n if (requested === undefined) {\n return previous;\n }\n if (requested === false) {\n return { level: null, styles: previous.styles };\n }\n if (requested === true) {\n return { level: CONSOLE_DEFAULT_LEVEL, styles: previous.styles };\n }\n if (typeof requested === \"string\") {\n const level = toLevel(requested);\n if (level === undefined) {\n reportInvalid(\n diagnostics,\n \"console\",\n LEVEL_EXPECTED,\n requested,\n \"the console level in force\",\n );\n return previous;\n }\n\n return { level, styles: previous.styles };\n }\n\n // Guard against null and other values that the type does not accept.\n if (typeof requested !== \"object\" || (requested as unknown) === null) {\n diagnostics.report(\n \"config.invalid\",\n \"console must be a boolean, a level or an object. The console settings in force stay.\",\n );\n return previous;\n }\n\n return {\n level: resolveConsoleLevel(requested.level, previous.level, diagnostics),\n styles: { ...previous.styles, ...validStyles(requested.styles, diagnostics) },\n };\n}\n\n/**\n * Merges and checks the sampling section. resolveConfig checks the rates after the merge.\n * @param input Sampling options that the consumer passed.\n * @param base Sampling options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The sampling options.\n */\nfunction resolveSampling(\n input: Partial<SamplingOptions> | undefined,\n base: SamplingOptions,\n diagnostics: Diagnostics,\n): SamplingOptions {\n const given = input ?? {};\n\n return {\n ...base,\n ...given,\n rates: { ...base.rates, ...given.rates },\n alwaysSampleTypes: resolveList(\n \"sampling.alwaysSampleTypes\",\n given.alwaysSampleTypes,\n base.alwaysSampleTypes,\n STRING_LIST_EXPECTED,\n toStringEntry,\n diagnostics,\n ),\n alwaysSampleFrom: resolveLevel(\n \"sampling.alwaysSampleFrom\",\n given.alwaysSampleFrom,\n base.alwaysSampleFrom,\n diagnostics,\n ),\n remote: resolveBoolean(\"sampling.remote\", given.remote, base.remote, diagnostics),\n };\n}\n\n/**\n * Merges and checks the bus section.\n * @param input Bus options that the consumer passed.\n * @param base Bus options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The bus options. Each trusted origin is a bare origin.\n */\nfunction resolveBus(\n input: Partial<BusOptions> | undefined,\n base: BusOptions,\n diagnostics: Diagnostics,\n): BusOptions {\n const given = input ?? {};\n\n return {\n maxTrackedSources: resolveInteger(\n \"bus.maxTrackedSources\",\n given.maxTrackedSources,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxTrackedSources,\n diagnostics,\n ),\n sourcePolicy: resolveChoice(\n \"bus.sourcePolicy\",\n given.sourcePolicy,\n [\"registered\", \"trusted-origin\"],\n base.sourcePolicy,\n diagnostics,\n ),\n validation: resolveChoice(\n \"bus.validation\",\n given.validation,\n [\"strict\", \"envelope\"],\n base.validation,\n diagnostics,\n ),\n maxMessageBytes: resolveInteger(\n \"bus.maxMessageBytes\",\n given.maxMessageBytes,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxMessageBytes,\n diagnostics,\n ),\n maxRecordsPerMessage: resolveInteger(\n \"bus.maxRecordsPerMessage\",\n given.maxRecordsPerMessage,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxRecordsPerMessage,\n diagnostics,\n ),\n maxMessagesPerSecond: resolveInteger(\n \"bus.maxMessagesPerSecond\",\n given.maxMessagesPerSecond,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxMessagesPerSecond,\n diagnostics,\n ),\n mode: resolveChoice(\"bus.mode\", given.mode, BUS_MODE_VALUES, base.mode, diagnostics),\n // Compare origins, not URLs. If not, an entry with a path never matches event.origin.\n trustedOrigins: resolveList(\n \"bus.trustedOrigins\",\n given.trustedOrigins,\n base.trustedOrigins,\n ORIGIN_LIST_EXPECTED,\n toOrigin,\n diagnostics,\n ),\n openFinRole: resolveChoice(\n \"bus.openFinRole\",\n given.openFinRole,\n OPENFIN_ROLE_VALUES,\n base.openFinRole,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the journey section.\n * @param input Journey options that the consumer passed.\n * @param base Journey options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The journey options.\n */\nfunction resolveJourney(\n input: Partial<JourneyOptions> | undefined,\n base: JourneyOptions,\n diagnostics: Diagnostics,\n): JourneyOptions {\n const given = input ?? {};\n\n return {\n scope: resolveChoice(\n \"journey.scope\",\n given.scope,\n JOURNEY_SCOPE_VALUES,\n base.scope,\n diagnostics,\n ),\n maxAgeMs: resolveInteger(\n \"journey.maxAgeMs\",\n given.maxAgeMs,\n JOURNEY_AGE_RANGE,\n base.maxAgeMs,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the retention section.\n * @param input Retention options that the consumer passed.\n * @param base Retention options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The retention options.\n */\nfunction resolveRetention(\n input: Partial<RetentionOptions> | undefined,\n base: RetentionOptions,\n diagnostics: Diagnostics,\n): RetentionOptions {\n const given = input ?? {};\n\n return {\n mode: resolveChoice(\n \"retention.mode\",\n given.mode,\n RETENTION_MODE_VALUES,\n base.mode,\n diagnostics,\n ),\n ...resolveRanges(\"retention\", given, base, RETENTION_RANGES, diagnostics),\n };\n}\n\n/**\n * Reads capture.console.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param diagnostics Diagnostics reporter.\n * @returns A boolean, or the accepted method names.\n */\nfunction resolveCaptureConsole(\n value: unknown,\n fallback: boolean | CapturedConsoleMethod[],\n diagnostics: Diagnostics,\n): boolean | CapturedConsoleMethod[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(\n diagnostics,\n \"capture.console\",\n CONSOLE_CAPTURE_EXPECTED,\n value,\n \"the value in force\",\n );\n return fallback;\n }\n\n return resolveList(\n \"capture.console\",\n value,\n [],\n CONSOLE_CAPTURE_EXPECTED,\n toConsoleMethod,\n diagnostics,\n );\n}\n\n/**\n * Merges and checks the capture section.\n * @param input Capture options that the consumer passed.\n * @param base Capture options in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The capture options.\n */\nfunction resolveCapture(\n input: Partial<CaptureOptions> | undefined,\n base: CaptureOptions,\n diagnostics: Diagnostics,\n): CaptureOptions {\n const given = input ?? {};\n const capture: CaptureOptions = {\n ...base,\n ...given,\n remoteToggles: resolveList(\n \"capture.remoteToggles\",\n given.remoteToggles,\n base.remoteToggles,\n \"a list of capture switch names without privacy controls\",\n (value) => REMOTE_CAPTURE_FLAGS.find((key) => key === value),\n diagnostics,\n ),\n resourceTiming: resolveResourceTiming(given.resourceTiming, base.resourceTiming, diagnostics),\n interactions: resolveInteractions(given.interactions, base.interactions, diagnostics),\n console: resolveCaptureConsole(given.console, base.console, diagnostics),\n longFrameThresholdMs: resolveNonNegative(\n \"capture.longFrameThresholdMs\",\n given.longFrameThresholdMs,\n base.longFrameThresholdMs,\n diagnostics,\n ),\n ignoreUrls: resolveList(\n \"capture.ignoreUrls\",\n given.ignoreUrls,\n base.ignoreUrls,\n PATTERN_LIST_EXPECTED,\n toPattern,\n diagnostics,\n ),\n userTimingInclude: resolveList(\n \"capture.userTimingInclude\",\n given.userTimingInclude,\n base.userTimingInclude,\n PATTERN_LIST_EXPECTED,\n toPattern,\n diagnostics,\n ),\n // A string target is an origin. A substring test also matches a query value or a longer host.\n propagateTraceHeaderTo: resolveList(\n \"capture.propagateTraceHeaderTo\",\n given.propagateTraceHeaderTo,\n base.propagateTraceHeaderTo,\n TARGET_LIST_EXPECTED,\n toTarget,\n diagnostics,\n ),\n plugins: resolveList(\n \"capture.plugins\",\n given.plugins,\n base.plugins,\n \"a list of objects with a name, install() and uninstall()\",\n toPlugin,\n diagnostics,\n ),\n };\n\n for (const key of CAPTURE_FLAG_KEYS) {\n capture[key] = resolveBoolean(`capture.${key}`, given[key], base[key], diagnostics);\n }\n\n return capture;\n}\n\n/** Checks resource timing settings. An invalid value keeps the settings in force. */\nfunction resolveResourceTiming(\n value: unknown,\n base: CaptureOptions[\"resourceTiming\"],\n diagnostics: Diagnostics,\n): CaptureOptions[\"resourceTiming\"] {\n if (value === undefined) {\n return base;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (!isObject(value)) {\n diagnostics.report(\n \"config.invalid\",\n \"capture.resourceTiming must be a boolean or an options object.\",\n );\n return base;\n }\n\n return {\n slowMs: resolveNonNegative(\n \"capture.resourceTiming.slowMs\",\n value.slowMs,\n typeof base === \"object\" ? (base.slowMs ?? RESOURCE_SLOW_MS) : RESOURCE_SLOW_MS,\n diagnostics,\n ),\n };\n}\n\n/**\n * Checks the click settings. An invalid value does not turn on text or selector capture.\n * @param value Settings that the app supplied.\n * @param base Settings in force.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid settings, with invalid values replaced by the values in force.\n */\nfunction resolveInteractions(\n value: CaptureOptions[\"interactions\"] | undefined,\n base: CaptureOptions[\"interactions\"],\n diagnostics: Diagnostics,\n): CaptureOptions[\"interactions\"] {\n if (value === undefined) return base;\n if (typeof value === \"boolean\") return value;\n if (!isObject(value)) {\n diagnostics.report(\n \"config.invalid\",\n \"capture.interactions must be a boolean or an options object.\",\n );\n return base;\n }\n const previous = typeof base === \"object\" ? base : {};\n const ignore = value.ignoreSelector;\n let ignoreSelector = ignore === undefined ? previous.ignoreSelector : ignore;\n if (ignoreSelector !== undefined && ignoreSelector !== null) {\n try {\n if (typeof ignoreSelector !== \"string\") throw new Error(\"Invalid selector\");\n if (typeof document !== \"undefined\") document.createElement(\"div\").matches(ignoreSelector);\n } catch {\n diagnostics.report(\n \"config.invalid\",\n \"capture.interactions.ignoreSelector must be a valid CSS selector or null.\",\n );\n ignoreSelector = previous.ignoreSelector;\n }\n }\n // The name goes into a CSS attribute selector. Letters, digits, hyphens and underscores need no\n // escape. Another name keeps the attribute in force.\n let actionAttribute = previous.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n if (value.actionAttribute !== undefined) {\n if (typeof value.actionAttribute === \"string\" && /^[a-z][\\w-]*$/i.test(value.actionAttribute)) {\n actionAttribute = value.actionAttribute;\n } else {\n reportInvalid(\n diagnostics,\n \"capture.interactions.actionAttribute\",\n \"an attribute name of letters, digits, hyphens and underscores\",\n value.actionAttribute,\n `\"${actionAttribute}\"`,\n );\n }\n }\n return {\n actionAttribute,\n text: resolveBoolean(\n \"capture.interactions.text\",\n value.text,\n previous.text ?? false,\n diagnostics,\n ),\n selector: resolveBoolean(\n \"capture.interactions.selector\",\n value.selector,\n previous.selector ?? false,\n diagnostics,\n ),\n ignoreSelector:\n typeof ignoreSelector === \"string\" || ignoreSelector === null ? ignoreSelector : undefined,\n maxTextChars: resolveInteger(\n \"capture.interactions.maxTextChars\",\n value.maxTextChars,\n [0, Number.MAX_SAFE_INTEGER],\n previous.maxTextChars ?? 50,\n diagnostics,\n ),\n rageClicks: resolveBoolean(\n \"capture.interactions.rageClicks\",\n value.rageClicks,\n previous.rageClicks ?? false,\n diagnostics,\n ),\n rageClickCount: resolveInteger(\n \"capture.interactions.rageClickCount\",\n value.rageClickCount,\n [2, 20],\n previous.rageClickCount ?? RAGE_CLICK_COUNT,\n diagnostics,\n ),\n rageClickWindowMs: resolveInteger(\n \"capture.interactions.rageClickWindowMs\",\n value.rageClickWindowMs,\n CLICK_WAIT_RANGE,\n previous.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS,\n diagnostics,\n ),\n deadClicks: resolveBoolean(\n \"capture.interactions.deadClicks\",\n value.deadClicks,\n previous.deadClicks ?? false,\n diagnostics,\n ),\n deadClickMs: resolveInteger(\n \"capture.interactions.deadClickMs\",\n value.deadClickMs,\n CLICK_WAIT_RANGE,\n previous.deadClickMs ?? DEAD_CLICK_MS,\n diagnostics,\n ),\n };\n}\n\n/** Result of a signal endpoint that is off, for each key. */\nconst SIGNAL_OFF = {\n metricsEndpoint: \"The library sends metric records as log records.\",\n tracesEndpoint: \"The library sends no span.\",\n} as const;\n\n/**\n * Validates the metrics or traces endpoint. Only the OTLP serializer has these formats.\n * @param key Config key.\n * @param value Value that the consumer passed.\n * @param fallback Value in force.\n * @param serializer Resolved serializer option.\n * @param diagnostics Diagnostics reporter.\n * @returns A valid absolute URL, or \"\" to turn the endpoint off.\n */\nfunction resolveSignalEndpoint(\n key: keyof typeof SIGNAL_OFF,\n value: unknown,\n fallback: string,\n serializer: SerializerChoice,\n diagnostics: Diagnostics,\n): string {\n let url = fallback;\n\n if (typeof value === \"string\" && value !== \"\") {\n try {\n new URL(value);\n url = value;\n } catch (error) {\n diagnostics.report(\n \"config.invalid\",\n `${key} is not a valid absolute URL: ${recordedUrl(value, false)}. The library keeps the value in force.`,\n undefined,\n error,\n );\n }\n } else if (value === \"\") {\n url = \"\";\n } else if (value !== undefined) {\n reportInvalid(diagnostics, key, \"a URL string\", value, \"the value in force\");\n }\n\n // A custom or ECS serializer cannot encode a metrics or traces request.\n if (url !== \"\" && serializer !== SERIALIZER_NAME_OTLP) {\n diagnostics.report(\n \"config.invalid\",\n `${key} needs serializer \"${SERIALIZER_NAME_OTLP}\". ${SIGNAL_OFF[key]}`,\n );\n return \"\";\n }\n\n return url;\n}\n\n/** Rules in the form that resolvePolicy() reads. POLICY_RULES holds the typed form. */\ninterface PolicyLookup {\n /** Accepted range of each number key. */\n ranges: Partial<Record<string, Range>>;\n /** Accepted values of each choice key. */\n choices?: Partial<Record<string, readonly string[]>>;\n /** Resolver of each key with another value type. */\n custom?: Partial<Record<string, CustomResolver>>;\n}\n\n/**\n * Checks one policy section. An invalid value keeps the value in force.\n * @param name Section name for diagnostic messages.\n * @param input Settings that the app supplied.\n * @param base Settings in force.\n * @param rules Ranges and choices of the section.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid section.\n */\nfunction resolvePolicy<T extends object>(\n name: string,\n input: Partial<T> | undefined,\n base: T,\n rules: PolicyLookup,\n diagnostics: Diagnostics,\n): T {\n const next = { ...base };\n for (const key of Object.keys(base) as (keyof T & string)[]) {\n const value: unknown = input?.[key];\n const fallback: unknown = base[key];\n const range = rules.ranges[key];\n const choice = rules.choices?.[key];\n const custom = rules.custom?.[key];\n let resolved: unknown = fallback;\n if (custom) {\n resolved = custom(`${name}.${key}`, value, fallback, diagnostics);\n } else if (typeof fallback === \"number\" && range) {\n resolved = resolveInteger(`${name}.${key}`, value, range, fallback, diagnostics);\n } else if (typeof fallback === \"boolean\") {\n resolved = resolveBoolean(`${name}.${key}`, value, fallback, diagnostics);\n } else if (choice) {\n resolved = resolveChoice(`${name}.${key}`, value, choice, String(fallback), diagnostics);\n } else if (value === undefined || typeof value === \"string\") {\n resolved = value ?? fallback;\n } else {\n reportInvalid(diagnostics, `${name}.${key}`, \"a string\", value, String(fallback));\n }\n Object.assign(next, { [key]: resolved });\n }\n return next;\n}\n\n/**\n * Resolves partial configuration inputs into a validated ResolvedConfig object.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n * @param previous Active configuration instance for incremental reconfigurations.\n * @returns Complete, validated configuration object.\n */\nexport function resolveConfig(\n input: Partial<ObservabilityConfig>,\n diagnostics: Diagnostics,\n previous?: ResolvedConfig,\n): ResolvedConfig {\n const base = previous ?? DEFAULT_CONFIG;\n\n // Check each policy section with its own rules. The key order of POLICY_RULES sets the report order.\n const policies = Object.fromEntries(\n (Object.keys(POLICY_RULES) as PolicySection[]).map((key) => [\n key,\n resolvePolicy(key, input[key], base[key], POLICY_RULES[key], diagnostics),\n ]),\n ) as Pick<ResolvedConfig, PolicySection>;\n const merged: ResolvedConfig = {\n ...base,\n ...input,\n ...policies,\n\n lockConfiguration: resolveBoolean(\n \"lockConfiguration\",\n input.lockConfiguration,\n base.lockConfiguration,\n diagnostics,\n ),\n loggerCache: {\n maxEntries: resolveCacheLimit(\n input.loggerCache?.maxEntries,\n base.loggerCache.maxEntries,\n diagnostics,\n ),\n },\n securityContext: {\n id:\n typeof input.securityContext?.id === \"string\"\n ? input.securityContext.id || base.securityContext.id\n : base.securityContext.id,\n isolation: resolveBoolean(\n \"securityContext.isolation\",\n input.securityContext?.isolation,\n base.securityContext.isolation,\n diagnostics,\n ),\n },\n // An unset environment variable gives undefined. Keep the current endpoint.\n endpoint: input.endpoint === undefined ? base.endpoint : input.endpoint,\n // A bad value reports config.invalid. The value in force stays. Without this check, a bad\n // minLevel drops each record with no message.\n enabled: resolveBoolean(\"enabled\", input.enabled, base.enabled, diagnostics),\n payloadMode: resolveChoice(\n \"payloadMode\",\n input.payloadMode,\n [\"copy\", \"defer\"] as const,\n base.payloadMode,\n diagnostics,\n ),\n minLevel: resolveLevel(\"minLevel\", input.minLevel, base.minLevel, diagnostics),\n minLevels: resolveMinLevels(input.minLevels, base.minLevels, diagnostics),\n processors: resolveList(\n \"processors\",\n input.processors,\n base.processors,\n \"a list of functions\",\n toProcessor,\n diagnostics,\n ),\n compression: resolveChoice(\n \"compression\",\n input.compression,\n COMPRESSION_VALUES,\n base.compression,\n diagnostics,\n ),\n credentials: resolveChoice(\n \"credentials\",\n input.credentials,\n CREDENTIALS_VALUES,\n base.credentials,\n diagnostics,\n ),\n headers:\n \"headers\" in input ? resolveHeaders(input.headers, base.headers, diagnostics) : base.headers,\n storage: resolveChoice(\"storage\", input.storage, STORAGE_VALUES, base.storage, diagnostics),\n identity: resolveChoice(\n \"identity\",\n input.identity,\n IDENTITY_VALUES,\n base.identity,\n diagnostics,\n ),\n // A serializer instance replaces the string name after the object merge.\n serializer: resolveSerializer(input.serializer, previous?.serializer, diagnostics),\n console: resolveConsole(input.console, base.console, diagnostics),\n sampling: resolveSampling(input.sampling, base.sampling, diagnostics),\n bus: resolveBus(input.bus, base.bus, diagnostics),\n batching: resolveRanges(\n \"batching\",\n input.batching,\n base.batching,\n BATCHING_RANGES,\n diagnostics,\n ),\n retention: resolveRetention(input.retention, base.retention, diagnostics),\n limits: resolveRanges(\"limits\", input.limits, base.limits, LIMIT_RANGES, diagnostics),\n journey: resolveJourney(input.journey, base.journey, diagnostics),\n capture: resolveCapture(input.capture, base.capture, diagnostics),\n };\n\n for (const key of [\"metricsEndpoint\", \"tracesEndpoint\"] as const) {\n merged[key] = resolveSignalEndpoint(key, input[key], base[key], merged.serializer, diagnostics);\n }\n\n // Guard against a value that cannot send. Keep the function in force.\n // Without a transport, the pipeline drops each batch.\n if (merged.transport !== undefined && typeof merged.transport !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transport must be a function. The library ignores the value.\",\n );\n merged.transport = base.transport;\n }\n\n if (merged.onDrop !== undefined && typeof merged.onDrop !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"onDrop must be a function. The library ignores the value.\",\n );\n merged.onDrop = base.onDrop;\n }\n\n if (merged.contextProvider !== undefined && typeof merged.contextProvider !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must be a function. The library ignores the value.\",\n );\n merged.contextProvider = base.contextProvider;\n }\n\n if (merged.transportWorker !== undefined && typeof merged.transportWorker !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transportWorker must be a function. The library keeps the value in force.\",\n );\n merged.transportWorker = base.transportWorker;\n }\n\n if (merged.transportOnExit !== undefined && typeof merged.transportOnExit !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transportOnExit must be a function. The library ignores the value.\",\n );\n merged.transportOnExit = base.transportOnExit;\n }\n\n // null selects console-only mode. That value is valid. Report only an empty string.\n // A custom transport needs no endpoint.\n if (merged.endpoint === \"\") {\n if (merged.transport === undefined) {\n diagnostics.report(\n \"config.invalid\",\n \"endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.\",\n );\n }\n } else if (merged.endpoint !== null) {\n try {\n new URL(merged.endpoint);\n } catch (error) {\n diagnostics.report(\n \"config.invalid\",\n `endpoint is not a valid absolute URL: ${recordedUrl(merged.endpoint, false)}.`,\n undefined,\n error,\n );\n }\n }\n\n // Only the delivery stack sends. It loads only with an endpoint or a custom transport.\n for (const key of [\"metricsEndpoint\", \"tracesEndpoint\"] as const) {\n if (merged[key] !== \"\" && merged.endpoint === null && !merged.transport) {\n diagnostics.report(\n \"config.invalid\",\n `${key} needs endpoint or transport. The library sends nothing to ${key}.`,\n );\n }\n }\n\n if (!merged.serviceName) {\n diagnostics.report(\n \"config.invalid\",\n `serviceName is missing. Every record reports service.name as '${UNKNOWN_SERVICE_NAME}'.`,\n );\n merged.serviceName = UNKNOWN_SERVICE_NAME;\n }\n\n const rate: unknown = merged.sampling.defaultRate;\n if (typeof rate !== \"number\" || rate < SAMPLING_RATE_MIN || rate > SAMPLING_RATE_MAX) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.defaultRate must be 0..1. The value is ${String(rate)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.defaultRate = SAMPLING_RATE_FALLBACK;\n }\n\n const maxRate: unknown = merged.sampling.remoteMaxRate;\n // The negated range test also rejects NaN.\n if (\n typeof maxRate !== \"number\" ||\n !(maxRate >= SAMPLING_RATE_MIN && maxRate <= SAMPLING_RATE_MAX)\n ) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.remoteMaxRate must be 0..1. The value is ${String(maxRate)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.remoteMaxRate = SAMPLING_RATE_FALLBACK;\n }\n\n const rates: [string, unknown][] = Object.entries(merged.sampling.rates);\n for (const [ns, r] of rates) {\n if (typeof r !== \"number\" || r < SAMPLING_RATE_MIN || r > SAMPLING_RATE_MAX) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.rates[\"${ns}\"] must be 0..1. The value is ${String(r)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.rates[ns] = SAMPLING_RATE_FALLBACK;\n }\n }\n\n // Replace the previous endpoints in the ignore list. This prevents a self-logging loop.\n // Without it, one failed POST logs another failed POST with no end.\n merged.capture.ignoreUrls = merged.capture.ignoreUrls.filter(\n (url) =>\n url !== previous?.endpoint &&\n url !== previous?.metricsEndpoint &&\n url !== previous?.tracesEndpoint,\n );\n for (const url of [merged.endpoint, merged.metricsEndpoint, merged.tracesEndpoint]) {\n if (url && !merged.capture.ignoreUrls.includes(url)) {\n merged.capture.ignoreUrls = [...merged.capture.ignoreUrls, url];\n }\n }\n\n if (merged.delivery.retryMaxDelayMs < merged.delivery.retryBaseDelayMs) {\n diagnostics.report(\n \"config.invalid\",\n \"delivery.retryMaxDelayMs must be at least retryBaseDelayMs.\",\n );\n merged.delivery.retryBaseDelayMs = base.delivery.retryBaseDelayMs;\n merged.delivery.retryMaxDelayMs = base.delivery.retryMaxDelayMs;\n }\n if (\n merged.capture.urlTransform !== undefined &&\n typeof merged.capture.urlTransform !== \"function\"\n ) {\n diagnostics.report(\"config.invalid\", \"capture.urlTransform must be a function.\");\n merged.capture.urlTransform = base.capture.urlTransform;\n }\n reportUnknownKeys(input, diagnostics);\n\n return merged;\n}\n\n/**\n * Reports each config key that the schema does not know. It checks the top level and\n * one level inside each section. A typo passes the `Partial` type check and has no effect.\n * Examples are `remoteUrl` for `endpoint` and `capture.webVital` for `capture.webVitals`.\n * Namespace keys under `sampling.rates` are free-form and one level deeper. The check\n * skips them.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n */\nfunction reportUnknownKeys(input: Partial<ObservabilityConfig>, diagnostics: Diagnostics): void {\n const known = new Set<string>([...Object.keys(DEFAULT_CONFIG), ...UNDEFAULTED_CONFIG_KEYS]);\n\n for (const key of Object.keys(input)) {\n if (!known.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown config key \"${key}\". Check the spelling.`,\n );\n }\n }\n\n for (const section of CONFIG_SECTIONS) {\n const values: unknown = input[section];\n\n if (typeof values !== \"object\" || values === null) {\n continue;\n }\n\n const sectionKeys = new Set<string>([\n ...Object.keys(DEFAULT_CONFIG[section]),\n ...UNDEFAULTED_SECTION_KEYS[section],\n ]);\n\n for (const key of Object.keys(values)) {\n if (!sectionKeys.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown config key \"${section}.${key}\". Check the spelling.`,\n );\n }\n }\n }\n}\n\n/**\n * Changes the active configuration object in place. Subsystems that hold a section\n * reference see the update.\n * @param target Active configuration object to change.\n * @param next Configuration object with the new values.\n */\nexport function applyResolvedConfig(target: ResolvedConfig, next: ResolvedConfig): void {\n for (const key of Object.keys(next) as (keyof ResolvedConfig)[]) {\n // The cast widens the tuple. Then includes accepts any string key. With satisfies,\n // the tuple stays narrow and each non-section key fails to compile.\n if ((CONFIG_SECTIONS as readonly string[]).includes(key)) {\n continue;\n }\n Object.assign(target, { [key]: next[key] });\n }\n\n // Merge each section object in place to keep its reference. A new object leaves\n // subsystems on the old section from construction.\n for (const section of CONFIG_SECTIONS) {\n Object.assign(target[section] as object, next[section] as object);\n }\n}\n","// src/core/context.ts\n//\n// This store keeps ambient context attributes. The logger merges them into each later record.\n// Keep the store per instance, not at module level. All runtimes in a realm share a module Map.\n\n/** Key-value store for ambient context attributes attached to log records. */\nexport class ContextStore {\n /** Backing store mapping attribute keys to raw values. */\n private readonly map = new Map<string, unknown>();\n\n /**\n * Sets an ambient context attribute key and value.\n * @param key Attribute key.\n * @param value Raw attribute value.\n */\n set(key: string, value: unknown): void {\n this.map.set(key, value);\n }\n\n /**\n * Merges multiple key-value pairs into the ambient context store.\n * @param values Record of attributes to merge.\n */\n setMany(values: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(values)) {\n this.map.set(key, value);\n }\n }\n\n /**\n * Deletes an attribute from the ambient context store.\n * @param key Attribute key to remove.\n */\n remove(key: string): void {\n this.map.delete(key);\n }\n\n /** Removes all ambient context attributes. */\n clear(): void {\n this.map.clear();\n }\n\n /**\n * Returns a copy of all ambient context attributes. The copy prevents a merge\n * target or a sanitizer from changing the store.\n * @returns Plain object containing stored key-value pairs.\n */\n getAll(): Record<string, unknown> {\n return Object.fromEntries(this.map);\n }\n}\n","// src/core/debug-buffer.ts\n//\n// Keeps the recent records that minLevel or sampling dropped. An error record of this context\n// sends them first. They show what happened before the error.\n\nimport { ATTR_DEBUG_BUFFER } from \"../constants\";\nimport type { DebugBufferPolicy } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** One kept record and the time when the buffer took it. */\ninterface Kept {\n /** Epoch time in milliseconds when the buffer took the record. */\n at: number;\n /** Built record. The privacy hooks already ran on it. */\n record: LogRecord;\n}\n\n/** Bounded list of the records that the library dropped by level or by sampling. */\nexport class DebugBuffer {\n /** Kept records, oldest first. It can hold up to two times maxRecords between trims. */\n private kept: Kept[] = [];\n\n /**\n * @param policy Gives the settings in force. A later configure() can change them.\n */\n constructor(private readonly policy: () => DebugBufferPolicy) {}\n\n /**\n * Keeps a record. When the buffer is full, the oldest record leaves first.\n * @param record Built record. The privacy hooks already ran on it.\n */\n push(record: LogRecord): void {\n const { enabled, maxRecords } = this.policy();\n if (!enabled) {\n return;\n }\n\n this.kept.push({ at: Date.now(), record });\n // Trim in steps. A trim at each push would copy the whole list each time.\n if (this.kept.length >= maxRecords * 2) {\n this.kept = this.kept.slice(-maxRecords);\n }\n }\n\n /**\n * Takes the kept records that are not too old, and empties the buffer.\n * @returns The records, oldest first. Each has `uiobs.debug_buffer: true`.\n */\n drain(): LogRecord[] {\n const kept = this.live();\n this.kept = [];\n\n return kept.map(({ record }) => ({\n ...record,\n attributes: { ...record.attributes, [ATTR_DEBUG_BUFFER]: true },\n }));\n }\n\n /**\n * Gives the kept records without taking them.\n * @returns The records, oldest first.\n */\n snapshot(): LogRecord[] {\n return this.live().map(({ record }) => record);\n }\n\n /**\n * Gives the kept records that the settings in force permit. A buffer that is off empties itself.\n * @returns The records, oldest first.\n */\n private live(): Kept[] {\n const { enabled, maxRecords, maxAgeMs } = this.policy();\n if (!enabled) {\n this.kept = [];\n return [];\n }\n\n const oldest = maxAgeMs === 0 ? -Infinity : Date.now() - maxAgeMs;\n\n return this.kept.slice(-maxRecords).filter((entry) => entry.at >= oldest);\n }\n\n /** Removes each kept record. The records of an old session or identity must not go out. */\n clear(): void {\n this.kept = [];\n }\n}\n","// src/core/diagnostics.ts\n//\n// This module reports internal errors of the library. It limits the emit rate.\n// It counts every event.\n\nimport { DIAGNOSTIC_THROTTLE_MS, LIBRARY_LOG_PREFIX } from \"../constants\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\n\n/** Closed set of diagnostic event codes emitted by library subsystems. */\nexport type DiagnosticCode =\n | \"config.locked\"\n | \"security.rotated\"\n | \"security.context_mismatch\"\n | \"record.dropped_during_rotation\"\n | \"bus.rejected_message\"\n | \"config.invalid\"\n | \"config.reconfigured\"\n | \"record.sanitize_failed\"\n | \"record.truncated\"\n | \"record.dropped_by_level\"\n | \"record.dropped_by_sampling\"\n | \"record.dropped_by_ceiling\"\n | \"record.dropped_by_processor\"\n | \"record.dropped_by_redact\"\n | \"record.dropped_boot_buffer_full\"\n | \"record.dropped_malformed\"\n | \"record.dropped_no_destination\"\n | \"runtime.version_mismatch\"\n | \"journey.expired\"\n | \"journey.adopted\"\n | \"journey.token_too_large\"\n | \"trace.otel_failed\"\n | \"bus.role_resolved\"\n | \"bus.no_owner\"\n | \"bus.handshake_timeout\"\n | \"bus.untrusted_origin\"\n | \"bus.send_failed\"\n | \"transport.http_error\"\n | \"transport.timeout\"\n | \"transport.batch_split\"\n | \"transport.throttled\"\n | \"transport.dropped_permanent\"\n | \"transport.rejected_credentials\"\n | \"transport.serialize_failed\"\n | \"storage.unavailable\"\n | \"storage.degraded\"\n | \"storage.quota_exceeded\"\n | \"storage.evicted\"\n | \"storage.dead_lettered\"\n | \"pipeline.crashed\"\n | \"capture.install_failed\"\n | \"capture.rate_limited\"\n | \"capture.header_failed\"\n | \"capture.record_failed\"\n | \"capture.transport_request\"\n | \"openfin.unavailable\"\n | \"platform.api_blocked\"\n | \"handler.threw\";\n\n/** Diagnostic event payload dispatched to consumer handlers. */\nexport interface DiagnosticEvent {\n /** Diagnostic fault code. */\n code: DiagnosticCode;\n /** Description for a person to read. */\n message: string;\n /** Structured context metadata. */\n detail?: Record<string, unknown>;\n /** Caught error instance or reason. */\n cause?: unknown;\n /** Event timestamp in epoch milliseconds. */\n at: number;\n /** Total count of this code since startup. It includes rate-limited occurrences. */\n count: number;\n}\n\n/** Consumer callback for receiving rate-limited diagnostic events. */\nexport type DiagnosticHandler = (event: DiagnosticEvent) => void;\n\n/** Reports internal errors. It limits the dispatch rate but counts every event. */\nexport class Diagnostics {\n /** Running occurrence counts per diagnostic code. */\n private readonly counters = new Map<DiagnosticCode, number>();\n\n /** Timestamp of last emitted event per code in epoch milliseconds. */\n private readonly lastEmitted = new Map<DiagnosticCode, number>();\n\n /**\n * @param handler Optional diagnostic event listener callback.\n * @param throttleMs Minimum duration in milliseconds between emitted events for a single code.\n * @param consoleFallback True to print a fixed warning if the diagnostic handler throws.\n */\n constructor(\n private handler?: DiagnosticHandler,\n private throttleMs = DIAGNOSTIC_THROTTLE_MS,\n private consoleFallback = false,\n ) {}\n\n /**\n * Changes the report interval and the console fallback rule.\n * @param throttleMs Minimum wait between reports of one code, in milliseconds.\n * @param consoleFallback True to print a fixed warning if the handler throws.\n */\n setPolicy(throttleMs: number, consoleFallback: boolean): void {\n this.throttleMs = throttleMs;\n this.consoleFallback = consoleFallback;\n }\n\n /**\n * Updates or removes the active diagnostic event handler.\n * @param handler New diagnostic event handler.\n */\n setHandler(handler?: DiagnosticHandler): void {\n this.handler = handler;\n }\n\n /**\n * Increments the count for a code. It does not call the handler.\n * @param code Diagnostic code to increment.\n * @param by Increment delta.\n * @returns New total for the code.\n */\n count(code: DiagnosticCode, by = 1): number {\n const total = (this.counters.get(code) ?? 0) + by;\n this.counters.set(code, total);\n return total;\n }\n\n /**\n * Increments the counter for the code. It sends the event to the handler when the\n * throttle window has passed. It never throws.\n * @param code Diagnostic code.\n * @param message Event description.\n * @param detail Optional structured metadata.\n * @param cause Caught error instance or reason.\n */\n report(\n code: DiagnosticCode,\n message: string,\n detail?: Record<string, unknown>,\n cause?: unknown,\n ): void {\n const count = this.count(code);\n const now = Date.now();\n const last = this.lastEmitted.get(code) ?? 0;\n if (now - last < this.throttleMs) {\n return;\n }\n this.lastEmitted.set(code, now);\n\n const event: DiagnosticEvent = {\n code,\n message,\n detail,\n cause,\n at: now,\n count,\n };\n\n const { handler } = this;\n\n if (!handler) {\n return;\n }\n try {\n // The console capture skips a console call of the handler. Without the scope, the line\n // gives a record, and a failed send of that record gives a new diagnostic.\n runAsLibraryConsole(() => {\n handler(event);\n });\n } catch (_handlerError) {\n // Increment the counter directly. A call to report() recurses when the handler throws.\n this.count(\"handler.threw\");\n if (this.consoleFallback && typeof console !== \"undefined\") {\n // The console capture skips a call in this scope.\n runAsLibraryConsole(() => {\n // eslint-disable-next-line no-console -- Fallback sink when diagnostic handler throws.\n console.warn(`${LIBRARY_LOG_PREFIX} The onDiagnostic handler threw an error.`);\n });\n }\n }\n }\n\n /**\n * Executes a synchronous function and reports any thrown error to diagnostics.\n * @param code Diagnostic code to report on throw.\n * @param message ASD-STE100 sentence that states the failure. The handler gets it as the event message.\n * @param fn Function to execute.\n * @returns Function return value, or undefined on throw.\n */\n guard<T>(code: DiagnosticCode, message: string, fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Executes an asynchronous function and reports any rejected promise to diagnostics.\n * @param code Diagnostic code to report on rejection.\n * @param message ASD-STE100 sentence that states the failure. The handler gets it as the event message.\n * @param fn Async function to execute.\n * @returns Promise that resolves to the return value, or undefined on rejection.\n */\n async guardAsync<T>(\n code: DiagnosticCode,\n message: string,\n fn: () => Promise<T>,\n ): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Returns a copy of all cumulative diagnostic event counts since initialization.\n * @returns Map of diagnostic codes to occurrence counts.\n */\n snapshot(): Record<string, number> {\n return Object.fromEntries(this.counters);\n }\n}\n","// src/core/drops.ts\n//\n// This module collects lost records into onDrop summaries. It sends one summary for each\n// reason after the current task. A storm of losses then gives one call, not one per record.\n\nimport { ATTR_JOURNEY_ID, DROP_SUMMARY_MAX_ITEMS } from \"../constants\";\nimport { attributeOf, isActionRecord } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { DropSummary, LossReason } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Adds a value to a summary list. The list keeps each value one time, up to the limit.\n * @param list Summary list.\n * @param value Value to add.\n */\nfunction addCapped(list: string[], value: string): void {\n if (list.length < DROP_SUMMARY_MAX_ITEMS && !list.includes(value)) {\n list.push(value);\n }\n}\n\n/** Collects lost records and gives one summary for each reason to the onDrop hook. */\nexport class DropReporter {\n /** Summaries that wait for the end of the task, one for each reason. */\n private readonly pending = new Map<LossReason, DropSummary>();\n\n /** True while a microtask waits to send the summaries. */\n private scheduled = false;\n\n /** True while the hook runs. A loss that the hook causes is not reported again. */\n private reporting = false;\n\n /**\n * @param config Active configuration. The reporter reads `onDrop` from it at each call.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Adds lost records to the summary of their reason. Without an onDrop hook, it does nothing.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n add(reason: LossReason, records: readonly LogRecord[], batchIds: readonly string[] = []): void {\n // A hook that logs can fill a buffer again. A report of that loss starts a loop.\n if (!this.config.onDrop || this.reporting) {\n return;\n }\n\n // A failed load with an empty buffer loses nothing. A corrupt entry has no id to report.\n if (records.length === 0 && batchIds.length === 0) {\n return;\n }\n\n let summary = this.pending.get(reason);\n if (!summary) {\n summary = { reason, records: 0, batchIds: [], journeyIds: [], actions: [] };\n this.pending.set(reason, summary);\n }\n\n summary.records += records.length;\n for (const id of batchIds) {\n addCapped(summary.batchIds, id);\n }\n\n for (const record of records) {\n // A record from storage can be corrupt. It can be null or have no attributes.\n const journey = attributeOf(record, ATTR_JOURNEY_ID);\n if (typeof journey === \"string\") {\n addCapped(summary.journeyIds, journey);\n }\n\n const body: unknown = isActionRecord(record) ? record.body : undefined;\n if (typeof body === \"string\") {\n addCapped(summary.actions, body);\n }\n }\n\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => {\n this.flush();\n });\n }\n }\n\n /** Gives each waiting summary to the hook. A hook that throws does not stop the others. */\n private flush(): void {\n this.scheduled = false;\n const summaries = [...this.pending.values()];\n this.pending.clear();\n\n const onDrop = this.config.onDrop;\n if (!onDrop) {\n return;\n }\n\n this.reporting = true;\n for (const summary of summaries) {\n this.diagnostics.guard(\"handler.threw\", \"The onDrop hook threw an error.\", () => {\n // The capture modules skip a request or a console line of the hook. A captured line\n // gives a record. That record can evict one more stored batch.\n runAsLibraryRequest(() => {\n runAsLibraryConsole(() => {\n onDrop(summary);\n });\n });\n });\n }\n this.reporting = false;\n }\n}\n","// src/core/hold-buffer.ts\n//\n// This module holds records while the runtime cannot deliver them. An action is an audit fact.\n// Actions have their own cap. A storm of other records cannot push an action out.\n\nimport { BUS_MAX_BOOT_BUFFER_ACTIONS, BUS_MAX_BOOT_BUFFER_RECORDS } from \"../constants\";\nimport { isActionRecord } from \"../models/batch\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** Holds records in arrival order. A full buffer drops its oldest record of the same kind. */\nexport class HoldBuffer {\n /** Held records in arrival order. */\n private held: LogRecord[] = [];\n\n /** Number of held actions. A count finds a full buffer without a scan at each push. */\n private actions = 0;\n\n /**\n * @param onDrop Receives the record that a full buffer drops.\n */\n constructor(private readonly onDrop: (record: LogRecord) => void) {}\n\n /** Held records in arrival order. */\n get records(): readonly LogRecord[] {\n return this.held;\n }\n\n /** Number of held records. */\n get length(): number {\n return this.held.length;\n }\n\n /**\n * Adds a record. A full buffer drops its oldest record of the same kind.\n * @param record Record to hold.\n */\n push(record: LogRecord): void {\n const action = isActionRecord(record);\n const count = action ? this.actions : this.held.length - this.actions;\n const cap = action ? BUS_MAX_BOOT_BUFFER_ACTIONS : BUS_MAX_BOOT_BUFFER_RECORDS;\n\n if (count < cap) {\n this.actions += action ? 1 : 0;\n } else {\n // Scan only at the cap. A scan at each push is quadratic in a log storm.\n const oldest = this.held.findIndex((one) => isActionRecord(one) === action);\n const [dropped] = this.held.splice(oldest, 1);\n this.onDrop(dropped);\n }\n\n this.held.push(record);\n }\n\n /**\n * Removes the held records.\n * @returns The records in arrival order.\n */\n take(): LogRecord[] {\n const records = this.held;\n this.held = [];\n this.actions = 0;\n return records;\n }\n}\n","// src/core/measure.ts\n//\n// Times one operation with named phases. Each phase and the total go into duration histograms.\n// With a span, the operation is that span with one child span for each phase.\n\nimport { METRIC_DEFAULT_BOUNDARIES } from \"../constants\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport { type ClientSpan, newSpanId } from \"../utils/tracing\";\nimport type { SpanData } from \"./spans\";\n\n/** Total duration of each measure, in milliseconds. */\nconst TOTAL_DURATION: InstrumentDef = {\n name: \"ui.measure.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Duration of each phase, in milliseconds. */\nconst PHASE_DURATION: InstrumentDef = {\n name: \"ui.measure.phase.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Receivers of the values of one measure. */\nexport interface MeasureSinks {\n /** Adds a value to a histogram. */\n metric(def: InstrumentDef, value: number, attributes: MetricAttributes): void;\n /** Records one span. */\n span(span: SpanData): void;\n}\n\n/**\n * Starts the clock of one operation.\n * @param name Operation name. A JavaScript caller can pass another type.\n * @param attributes Copy of the attribute set of the app.\n * @param span Span of the operation, or undefined with spans off or for a dropped trace.\n * @param sinks Receivers of the values.\n * @returns The handle of the operation.\n */\nexport function createMeasure(\n name: unknown,\n attributes: MetricAttributes,\n span: ClientSpan | undefined,\n sinks: MeasureSinks,\n): Measure {\n // The record builder needs text.\n const label = String(name);\n const startMs = Date.now();\n const startedAt = performance.now();\n let open: { name: string; at: number } | undefined;\n let ended = false;\n\n // The histograms use the monotonic clock. A span needs epoch times.\n const epoch = (at: number): number => startMs + at - startedAt;\n\n const closePhase = (now: number, error: boolean): void => {\n if (!open) {\n return;\n }\n\n sinks.metric(PHASE_DURATION, now - open.at, {\n ...attributes,\n \"measure.name\": label,\n \"measure.phase\": open.name,\n });\n if (span) {\n sinks.span({\n name: open.name,\n kind: \"internal\",\n traceId: span.traceId,\n spanId: newSpanId(),\n parentSpanId: span.spanId,\n startMs: epoch(open.at),\n endMs: epoch(now),\n error,\n attributes: { \"measure.name\": label },\n });\n }\n open = undefined;\n };\n\n return {\n phase: (next: unknown) => {\n if (ended) {\n return;\n }\n\n const now = performance.now();\n closePhase(now, false);\n open = { name: String(next), at: now };\n },\n end: (outcome = \"ok\") => {\n if (ended) {\n return;\n }\n\n ended = true;\n const now = performance.now();\n const error = outcome === \"error\";\n closePhase(now, error);\n const fields = { ...attributes, \"measure.outcome\": outcome };\n sinks.metric(TOTAL_DURATION, now - startedAt, { ...fields, \"measure.name\": label });\n if (span) {\n sinks.span({\n ...span,\n name: label,\n kind: \"internal\",\n startMs,\n endMs: epoch(now),\n error,\n attributes: fields,\n });\n }\n },\n };\n}\n","// src/core/record.ts\n//\n// This module builds structured log records from ambient context, journey data, trace\n// context and resource attributes. It never throws to the caller.\n// The builder caches the resource block. Call invalidateResource after a change to its inputs.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_ATTRIBUTES_BYTES,\n ATTR_ATTRIBUTES_DROPPED,\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_SANITIZE_FAILED,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n METRIC_KEYS,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_CONTEXT_ID,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_HOST_PLATFORM,\n RESOURCE_OPENFIN_NAME,\n RESOURCE_OPENFIN_UUID,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n RESOURCE_SESSION_ID,\n RESOURCE_TAB_ID,\n RESOURCE_TELEMETRY_SDK_LANGUAGE,\n RESOURCE_TELEMETRY_SDK_NAME,\n RESOURCE_TELEMETRY_SDK_VERSION,\n SEVERITY_NUMBER,\n SPAN_KEYS,\n TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport {\n isLogLevel,\n isLogRecord,\n type LogLevel,\n type LogRecord,\n type LogType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Identity } from \"../utils/identity\";\nimport { currentUrl, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { type SanitizeLimits, sanitizeWithSize, truncate } from \"../utils/sanitize\";\nimport type { Sequence } from \"../utils/sequence\";\nimport type { TraceContext, TraceEngine } from \"../utils/tracing\";\nimport type { ContextStore } from \"./context\";\nimport type { DebugBuffer } from \"./debug-buffer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { Journey, JourneyEngine } from \"./journey\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport { levelFor, shouldSampleInput } from \"./sampling\";\n\n/** Prefix of the error fields. An oversized error record keeps them. */\nconst ERROR_ATTR_PREFIX = \"error.\";\n\n/** Index keys that an oversized record keeps in the form that redact gave them. */\nconst REDACTABLE_INDEX_KEYS = [ATTR_PAGE_URL, ATTR_JOURNEY_ID, ATTR_JOURNEY_NAME] as const;\n\n/** Injected dependencies required by RecordBuilder. */\nexport interface RecordBuilderDeps {\n /** Active configuration object reference. */\n config: ResolvedConfig;\n /** Per-record size caps. */\n limits: RecordLimits;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Ambient context store. */\n context: ContextStore;\n /** Active journey engine. */\n journey: JourneyEngine;\n /** Distributed tracing engine. */\n tracing: TraceEngine;\n /** Monotonic sequence counter. */\n sequence: Sequence;\n /** Context, session and tab identity. */\n identity: Identity;\n /** Detected host platform metadata. */\n platform: PlatformMetadata;\n /** Slot of the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Keeps the records that minLevel or sampling drops, for the next error. */\n debug?: DebugBuffer;\n}\n\n/** Size limits for each record. The builder applies them after sanitize and after redact. */\nexport interface RecordLimits extends SanitizeLimits {\n /** Max record body length, in characters. */\n maxBodyChars: number;\n /** Max total attribute bytes per record. */\n maxRecordBytes: number;\n}\n\n/**\n * Reason a record was not built. \"malformed\" means a processor or the redact hook broke the\n * record shape or set an unknown severityText.\n */\nexport type DropReason = \"level\" | \"sampling\" | \"processor\" | \"redact\" | \"malformed\";\n\n/** Consumer hook that changes or drops a record. */\ntype RecordHook = (record: LogRecord) => LogRecord | null;\n\n/** Stage of a consumer hook. */\ntype HookStage = \"processor\" | \"redact\";\n\n/** Message subject and drop code of each hook stage. */\nconst HOOK_STAGES = {\n processor: { label: \"A processor\", code: \"record.dropped_by_processor\" },\n redact: { label: \"The redact hook\", code: \"record.dropped_by_redact\" },\n} as const;\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when the builder drops it. */\n record: LogRecord | null;\n /** Reason for the drop. It is absent when the builder built a record. */\n dropped?: DropReason;\n}\n\n/** Metadata captured before a deferred logger call reads its payload. */\nexport interface RecordSnapshot {\n timeUnixNano: string;\n trace: TraceContext;\n journey: Journey | null;\n context: Record<string, unknown>;\n url: string;\n}\n\n/** Input parameters for constructing a single log record. */\nexport interface BuildInput {\n /** Severity level of the log entry. */\n level: LogLevel;\n /** Telemetry type classification. */\n type: LogType;\n /** Primary log message body. */\n body: string;\n /** Originating application namespace. */\n namespace: string;\n /** Pre-merged scoped context from logger instance. */\n scoped?: Record<string, unknown>;\n /** Call-site payload attributes. */\n payload?: Record<string, unknown>;\n /**\n * Fields that the library builds with a fixed size bound, for example the buckets of a point.\n * The record limits do not cut them. They override a payload key of the same name.\n */\n fixed?: Record<string, unknown>;\n /** True for a point of a counter or histogram. Sampling keeps it. */\n aggregated?: boolean;\n /** Trace IDs of a span. Without them, the builder reads the active trace. */\n trace?: TraceContext;\n /** Metadata of the call before the deferred build. */\n snapshot?: RecordSnapshot;\n}\n\n/** Keys of the fields that the library builds for a metric point or a span. */\nconst FIXED_KEYS: readonly string[] = [\n \"metric.name\",\n \"metric.unit\",\n \"metric.type\",\n \"metric.value\",\n ...Object.values(METRIC_KEYS),\n ...Object.values(SPAN_KEYS),\n];\n\n/**\n * Reads the fields that the library built in another context. A hook of the sender cannot change\n * them, and the limits cannot cut them.\n * @param attributes Attributes of a forwarded record.\n * @returns The fields that the record has.\n */\nfunction fixedOf(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n FIXED_KEYS.filter((key) => key in attributes).map((key) => [key, attributes[key]]),\n );\n}\n\n/**\n * Casts a sanitized plain object value to an attribute record.\n * @param value Sanitized object value.\n * @returns Attribute record.\n */\nfunction asAttributes(value: unknown): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\n/** Builds validated and sanitized LogRecord instances from logger inputs. */\nexport class RecordBuilder {\n /** Cached resource attributes block. */\n private resourceCache: Record<string, unknown> | null = null;\n\n /**\n * @param deps Injected builder dependencies.\n */\n constructor(private readonly deps: RecordBuilderDeps) {}\n\n /** Clears the cached resource attributes. The next build computes them again. */\n invalidateResource(): void {\n this.resourceCache = null;\n }\n\n /**\n * Checks if logging is on and the level is at or above the minimum level of the namespace.\n * The minimum level does not apply to an action or a metric.\n * @param level Target log severity level.\n * @param namespace Logger namespace. `minLevels` can set its level.\n * @param type Record type. Without it, the check applies the minimum level.\n * @returns True if the library builds a record of this level and type.\n */\n isEnabled(level: LogLevel, namespace: string, type?: LogType): boolean {\n const { config } = this.deps;\n if (!config.enabled) {\n return false;\n }\n\n if (type !== undefined && LEVEL_BYPASS_TYPES.includes(type)) {\n return true;\n }\n\n // A remote rule can lower the level during an incident.\n const minLevel =\n this.deps.remote.sampling?.minLevelFor(namespace) ?? levelFor(namespace, config);\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];\n }\n\n /**\n * Keeps a record that minLevel or sampling dropped, when the debug buffer is on. The privacy\n * hooks run now. An error record of this context sends the kept record later.\n * @param input Input of the dropped record.\n */\n private keepForDebug(input: BuildInput): void {\n const { config, debug } = this.deps;\n if (!debug || !config.enabled || !config.debugBuffer.enabled) {\n return;\n }\n\n const { record } = this.build(input, true);\n if (record) {\n debug.push(record);\n }\n }\n\n /**\n * Builds a structured LogRecord from the input. It sanitizes attributes and applies size limits.\n * @param input Logger call input parameters.\n * @param forConsole True to skip delivery sampling and level checks. Privacy hooks still run.\n * @returns The record, or null with the reason of the drop.\n */\n build(input: BuildInput, forConsole = false): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits, remote } = this.deps;\n\n if (!forConsole && !this.isEnabled(input.level, input.namespace, input.type)) {\n diagnostics.count(\"record.dropped_by_level\");\n this.keepForDebug(input);\n return { record: null, dropped: \"level\" };\n }\n\n const traceCtx = input.trace ?? input.snapshot?.trace ?? tracing.resolve();\n const activeJourney = input.snapshot ? input.snapshot.journey : journey.current();\n\n // Sample delivery records before the attribute walk. A record for the console or a\n // breadcrumb skips this check. The privacy hooks process that record, but do not send it.\n const sampled = shouldSampleInput(\n {\n level: input.level,\n type: input.type,\n namespace: input.namespace,\n journeyId: activeJourney?.id ?? \"\",\n traceId: traceCtx.traceId,\n aggregated: input.aggregated,\n },\n config,\n remote.sampling?.current() ?? null,\n );\n if (!forConsole && !sampled) {\n diagnostics.count(\"record.dropped_by_sampling\");\n this.keepForDebug(input);\n return { record: null, dropped: \"sampling\" };\n }\n\n const seq = sequence.next();\n // The query and fragment can contain tokens and user input. The path groups records.\n const url = input.snapshot?.url ?? currentUrl(diagnostics);\n const pageUrl = config.metadata.pageUrl\n ? recordedUrl(url, config.capture.fullUrls, config.capture.urlTransform, diagnostics)\n : \"\";\n\n let attributes: Record<string, unknown>;\n let bytes = 0;\n try {\n const fromContext = sanitizeWithSize(\n input.snapshot?.context ?? this.deps.context.getAll(),\n limits,\n diagnostics,\n );\n const fromProvider = sanitizeWithSize(this.provided(), limits, diagnostics);\n const fromScope = sanitizeWithSize(input.scoped ?? {}, limits, diagnostics);\n const fromPayload = sanitizeWithSize(input.payload ?? {}, limits, diagnostics);\n bytes = fromContext.bytes + fromProvider.bytes + fromScope.bytes + fromPayload.bytes;\n\n // Merge in increasing precedence. The provider overrides the context. Scope overrides the\n // provider. Payload overrides scope.\n attributes = {\n ...asAttributes(fromContext.value),\n ...asAttributes(fromProvider.value),\n ...asAttributes(fromScope.value),\n ...asAttributes(fromPayload.value),\n };\n } catch (error) {\n diagnostics.report(\n \"record.sanitize_failed\",\n \"The library could not sanitize the attributes.\",\n undefined,\n error,\n );\n attributes = { [ATTR_SANITIZE_FAILED]: true };\n }\n\n // A cut bucket list makes the serializer drop the point.\n Object.assign(attributes, input.fixed);\n\n // Set reserved attributes after the payload merge. If they merge first, a payload key\n // named journey.id replaces the ID that correlates the records.\n attributes[ATTR_LOG_TYPE] = input.type;\n attributes[ATTR_LOG_SEQ] = seq;\n attributes[ATTR_APP_NAMESPACE] = input.namespace;\n attributes[ATTR_PAGE_URL] = pageUrl;\n if (activeJourney) {\n attributes[ATTR_JOURNEY_ID] = activeJourney.id;\n attributes[ATTR_JOURNEY_NAME] = activeJourney.name;\n if (activeJourney.parentId !== undefined) {\n attributes[ATTR_JOURNEY_PARENT_ID] = activeJourney.parentId;\n }\n }\n\n const body = truncate(input.body, limits.maxBodyChars);\n if (body !== input.body) {\n diagnostics.count(\"record.truncated\");\n }\n\n let record: LogRecord = {\n timeUnixNano: input.snapshot?.timeUnixNano ?? nowUnixNano(),\n traceId: traceCtx.traceId,\n spanId: traceCtx.spanId,\n traceFlags: traceCtx.traceFlags,\n severityNumber: SEVERITY_NUMBER[input.level],\n severityText: input.level,\n body,\n attributes,\n resource: this.resource(),\n };\n\n // The processors run first. redact is the last privacy gate.\n const stages = config.processors.map((hook): [RecordHook, HookStage] => [hook, \"processor\"]);\n if (config.redact) {\n stages.push([config.redact, \"redact\"]);\n }\n\n if (stages.length > 0) {\n const outcome = this.applyHooks(record, stages, input.fixed);\n if (typeof outcome === \"string\") {\n return { record: null, dropped: outcome };\n }\n\n ({ record, bytes } = outcome);\n }\n\n // Drop the caller attributes when their size exceeds maxRecordBytes. Keep the index keys.\n // A search cannot find a record without journey.id and trace_id. Keep the error fields,\n // then the breadcrumbs if they fit. They tell why the record exists.\n if (bytes > limits.maxRecordBytes) {\n diagnostics.report(\n \"record.truncated\",\n \"The attributes are larger than the size limit. The library dropped the caller attributes.\",\n { bytes, body: record.body },\n );\n\n const kept: Record<string, unknown> = {\n [ATTR_LOG_TYPE]: input.type,\n [ATTR_LOG_SEQ]: seq,\n [ATTR_APP_NAMESPACE]: input.namespace,\n [ATTR_ATTRIBUTES_DROPPED]: true,\n [ATTR_ATTRIBUTES_BYTES]: bytes,\n };\n\n // Read these keys after redact. The hook can remove a token from page.url.\n for (const key of REDACTABLE_INDEX_KEYS) {\n if (key in record.attributes) {\n kept[key] = record.attributes[key];\n }\n }\n\n for (const [key, value] of Object.entries(record.attributes)) {\n if (key.startsWith(ERROR_ATTR_PREFIX)) {\n kept[key] = value;\n }\n }\n\n // error.data can be large. Drop it first, before the other error fields.\n let keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n if (keptBytes > limits.maxRecordBytes && ATTR_ERROR_DATA in kept) {\n Reflect.deleteProperty(kept, ATTR_ERROR_DATA);\n keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n }\n\n const breadcrumbs = record.attributes[ATTR_BREADCRUMBS];\n if (breadcrumbs !== undefined) {\n const crumbBytes = sanitizeWithSize(breadcrumbs, limits, diagnostics).bytes;\n if (keptBytes + crumbBytes <= limits.maxRecordBytes) {\n kept[ATTR_BREADCRUMBS] = breadcrumbs;\n }\n }\n\n // A point without its metric fields is lost.\n Object.assign(kept, input.fixed);\n record.attributes = kept;\n }\n\n return { record };\n }\n\n /**\n * Runs the redact hook on a record from another context. A child context without redact\n * forwards raw records. The sender is the last privacy gate.\n * @param record Forwarded record.\n * @returns The record to deliver, or null when the hook drops it.\n */\n redactForwarded(record: LogRecord): LogRecord | null {\n const { redact } = this.deps.config;\n if (!redact) {\n return record;\n }\n\n const stages: [RecordHook, HookStage][] = [[redact, \"redact\"]];\n const outcome = this.applyHooks(record, stages, fixedOf(record.attributes));\n return typeof outcome === \"string\" ? null : outcome.record;\n }\n\n /**\n * Runs the hooks in order. Then it sanitizes and measures the attributes again.\n * @param record Built record.\n * @param stages Hooks and their stages.\n * @param fixed Fields that the library builds. The hooks cannot change them.\n * @returns The record and the size of its attributes, or the reason of the drop.\n */\n private applyHooks(\n record: LogRecord,\n stages: readonly [RecordHook, HookStage][],\n fixed: Record<string, unknown> | undefined,\n ): { record: LogRecord; bytes: number } | DropReason {\n let current = record;\n\n for (const [hook, stage] of stages) {\n const outcome = this.runHook(hook, stage, current);\n if (typeof outcome === \"string\") {\n return outcome;\n }\n current = outcome;\n }\n\n // A hook can change the attributes in place or replace them. A cycle, a hostile getter or a\n // BigInt from a hook throws at serialization. The transport then loses the batch.\n const { diagnostics, limits } = this.deps;\n const remeasured = sanitizeWithSize(current.attributes, limits, diagnostics);\n const attributes = asAttributes(remeasured.value);\n // The limits must not cut the fields that the library builds.\n Object.assign(attributes, fixed);\n\n return { record: { ...current, attributes }, bytes: remeasured.bytes };\n }\n\n /**\n * Runs one consumer hook on a record. A processor and the redact hook have the same contract.\n * @param hook Processor or redact hook.\n * @param stage Stage of the hook.\n * @param record Record before the hook.\n * @returns The record after the hook, or the reason of the drop.\n */\n private runHook(hook: RecordHook, stage: HookStage, record: LogRecord): LogRecord | DropReason {\n const { diagnostics } = this.deps;\n const { label, code } = HOOK_STAGES[stage];\n\n // A plain JavaScript hook can edit the record in place without a return value.\n let changed: unknown;\n try {\n changed = hook(record);\n } catch (error) {\n // Drop the record. A record that the hook did not clean must not leave the page.\n diagnostics.report(\n code,\n `${label} threw an error. The library dropped the record.`,\n undefined,\n error,\n );\n return stage;\n }\n\n if (changed === null) {\n diagnostics.count(code);\n return stage;\n }\n\n const candidate: unknown = changed ?? record;\n\n if (!isLogRecord(candidate)) {\n // The hook changed the record in place. The library has no intact copy.\n if (candidate === record) {\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} changed the record to a shape that is not a record. The library dropped it.`,\n );\n return \"malformed\";\n }\n\n // A plain JavaScript hook can return a string or a Promise. The record did not pass the hook.\n diagnostics.report(\n code,\n `${label} returned a value that is not a record. The library dropped the record.`,\n );\n return stage;\n }\n\n if (!isLogLevel(candidate.severityText)) {\n // An unknown level has no severity number. The serializer cannot map it.\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} set a severityText that is not a log level. The library dropped the record.`,\n );\n return \"malformed\";\n }\n\n // The hook can change severityText. Keep the number in step with the text.\n return { ...candidate, severityNumber: SEVERITY_NUMBER[candidate.severityText] };\n }\n\n /**\n * Calls the contextProvider of the config. A provider that throws or gives a value that is not\n * an object adds nothing. The record is still built. undefined means no attributes.\n * @returns The attributes from the provider, or an empty object.\n */\n private provided(): unknown {\n const provider = this.deps.config.contextProvider;\n if (!provider) {\n return {};\n }\n\n const { diagnostics } = this.deps;\n const value = diagnostics.guard(\n \"handler.threw\",\n \"The contextProvider threw an error. The record has no attributes from it.\",\n () => {\n const given: unknown = provider();\n if (given === undefined) {\n return {};\n }\n\n // A promise is an object. Its fields are not attributes.\n return isObject(given) && typeof given.then !== \"function\" ? given : null;\n },\n );\n\n if (value === null) {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must return an object of attributes. The library ignores the value.\",\n );\n }\n\n return value ?? {};\n }\n\n /**\n * Computes or returns cached resource metadata for this runtime context.\n * @returns Resource attributes record.\n */\n private resource(): Record<string, unknown> {\n if (this.resourceCache) {\n return this.resourceCache;\n }\n const { config, identity, platform } = this.deps;\n\n this.resourceCache = {\n [RESOURCE_SERVICE_NAME]: config.serviceName,\n [RESOURCE_SERVICE_VERSION]: config.serviceVersion,\n [RESOURCE_DEPLOYMENT_ENVIRONMENT]: config.environment,\n [RESOURCE_TELEMETRY_SDK_NAME]: TELEMETRY_SDK_NAME,\n [RESOURCE_TELEMETRY_SDK_VERSION]: TELEMETRY_SDK_VERSION,\n [RESOURCE_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE,\n [RESOURCE_HOST_PLATFORM]: platform.platform,\n [RESOURCE_SESSION_ID]: identity.sessionId,\n [RESOURCE_TAB_ID]: identity.tabId,\n [RESOURCE_CONTEXT_ID]: identity.contextId,\n ...(config.metadata.userAgent ? { [RESOURCE_BROWSER_USER_AGENT]: platform.userAgent } : {}),\n // Omits undefined OpenFin properties from resource attributes.\n ...(!config.metadata.openfin || platform.openfinUuid === undefined\n ? {}\n : { [RESOURCE_OPENFIN_UUID]: platform.openfinUuid }),\n ...(!config.metadata.openfin || platform.openfinName === undefined\n ? {}\n : { [RESOURCE_OPENFIN_NAME]: platform.openfinName }),\n };\n return this.resourceCache;\n }\n}\n","// src/core/spans.ts\n//\n// Builds the span data of a root span and the span fields of a span record. The runtime builds\n// each span as a record with the type \"span\". The traces serializer reads the span fields.\n\nimport { SPAN_KEYS } from \"../constants\";\nimport type { EndedTrace, RotateReason } from \"../utils/tracing\";\n\n/** Microseconds in one millisecond. */\nconst US_PER_MS = 1000;\n\n/** Name of the root span for each cause of the start of a trace. */\nconst ROOT_NAMES: Record<RotateReason, string> = {\n start: \"ui.start\",\n interaction: \"ui.interaction\",\n navigation: \"ui.navigation\",\n explicit: \"ui.trace\",\n maxAge: \"ui.trace\",\n};\n\n/** One span that the runtime records. */\nexport interface SpanData {\n /** Span name. */\n name: string;\n /** \"internal\" for a root span, \"client\" for a request. */\n kind: \"internal\" | \"client\";\n /** Trace ID. */\n traceId: string;\n /** Span ID. */\n spanId: string;\n /** Span ID of the parent, or \"\" for a root span. */\n parentSpanId: string;\n /** Start time in epoch milliseconds. */\n startMs: number;\n /** End time in epoch milliseconds. */\n endMs: number;\n /** True for a failed operation. */\n error: boolean;\n /** Attributes of the span. */\n attributes: Record<string, unknown>;\n /** Server span linked through a response traceparent entry. */\n link?: { traceId: string; spanId: string };\n}\n\n/**\n * Converts epoch milliseconds to nanoseconds, as a decimal string. It keeps microseconds.\n * @param ms Epoch time in milliseconds. It can have a fraction.\n * @returns Epoch time in nanoseconds.\n */\nfunction unixNano(ms: number): string {\n return `${String(Math.round(ms * US_PER_MS))}000`;\n}\n\n/**\n * Builds the root span of an ambient trace that ended.\n * @param ended The trace.\n * @returns The span data.\n */\nexport function rootSpan(ended: EndedTrace): SpanData {\n return {\n name: ROOT_NAMES[ended.reason],\n kind: \"internal\",\n traceId: ended.traceId,\n spanId: ended.spanId,\n parentSpanId: \"\",\n startMs: ended.startedAt,\n endMs: ended.endedAt,\n error: false,\n attributes: {},\n };\n}\n\n/**\n * Builds the span fields of a span record. The record limits do not cut them.\n * @param span The span data.\n * @returns The fields.\n */\nexport function spanFields(span: SpanData): Record<string, unknown> {\n return {\n [SPAN_KEYS.kind]: span.kind,\n [SPAN_KEYS.parentId]: span.parentSpanId,\n [SPAN_KEYS.start]: unixNano(span.startMs),\n [SPAN_KEYS.end]: unixNano(span.endMs),\n [SPAN_KEYS.status]: span.error ? \"error\" : \"unset\",\n ...(span.link\n ? {\n [SPAN_KEYS.linkTraceId]: span.link.traceId,\n [SPAN_KEYS.linkSpanId]: span.link.spanId,\n }\n : {}),\n };\n}\n","// src/core/runtime.ts\n//\n// This runtime coordinates the subsystems. It manages their lifecycles, the configuration\n// and the routing of records.\n\nimport type { Bus } from \"../bus/bus\";\nimport type { Receive, WorkerLike } from \"../bus/links\";\nimport type { Capture, CaptureContext, CaptureOnce } from \"../capture/types\";\nimport {\n ATTR_BREADCRUMBS,\n ATTR_DEBUG_BUFFER,\n ATTR_PAGE_URL,\n CAPTURE_NAMESPACE,\n REMOTE_CAPTURE_FLAGS,\n DIAGNOSTICS_NAMESPACE,\n GAP_REPORT_THROTTLE_MS,\n METRIC_NAMESPACE,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n TELEMETRY_SDK_VERSION,\n TRACE_FLAGS_SAMPLED,\n TRACE_NAMESPACE,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type { FrameOptions, SourceOptions } from \"../models/bus\";\nimport type {\n CaptureOptions,\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n StorageStrategy,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n} from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport type { CapturePlugin, PluginContext } from \"../models/plugin\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { DeliveryStats } from \"../models/stats\";\nimport type { DebugBundle, ObservabilityHealth } from \"../models/health\";\nimport type { PruneResult, StorageAdapter, StoragePersistence } from \"../models/storage\";\nimport { ConsoleSink } from \"../utils/console\";\nimport { isObject } from \"../utils/guards\";\nimport {\n BROWSER_STORES,\n type Identity,\n type IdentityStores,\n memoryStores,\n newId,\n persistTabId,\n resolveIdentity,\n SessionTouch,\n} from \"../utils/identity\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { detectPlatform, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { sanitize, truncate } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { Sequence } from \"../utils/sequence\";\nimport { TraceEngine } from \"../utils/tracing\";\nimport { type Breadcrumb, BreadcrumbBuffer } from \"./breadcrumbs\";\nimport { applyResolvedConfig, resolveConfig } from \"./config\";\nimport { ContextStore } from \"./context\";\nimport { DebugBuffer } from \"./debug-buffer\";\nimport { cancelDeferred, drainDeferred } from \"./deferred\";\nimport {\n type DiagnosticCode,\n type DiagnosticEvent,\n type DiagnosticHandler,\n Diagnostics,\n} from \"./diagnostics\";\nimport { DropReporter } from \"./drops\";\nimport { HoldBuffer } from \"./hold-buffer\";\nimport { JourneyEngine, JOURNEY_OPTIONS, type JourneyOptions } from \"./journey\";\nimport { OneLogger } from \"./logger\";\nimport { createMeasure } from \"./measure\";\nimport { makeCounter, makeHistogram, Meter, type RecordMetric } from \"./meter\";\nimport { RecordBuilder } from \"./record\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport { sampleKey, shouldSample } from \"./sampling\";\nimport type { Sender } from \"./sender\";\nimport { rootSpan, type SpanData, spanFields } from \"./spans\";\n\n/** Constructor of one capture module. */\ntype CaptureClass = new (ctx: CaptureContext) => Capture;\n\n/** Import of each capture module. Each import makes a separate chunk. */\nconst CAPTURE_LOADERS = {\n errors: async (): Promise<CaptureClass> => (await import(\"../capture/errors\")).ErrorCapture,\n network: async (): Promise<CaptureClass> => (await import(\"../capture/network\")).NetworkCapture,\n interactions: async (): Promise<CaptureClass> =>\n (await import(\"../capture/interactions\")).InteractionCapture,\n webVitals: async (): Promise<CaptureClass> =>\n (await import(\"../capture/web-vitals\")).WebVitalsCapture,\n longFrames: async (): Promise<CaptureClass> =>\n (await import(\"../capture/long-frames\")).LongFrameCapture,\n console: async (): Promise<CaptureClass> => (await import(\"../capture/console\")).ConsoleCapture,\n uncleanExit: async (): Promise<CaptureClass> =>\n (await import(\"../capture/unclean-exit\")).UncleanExitCapture,\n userTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/user-timing\")).UserTimingCapture,\n reports: async (): Promise<CaptureClass> => (await import(\"../capture/reports\")).ReportCapture,\n resourceTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/resource-timing\")).ResourceTimingCapture,\n lifecycle: async (): Promise<CaptureClass> =>\n (await import(\"../capture/lifecycle\")).LifecycleCapture,\n};\n\n/** Name of one capture module. */\ntype CaptureName = keyof typeof CAPTURE_LOADERS;\n\n/** Constructor of the WebSocket capture plugin. */\ntype WebSocketClass = new (diagnostics: Diagnostics, config: ResolvedConfig) => CapturePlugin;\n\n/** Id of each plugin object. A new plugin object then changes the capture key. */\nconst pluginIds = new WeakMap<object, number>();\n\n/** Last plugin id that pluginId() gave. */\nlet lastPluginId = 0;\n\n/**\n * Gives the id of a plugin object. The capture key must not hold the plugin. A plugin can hold\n * a cycle, and JSON.stringify then throws.\n * @param plugin Plugin of the app.\n * @returns The id of the object.\n */\nfunction pluginId(plugin: object): number {\n let id = pluginIds.get(plugin);\n\n if (id === undefined) {\n id = ++lastPluginId;\n pluginIds.set(plugin, id);\n }\n\n return id;\n}\n\n/** Global symbol key of the singleton runtime. All federated bundles share it. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Global symbol key of the runtime that shutdown() stopped. */\nconst STOPPED_KEY = Symbol.for(RUNTIME_STOPPED_KEY);\n\n/** Config sections that the delivery stack reads one time, when it loads. */\nconst SENDER_SECTIONS = [\"batching\", \"retention\"] as const;\n\n/** Config sections that a later configure() cannot change. */\ntype StartupSection = (typeof SENDER_SECTIONS)[number] | \"limits\";\n\n/** Delivery settings that a rotation resets when the update omits them. */\nconst DELIVERY_RESET = {\n endpoint: null,\n metricsEndpoint: \"\",\n tracesEndpoint: \"\",\n headers: undefined,\n credentials: \"omit\",\n transport: undefined,\n transportOnExit: undefined,\n transportWorker: undefined,\n} as const;\n\n/** Delivery settings that configure() cannot change while isolation is on. */\nconst ROUTING_KEYS = Object.keys(DELIVERY_RESET) as (keyof typeof DELIVERY_RESET)[];\n\n/** Diagnostic codes that report a normal event, not a fault. Their records have the level INFO. */\nconst NOTICE_CODES: ReadonlySet<DiagnosticCode> = new Set([\n \"bus.role_resolved\",\n \"config.reconfigured\",\n \"security.rotated\",\n \"journey.adopted\",\n \"journey.expired\",\n]);\n\n/**\n * Makes a text key of the capture section. A later configure() reinstalls the capture\n * modules only when the key changes. A reinstall unpatches and patches each host function.\n * @param capture Capture section.\n * @returns The key. A function and a RegExp give a fixed text.\n */\nfunction captureKey(capture: CaptureOptions): string {\n return JSON.stringify({\n ...capture,\n urlTransform: capture.urlTransform ? pluginId(capture.urlTransform) : undefined,\n webVitalsLoader: capture.webVitalsLoader !== undefined,\n ignoreUrls: capture.ignoreUrls.map(String),\n propagateTraceHeaderTo: capture.propagateTraceHeaderTo.map(String),\n userTimingInclude: capture.userTimingInclude.map(String),\n plugins: capture.plugins.map(pluginId),\n });\n}\n\n/**\n * Cuts the URL fields of a diagnostic detail. Their query can hold a key. onDiagnostic stays local\n * and keeps them.\n * @param detail Detail of a diagnostic event.\n * @returns The detail for a record.\n */\nfunction recordDetail(detail: unknown): unknown {\n if (!isObject(detail)) {\n return detail;\n }\n\n const copy = { ...detail };\n for (const key of [\"url\", \"endpoint\"]) {\n const value = copy[key];\n if (typeof value === \"string\") {\n copy[key] = recordedUrl(value, false);\n }\n }\n\n return copy;\n}\n\n/**\n * Removes the delivery settings from a configuration. A console-only runtime must not send\n * or join a bus. The runtime of the other version does both.\n * @param input Consumer configuration options.\n * @returns The options with no endpoint, no transport and bus mode \"off\".\n */\nfunction consoleOnly(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n return {\n ...input,\n endpoint: null,\n metricsEndpoint: \"\",\n tracesEndpoint: \"\",\n transport: undefined,\n transportOnExit: undefined,\n transportWorker: undefined,\n bus: { ...input.bus, mode: \"off\" },\n };\n}\n\n/**\n * Tests if a configuration names a destination.\n * @param input Consumer configuration options.\n * @returns True with an endpoint, a signal endpoint or a transport.\n */\nfunction sends(input: Partial<ObservabilityConfig>): boolean {\n return (\n Boolean(input.endpoint) ||\n Boolean(input.metricsEndpoint) ||\n Boolean(input.tracesEndpoint) ||\n input.transport !== undefined ||\n input.transportWorker !== undefined\n );\n}\n\n/**\n * Tests if a runtime on a global key comes from this version of the library.\n * @param runtime Runtime on the global key. A runtime before 0.9.0 has no sdkVersion.\n * @returns True if this copy can call the methods of the runtime.\n */\nfunction ownVersion(runtime: ObservabilityRuntime): boolean {\n return runtime.sdkVersion === TELEMETRY_SDK_VERSION;\n}\n\n/** Manages subsystem lifecycles, bus coordination and record delivery. */\nexport class ObservabilityRuntime {\n /** True while the runtime changes the security context. */\n private rotating = false;\n /** True while the runtime collects the last records of the old context. */\n private closingContext = false;\n /** Version of another SDK copy that owns the page runtime, or null. */\n private mismatchVersion: string | null = null;\n /** True if the configured context id differs from the owner context id. */\n private contextMismatch = false;\n /** Current context change. Shutdown waits for this promise. */\n private rotation?: Promise<void>;\n /** Memory store kept for later context changes. */\n private memoryStorage?: StorageAdapter;\n /** State of the request for persistent storage. getHealth() reports it. */\n private storagePersistence: StoragePersistence = \"off\";\n /** True while a diagnostic record goes out. A diagnostic during that time gives no record. */\n private recordingDiagnostic = false;\n /** Logger of the records that diagnostics.records gives. */\n private readonly diagnosticLogger = new OneLogger(() => this, DIAGNOSTICS_NAMESPACE);\n /** Records that minLevel or sampling dropped. An error of this context sends them first. */\n private readonly debugBuffer = new DebugBuffer(() => this.config.debugBuffer);\n /** True if the app supplied a context id at startup. */\n private explicitSecurityContext: boolean;\n /** True after this forwarder takes a context id from its owner. */\n private ownerAdopted = false;\n\n /**\n * Checks if a security context change is in progress.\n * @returns True until the current change completes.\n */\n isRotating(): boolean {\n return this.rotating;\n }\n\n /**\n * Locks or unlocks configuration at the request of the app. Other code of this origin can\n * call this method. The lock does not control access.\n * @param locked True to refuse changes through configure().\n */\n setConfigurationLocked(locked: boolean): void {\n if (typeof locked === \"boolean\") this.config.lockConfiguration = locked;\n }\n /**\n * Runtime of this copy of the library when another version owns the page runtime.\n * It stays off the global key.\n */\n private static local: ObservabilityRuntime | null = null;\n\n /**\n * Library version of this runtime. Another copy reads it from the global key.\n * Two versions with one runtime call methods that the other version does not have.\n */\n readonly sdkVersion: string = TELEMETRY_SDK_VERSION;\n\n /** Diagnostics reporter for internal faults. */\n readonly diagnostics: Diagnostics;\n\n /** Active configuration instance. A reconfigure changes it in place. */\n readonly config: ResolvedConfig;\n\n /** Detected host platform metadata. */\n readonly platform: PlatformMetadata;\n\n /** Identity context containing session, tab, and context identifiers. */\n readonly identity: Identity;\n\n /** Stores for identity and journey keys. The runtime sets them at startup. */\n private readonly stores: IdentityStores;\n\n /** Identity strategy that the runtime used to make the stores. */\n private readonly identityBuiltAs: IdentityStrategy;\n\n /** Throttled writer of the session's last-seen timestamp. */\n private readonly sessionTouch: SessionTouch;\n\n /** Store for ambient application context attributes. */\n readonly context = new ContextStore();\n\n /** Ring buffer holding contextual user breadcrumbs. */\n readonly breadcrumbs: BreadcrumbBuffer;\n\n /** Distributed tracing context engine. */\n readonly tracing: TraceEngine;\n\n /** Monotonic sequence counter for records emitted in this context. */\n readonly sequence = new Sequence();\n\n /** Journey tracking engine managing workflow correlation. */\n readonly journey: JourneyEngine;\n\n /** Record builder assembling structured log records. */\n readonly builder: RecordBuilder;\n\n /** Slot of the remote sampling rules. The sender or the bus fills it. */\n private readonly remote: RemoteSlot = {\n sampling: null,\n changed: () => {\n this.refreshCaptures();\n },\n };\n\n /** Count of delivery identity changes. The first id of a context is not a change. */\n private identityEpoch = 0;\n\n /** Timer that restores the local capture switches after the remote TTL. */\n private remoteCaptureTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Settings of the current capture load or install. */\n private installedCaptureKey = \"\";\n\n /** Console sink for local developer output. */\n readonly console: ConsoleSink;\n\n /** Collects lost records into onDrop summaries. */\n private readonly drops: DropReporter;\n\n /** Sums the values of the counter and histogram instruments. */\n private readonly meter: Meter;\n\n /**\n * Cross-realm communication bus. It is null until its chunk loads.\n * In bus.mode \"off\", it loads only when a child frame or a worker needs it.\n */\n private bus: Bus | null = null;\n\n /** Load and construction of the bus. It is undefined until the first need. */\n private busBuilt?: Promise<Bus | null>;\n\n /** Load and start of the bus. It is undefined until the first need. */\n private busLoad?: Promise<Bus | null>;\n\n /** Storage strategy of the adapter. The runtime sets it when the build starts. */\n private storageBuiltAs?: StorageStrategy;\n\n /** Delivery stack. The runtime sets it in the sender role with an endpoint, after the chunk loads. */\n private sender?: Sender;\n\n /** Load of the delivery stack. It is undefined when nothing loads. A record then has no destination. */\n private senderLoad?: Promise<void>;\n\n /** Records that arrive while the delivery stack loads. */\n private readonly pendingRecords = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Active auto-capture instrumentation modules. */\n private readonly captures: Capture[] = [];\n\n /** Count of capture installs. An install that a later install replaced stops after its load. */\n private captureGeneration = 0;\n\n /** Capture work that a rebuild of the capture modules must not repeat. */\n private readonly captureOnce: CaptureOnce = {\n webVitals: false,\n navigationTiming: false,\n longFrames: false,\n uncleanExit: false,\n userTiming: false,\n };\n\n /** Queue buffering records created before bus role resolution. */\n private readonly bootBuffer = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Batch buffer staging records for microtask forwarding. */\n private forwardBuffer: LogRecord[] = [];\n\n /** True if a microtask drain of the forward buffer is pending. */\n private forwardScheduled = false;\n\n /** True if startup has decided the bus role. A sender load waits for it. */\n private roleResolved = false;\n\n /** Resolves when startup releases the boot records. flush() waits for it. init() sets it. */\n private started: Promise<void> = Promise.resolve();\n\n /** True if asynchronous initialization is complete. */\n private ready = false;\n\n /** True if shutdown stopped the runtime. */\n private destroyed = false;\n\n /** Timestamp of the last reported storage gap warning in epoch milliseconds. */\n private lastGapAt = 0;\n\n /** Record limits of the builder and the console. The first configure() of the app sets them. */\n private readonly limits: ResolvedConfig[\"limits\"];\n\n /** Lifetime rules of the journey engine. The first configure() of the app sets the age. */\n private readonly journeyOptions: JourneyOptions;\n\n /** False in a runtime that an early log call started. The first configure() then sets limits. */\n private tunablesLocked = true;\n\n /**\n * True for a console-only runtime. It sends nothing, joins no bus and installs no capture.\n * Another version of the library on the page, or a server, makes it console-only.\n */\n private readonly degraded: boolean;\n\n /** True after the report of a destination on a server. The runtime reports it one time. */\n private serverReported = false;\n\n /**\n * Ends the root span of a forwarder when its document unloads. The exit flush ends it only in\n * the sender. Without this, the client spans of a frame or a view have no parent.\n */\n private readonly onPageHide = (): void => {\n drainDeferred(this);\n if (this.role() !== \"forwarder\") {\n return;\n }\n\n this.tracing.end();\n this.sendForwarded();\n };\n\n /**\n * @param input Initial consumer configuration options.\n * @param mismatch True for a console-only runtime next to another version.\n */\n private constructor(input: Partial<ObservabilityConfig>, mismatch = false) {\n this.diagnostics = new Diagnostics(input.onDiagnostic);\n\n this.platform = detectPlatform(this.diagnostics);\n // A server has no page to capture and no storage. It writes to the console only.\n this.degraded = mismatch || this.onServer();\n this.config = resolveConfig(this.allowed(input), this.diagnostics);\n this.explicitSecurityContext = Boolean(input.securityContext?.id);\n this.config.securityContext.id ||= newId(this.diagnostics);\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n this.identityBuiltAs = this.config.identity;\n this.stores =\n this.identityBuiltAs === \"memory\" || this.onServer() ? memoryStores() : BROWSER_STORES;\n this.identity = resolveIdentity(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionIdleMs,\n );\n this.sessionTouch = new SessionTouch(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionTouchMs,\n this.config.correlation.sessionIdleMs,\n );\n this.breadcrumbs = new BreadcrumbBuffer(this.config.capturePolicy.breadcrumbs);\n // Sample a span by its trace. The whole trace stays or goes.\n const keeps = (traceId: string): boolean =>\n sampleKey(traceId, this.config.sampling.defaultRate);\n this.tracing = new TraceEngine(\n this.diagnostics,\n this.config.correlation.traceMaxAgeMs || Infinity,\n this.config.otelLoader,\n {\n enabled: () => this.config.tracesEndpoint !== \"\",\n keeps,\n onEnd: (ended) => {\n if (keeps(ended.traceId)) {\n this.recordSpan(rootSpan(ended));\n }\n },\n },\n );\n // Do not await. Without OTel, records use the ambient trace. The library loses no record.\n void this.tracing.loadOtel();\n // The startup values stay. A later configure() cannot change the limits or the journey age.\n this.limits = { ...this.config.limits };\n this.console = new ConsoleSink(this.config.console, this.diagnostics, this.limits);\n this.drops = new DropReporter(this.config, this.diagnostics);\n this.journeyOptions = { ...JOURNEY_OPTIONS, maxAgeMs: this.config.journey.maxAgeMs };\n\n this.journey = new JourneyEngine(\n this.journeyOptions,\n this.diagnostics,\n this.identity.contextId,\n (journey) => {\n this.bus?.broadcastJourney(journey);\n },\n this.stores,\n );\n\n this.builder = new RecordBuilder({\n remote: this.remote,\n config: this.config,\n limits: this.limits,\n diagnostics: this.diagnostics,\n context: this.context,\n journey: this.journey,\n tracing: this.tracing,\n sequence: this.sequence,\n identity: this.identity,\n platform: this.platform,\n debug: this.debugBuffer,\n });\n\n this.meter = new Meter(\n () => this.config.batching.metricFlushIntervalMs,\n (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n this.diagnostics,\n this.config.metrics,\n );\n // The record builder exists now. A diagnostic can become a record.\n this.diagnostics.setHandler(this.diagnosticHandler());\n }\n\n /**\n * Gives the handler of the diagnostics. With diagnostics.records, it also sends each event\n * as a record.\n * @returns The handler, or undefined without onDiagnostic and without diagnostic records.\n */\n private diagnosticHandler(): DiagnosticHandler | undefined {\n if (this.config.diagnostics.records === false) {\n return this.config.onDiagnostic;\n }\n\n return (event) => {\n this.recordDiagnostic(event);\n this.config.onDiagnostic?.(event);\n };\n }\n\n /**\n * Sends a diagnostic event as a record when diagnostics.records selects its code.\n * A diagnostic during that send gives no record. That stops a loop.\n * @param event Diagnostic event.\n */\n private recordDiagnostic(event: DiagnosticEvent): void {\n const { records } = this.config.diagnostics;\n const selected = records === true || (records !== false && records.includes(event.code));\n if (!selected || this.recordingDiagnostic) {\n return;\n }\n\n this.recordingDiagnostic = true;\n try {\n const write = NOTICE_CODES.has(event.code)\n ? this.diagnosticLogger.info\n : this.diagnosticLogger.warn;\n write(event.message, {\n \"diagnostic.code\": event.code,\n \"diagnostic.count\": event.count,\n \"diagnostic.detail\": recordDetail(event.detail),\n });\n } finally {\n this.recordingDiagnostic = false;\n }\n }\n\n /**\n * Adds a breadcrumb from app code. It copies the data now. A later change of the object of the\n * app then does not change the trail.\n * @param message Description of the event. A JavaScript caller can pass a value that is not a\n * string. The library converts it.\n * @param data Optional metadata.\n */\n addBreadcrumb(message: unknown, data?: Record<string, unknown>): void {\n if (this.rotating || this.destroyed) return;\n // A message with a toString() that throws, or a data getter that throws, must not throw\n // into the call of the app.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not add the breadcrumb.\",\n () => {\n const crumb: Breadcrumb = {\n t: Date.now(),\n category: \"custom\",\n message: truncate(String(message), this.limits.maxBodyChars),\n };\n\n if (data !== undefined) {\n const clean = sanitize(data, this.limits, this.diagnostics);\n crumb.data = isObject(clean) ? clean : { value: clean };\n }\n\n this.breadcrumbs.push(crumb);\n },\n );\n }\n\n /**\n * Adds a value to a counter or a histogram. The meter sends one point at each interval.\n * @param def Definition of the instrument.\n * @param value Value to add.\n * @param attributes Attribute set of the value.\n */\n recordMetric(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // Guard against a value after shutdown. Its interval timer would outlive the runtime.\n if (!this.destroyed && !this.rotating) {\n this.meter.record(def, value, attributes);\n }\n }\n\n /**\n * Starts a timed operation. A shutdown or a new delivery identity before its end drops its values.\n * @param name Operation name.\n * @param attributes Attribute set of each histogram point.\n * @returns The handle of the operation.\n */\n startMeasure(name: string, attributes?: MetricAttributes): Measure {\n const epoch = this.identityEpoch;\n const current = (): boolean =>\n !this.destroyed &&\n !this.rotating &&\n (!this.config.securityContext.isolation || this.identityEpoch === epoch);\n const copied = this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the attributes of the measure.\",\n () => ({ ...attributes }),\n );\n\n return createMeasure(name, copied ?? {}, this.tracing.request().span, {\n metric: (def, value, points) => {\n if (current()) {\n this.recordMetric(def, value, points);\n }\n },\n span: (span) => {\n if (current()) {\n this.recordSpan(span);\n }\n },\n });\n }\n\n /**\n * Builds and emits the record of one span. The console does not print it. minLevel does not\n * drop it. The trace engine sampled the trace before the span existed.\n * @param span The span data.\n */\n private recordSpan(span: SpanData): void {\n if (this.config.tracesEndpoint === \"\") {\n return;\n }\n\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"span\",\n body: span.name,\n namespace: TRACE_NAMESPACE,\n payload: span.attributes,\n fixed: spanFields(span),\n trace: { traceId: span.traceId, spanId: span.spanId, traceFlags: TRACE_FLAGS_SAMPLED },\n });\n this.emit(record);\n }\n\n /**\n * Builds and emits the record of one aggregated point. The console does not print it.\n * @param name Metric name.\n * @param attributes Attributes of the call. The record limits apply to them.\n * @param fields Metric fields of the point. The record limits do not cut them.\n */\n private emitPoint(\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ): void {\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"metric\",\n body: name,\n namespace: METRIC_NAMESPACE,\n payload: attributes,\n fixed: fields,\n aggregated: true,\n });\n this.emit(record);\n }\n\n /**\n * Checks the source policy before a direct child link opens.\n * @param source Child window.\n * @param origin Origin of the child window.\n * @returns True if the bus permits this source.\n */\n readonly busCanAccept = (source: Window, origin: string): boolean =>\n this.bus?.isRegistered(source, origin) ?? false;\n\n /**\n * Receives direct messages from same-origin child frames.\n * @param message Inbound bus message.\n * @param reply Direct response callback.\n * @param source Window of the child frame.\n */\n readonly busAccept = (message: BusMessage, reply: Receive, source?: Window): void => {\n if (this.destroyed) {\n return;\n }\n\n // Messages wait for the bus in arrival order. A promise runs its callbacks in order.\n void this.ensureBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The bus could not accept a direct message from a child frame.\",\n () => {\n bus.acceptDirect(message, reply, source);\n },\n );\n });\n };\n\n /**\n * Returns the runtime on the global key of this realm. Another copy of the library can own it.\n * @returns Pinned runtime instance or null.\n */\n private static pinned(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[RUNTIME_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Returns the local runtime of this copy. Without one, it returns the pinned runtime.\n * A pinned runtime of another version gives null. A log call then starts the local runtime.\n * @returns Active runtime instance or null.\n */\n static current(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local) {\n return local.destroyed ? null : local;\n }\n\n const pinned = ObservabilityRuntime.pinned();\n return pinned && ownVersion(pinned) ? pinned : null;\n }\n\n /**\n * Returns the runtime that shutdown() stopped, until the next configure().\n * A stopped runtime of another version gives null.\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local?.destroyed) {\n return local;\n }\n\n const stopped = (globalThis as Record<symbol, unknown>)[STOPPED_KEY] as\n ObservabilityRuntime | undefined;\n return stopped && ownVersion(stopped) ? stopped : null;\n }\n\n /**\n * Tests if shutdown() stopped this runtime.\n * @returns True after destroy() starts.\n */\n isDestroyed(): boolean {\n return this.destroyed;\n }\n\n /**\n * Initializes a new runtime instance or updates the existing singleton.\n * @param input Consumer configuration options.\n * @param implicit True for the default runtime that an early log call starts.\n * @returns Active runtime instance.\n */\n static configure(input: Partial<ObservabilityConfig>, implicit = false): ObservabilityRuntime {\n const local = ObservabilityRuntime.local;\n if (local && !local.destroyed) {\n // The local runtime stays console-only. React StrictMode calls configure() two times.\n local.reconfigure(input);\n return local;\n }\n ObservabilityRuntime.local = null;\n\n const pinned = ObservabilityRuntime.pinned();\n if (pinned) {\n // A runtime before 0.9.0 has no sdkVersion. It is also another version.\n if (!ownVersion(pinned)) {\n return ObservabilityRuntime.startDegraded(input, pinned.sdkVersion);\n }\n\n if (!pinned.destroyed) {\n pinned.reconfigure(input);\n return pinned;\n }\n }\n\n const runtime = new ObservabilityRuntime(input);\n // The first configure() of the app sets the limits of a default runtime.\n runtime.tunablesLocked = !implicit;\n (globalThis as Record<symbol, unknown>)[RUNTIME_KEY] = runtime;\n Reflect.deleteProperty(globalThis, STOPPED_KEY);\n void runtime.init();\n return runtime;\n }\n\n /**\n * Starts a console-only runtime next to the runtime of another version. It sends nothing,\n * joins no bus and installs no capture. The other version keeps the page runtime.\n * @param input Consumer configuration options.\n * @param found sdkVersion of the pinned runtime. A runtime before 0.9.0 has none.\n * @returns The local runtime.\n */\n private static startDegraded(\n input: Partial<ObservabilityConfig>,\n found: unknown,\n ): ObservabilityRuntime {\n const runtime = new ObservabilityRuntime(input, true);\n ObservabilityRuntime.local = runtime;\n\n const foundText = typeof found === \"string\" ? found : \"before 0.9.0\";\n runtime.mismatchVersion = foundText;\n runtime.diagnostics.report(\n \"runtime.version_mismatch\",\n `Another copy of the library, version ${foundText}, owns the page runtime. This copy, version ${TELEMETRY_SDK_VERSION}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,\n { found: foundText, own: TELEMETRY_SDK_VERSION },\n );\n\n void runtime.init();\n return runtime;\n }\n\n /**\n * Updates runtime configuration and refreshes affected subsystems.\n * @param input Partial configuration to merge.\n */\n private reconfigure(input: Partial<ObservabilityConfig>): void {\n if (this.rotating) {\n this.diagnostics.report(\n \"config.locked\",\n \"Configuration cannot change during security-context rotation.\",\n );\n return;\n }\n if (this.config.lockConfiguration) {\n const next = resolveConfig(input, this.diagnostics, this.config);\n if (!sameConfig(this.config, next))\n this.diagnostics.report(\n \"config.locked\",\n \"Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.\",\n );\n return;\n }\n drainDeferred(this);\n const accepted = this.keepDestination(this.keepRouting(this.allowed(input)));\n // The first configure() after an implicit start is the startup of the app. Its id is explicit.\n if (!this.tunablesLocked && accepted.securityContext?.id) {\n this.explicitSecurityContext = true;\n }\n for (const key of [\"correlation\", \"persistence\"] as const) {\n // The sender reads the namespace when it loads. Before that, the first configure() can set it.\n if (key === \"persistence\" && !this.tunablesLocked && this.senderLoad === undefined) {\n continue;\n }\n if (\n accepted[key] &&\n !sameConfig({ ...this.config[key], ...accepted[key] }, this.config[key])\n ) {\n this.diagnostics.report(\"config.invalid\", `${key} cannot change after startup.`);\n Object.assign(accepted, { [key]: this.config[key] });\n }\n }\n const next = resolveConfig(accepted, this.diagnostics, this.config);\n this.keepStartupTunables(next);\n const { redact, processors } = this.config;\n applyResolvedConfig(this.config, next);\n // A kept record has only the hooks of its log call. New hooks must not miss it.\n if (this.config.redact !== redact || this.config.processors !== processors) {\n this.debugBuffer.clear();\n }\n this.breadcrumbs.resize(this.config.capturePolicy.breadcrumbs);\n this.diagnostics.setHandler(this.diagnosticHandler());\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n\n this.builder.invalidateResource();\n this.console.update(this.config.console);\n this.keepBuiltStorage();\n this.keepBuiltIdentity();\n\n // Reinstall only on a change. A reinstall unpatches and patches each host function.\n // A stale capture load stops at its generation check. A reinstall is safe at any time.\n this.refreshCaptures();\n\n if (this.roleResolved) {\n void this.syncSender();\n }\n\n this.diagnostics.report(\"config.reconfigured\", \"A later configure() call updated the runtime.\");\n }\n\n /**\n * Tests if the runtime runs on a server, for example Node during server-side rendering.\n * @returns True on Node.\n */\n private onServer(): boolean {\n return this.platform.platform === \"node\";\n }\n\n /**\n * Removes the delivery settings from the input of a console-only runtime. On a server, it\n * reports a destination one time.\n * @param input Consumer configuration options.\n * @returns The options that the runtime accepts.\n */\n private allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.degraded) {\n return input;\n }\n\n if (this.onServer() && !this.serverReported && sends(input)) {\n this.serverReported = true;\n this.diagnostics.report(\n \"config.invalid\",\n \"The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint, transport and transportWorker.\",\n );\n }\n\n return consoleOnly(input);\n }\n\n /**\n * Removes delivery and identity changes while isolation is on. The other settings still apply.\n * @param input Consumer configuration options.\n * @returns The options without the refused delivery or identity changes.\n */\n private keepRouting(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.tunablesLocked || this.degraded || !this.config.securityContext.isolation) {\n return input;\n }\n\n // Compare resolved values. An unset endpoint keeps the endpoint in force. It is not a change.\n // A separate reporter prevents a second count of the diagnostics of the real resolve.\n const probe = resolveConfig(input, new Diagnostics(), this.config);\n const refused: string[] = ROUTING_KEYS.filter(\n (key) => !sameConfig(probe[key], this.config[key]),\n );\n if (probe.securityContext.id !== this.config.securityContext.id) {\n refused.push(\"securityContext.id\");\n }\n if (refused.length === 0) {\n return input;\n }\n\n const kept: Partial<ObservabilityConfig> = { ...input };\n for (const key of ROUTING_KEYS) {\n if (refused.includes(key)) {\n Reflect.deleteProperty(kept, key);\n }\n }\n if (refused.includes(\"securityContext.id\")) {\n const context = { ...input.securityContext };\n Reflect.deleteProperty(context, \"id\");\n kept.securityContext = context;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `Isolation refuses changes to ${refused.join(\", \")}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`,\n );\n return kept;\n }\n\n /**\n * Restores the startup tunables in the next config. A part of the runtime reads each tunable\n * one time. A later change has no effect. The runtime then refuses it.\n * @param next Resolved config of a later configure() call.\n */\n private keepStartupTunables(next: ResolvedConfig): void {\n if (this.senderLoad !== undefined) {\n this.keepSections(next, SENDER_SECTIONS);\n }\n\n // An early log call starts a runtime with defaults. The first configure() of the app sets\n // the limits and the journey age of that runtime.\n if (!this.tunablesLocked) {\n this.tunablesLocked = true;\n Object.assign(this.limits, next.limits);\n this.journeyOptions.maxAgeMs = next.journey.maxAgeMs;\n return;\n }\n\n this.keepSections(next, [\"limits\"]);\n\n const { maxAgeMs } = this.config.journey;\n if (next.journey.maxAgeMs !== maxAgeMs) {\n this.diagnostics.report(\n \"config.invalid\",\n `journey.maxAgeMs cannot change after startup. It stays ${String(maxAgeMs)}.`,\n { requested: next.journey.maxAgeMs },\n );\n next.journey.maxAgeMs = maxAgeMs;\n }\n }\n\n /**\n * Refuses a change of config sections. It restores the values in force in the next config.\n * @param next Resolved config of a later configure() call.\n * @param sections Sections that cannot change.\n */\n private keepSections(next: ResolvedConfig, sections: readonly StartupSection[]): void {\n for (const section of sections) {\n if (sameConfig(next[section], this.config[section])) {\n continue;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `${section} cannot change after startup. The values in force stay.`,\n { requested: next[section] },\n );\n Object.assign(next, { [section]: this.config[section] });\n }\n }\n\n /**\n * Restores the storage strategy of the built adapter. The runtime reads all other keys\n * live. It builds the adapter only one time. A new adapter strands the batches in the\n * old adapter. That loss is worse than a refused change.\n */\n private keepBuiltStorage(): void {\n const built = this.storageBuiltAs;\n\n if (built === undefined || this.config.storage === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `storage cannot change after startup. It stays ${built}.`,\n { requested: this.config.storage },\n );\n this.config.storage = built;\n }\n\n /**\n * Refuses a change that leaves the built delivery stack with no destination.\n * Without a destination, the retry engine removes each stored batch as delivered.\n * @param input Partial configuration to merge.\n * @returns Input without the refused changes.\n */\n private keepDestination(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined) {\n return input;\n }\n\n let accepted = input;\n // The stack selects its transport one time. A rotation can select another transport.\n for (const key of [\"transport\", \"transportWorker\"] as const) {\n const addsOrRemoves =\n key in input && (input[key] === undefined) !== (this.config[key] === undefined);\n if (addsOrRemoves) {\n this.diagnostics.report(\n \"config.invalid\",\n `You cannot add or remove ${key} after the delivery stack loads. The transport in force stays.`,\n );\n accepted = { ...accepted };\n Reflect.deleteProperty(accepted, key);\n }\n }\n\n const removesEndpoint = accepted.endpoint === null || accepted.endpoint === \"\";\n\n if (removesEndpoint && this.config.transport === undefined) {\n this.diagnostics.report(\n \"config.invalid\",\n \"You cannot remove the endpoint after the delivery stack loads. The endpoint in force stays.\",\n );\n // An undefined endpoint keeps the endpoint in force, and keeps it in ignoreUrls.\n accepted = { ...accepted, endpoint: undefined };\n }\n\n return accepted;\n }\n\n /**\n * Restores the identity strategy from startup. The ids exist from startup.\n * A later change cannot move them to another store.\n */\n private keepBuiltIdentity(): void {\n const built = this.identityBuiltAs;\n\n if (this.config.identity === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `identity cannot change after startup. It stays ${built}.`,\n { requested: this.config.identity },\n );\n this.config.identity = built;\n }\n\n /** Initializes asynchronous subsystems and flushes the boot buffer. */\n private async init(): Promise<void> {\n // A console-only runtime never forwards. Node has no addEventListener.\n if (!this.degraded) {\n addEventListener(\"pagehide\", this.onPageHide);\n }\n\n // Start the capture imports now. They download in parallel with the bus and the sender.\n const captures = this.installCaptures();\n\n // Set before the first await. A flush() directly after configure() then waits for it.\n this.started = this.boot();\n await this.started;\n await captures;\n }\n\n /** Resolves the bus role, loads the delivery stack and releases the boot records. It never rejects. */\n private async boot(): Promise<void> {\n try {\n const journeyReady = this.journey.bootstrap();\n\n if (this.config.bus.mode !== \"off\") {\n await this.ensureBus();\n }\n\n this.roleResolved = true;\n await this.syncSender();\n await journeyReady;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"Startup failed. The runtime continues with reduced function.\",\n undefined,\n error,\n );\n } finally {\n // Release the boot records before the captures load. The exit flush can then find them.\n this.ready = true;\n this.releaseBootBuffer();\n }\n }\n\n /**\n * Starts the load of the bus one time.\n * @returns Promise that resolves to the started bus, or null if it did not load.\n */\n private ensureBus(): Promise<Bus | null> {\n this.busLoad ??= this.startBus();\n return this.busLoad;\n }\n\n /**\n * Loads and constructs the bus one time. It does not call start().\n * @returns Promise that resolves to the constructed bus, or null if it did not load.\n */\n private constructBus(): Promise<Bus | null> {\n this.busBuilt ??= this.buildBus();\n return this.busBuilt;\n }\n\n /**\n * Starts the constructed bus. It never rejects.\n * @returns Promise that resolves to the started bus, or null if it did not load or start.\n */\n private async startBus(): Promise<Bus | null> {\n const bus = await this.constructBus();\n\n if (!bus) {\n return null;\n }\n\n try {\n await bus.start();\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not start. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /** Imports and constructs the bus. It never rejects. */\n private async buildBus(): Promise<Bus | null> {\n try {\n const { Bus } = await import(\"../bus/bus\");\n\n // Guard against a shutdown during the load. A bus on a destroyed runtime leaks its links.\n if (this.destroyed) {\n return null;\n }\n\n const bus = new Bus(\n this.config,\n this.diagnostics,\n this.platform,\n this.identity.contextId,\n this.identity.tabId,\n {\n onSecurityContext: (id) => {\n if (this.explicitSecurityContext && this.config.securityContext.id !== id) {\n this.contextMismatch = true;\n this.diagnostics.report(\n \"security.context_mismatch\",\n \"The configured security context differs from the upstream owner.\",\n );\n return false;\n }\n this.contextMismatch = false;\n if (this.config.securityContext.id !== id) {\n // The first owner id keeps the startup records and the context of the app. Those\n // records had no other identity. A later change retires them, also before ready.\n if (this.ownerAdopted) {\n drainDeferred(this);\n this.drops.add(\"security_context\", [\n ...this.bootBuffer.take(),\n ...this.pendingRecords.take(),\n ...this.forwardBuffer,\n ]);\n this.forwardBuffer = [];\n this.context.clear();\n this.breadcrumbs.clear();\n // collect() removes the open measurements. emit() refuses them during this reset.\n const rotating = this.rotating;\n this.rotating = true;\n this.meter.collect();\n // A same-origin owner stores its new session before it sends the new id. Use that\n // session. Without it, each frame starts a different session.\n const shared = this.sessionTouch.stored();\n this.resetSession(\n shared !== undefined && shared !== this.identity.sessionId\n ? shared\n : newId(this.diagnostics),\n );\n this.rotating = rotating;\n this.identityEpoch++;\n // The rules of the old owner must not apply to the new identity.\n this.remote.sampling = null;\n this.refreshCaptures();\n }\n this.config.securityContext.id = id;\n }\n this.ownerAdopted = true;\n return true;\n },\n onRecords: (records) => {\n this.ingestForwarded(records);\n },\n onJourney: (journey) => {\n this.journey.applyRemote(journey);\n },\n onJourneyRequest: () => this.journey.current(),\n onTabConflict: () => {\n this.regenerateTabId();\n },\n remote: this.remote,\n },\n );\n\n this.bus = bus;\n\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not load. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /**\n * Reads the bus role. Without a bus, this context is the sender.\n * @returns Active bus role.\n */\n private role(): BusRole {\n return this.bus?.getRole() ?? \"sender\";\n }\n\n /**\n * Loads the delivery stack if this context is the sender and has an endpoint.\n * @returns Promise that resolves when the load completes, or immediately when nothing loads.\n */\n private syncSender(): Promise<void> {\n if (!this.hasDestination() || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Tests if the config names a destination for the records.\n * @returns True with an endpoint or a custom transport.\n */\n private hasDestination(): boolean {\n return Boolean(this.config.endpoint) || this.config.transport !== undefined;\n }\n\n /**\n * Starts the load of the delivery stack one time.\n * @returns Promise that resolves when the load completes or fails.\n */\n private loadSender(): Promise<void> {\n this.senderLoad ??= this.buildSender();\n return this.senderLoad;\n }\n\n /** Imports and builds the delivery stack. It then moves the held records into it. It never rejects. */\n private async buildSender(): Promise<void> {\n this.storageBuiltAs = this.config.storage;\n\n try {\n const { Sender } = await import(\"./sender\");\n const sender = this.destroyed\n ? null\n : await Sender.create({\n storage: this.memoryStorage,\n onStorage: (storage) => {\n if (storage.name === \"memory\") this.memoryStorage = storage;\n },\n onPersistence: (state) => {\n this.storagePersistence = state;\n },\n config: this.config,\n diagnostics: this.diagnostics,\n onGap: this.reportGap,\n onLoss: this.reportLoss,\n remote: this.remote,\n beforeExit: () => {\n drainDeferred(this);\n this.meter.collect();\n this.tracing.end();\n },\n });\n\n // Guard against a shutdown during the load. The stack must not outlive the runtime.\n if (!sender || this.destroyed) {\n await sender?.destroy();\n return;\n }\n\n this.sender = sender;\n } catch (error) {\n // Clear the load. A later configure() can then try again.\n this.senderLoad = undefined;\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The delivery stack did not load. The library does not send records.\",\n { held: this.pendingRecords.length },\n error,\n );\n this.drops.add(\"load_failed\", this.pendingRecords.records);\n }\n\n for (const record of this.pendingRecords.take()) {\n this.sender?.push(record);\n }\n }\n\n /** Refreshes temporary switches and restores local settings when their TTL ends. */\n private refreshCaptures(): void {\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n if (this.destroyed) {\n return;\n }\n\n const wire = this.remote.sampling?.wire();\n if (wire) {\n this.remoteCaptureTimer = setTimeout(() => {\n this.refreshCaptures();\n }, wire.ttlMs);\n unrefTimer(this.remoteCaptureTimer);\n }\n\n if (captureKey(this.effectiveCapture()) !== this.installedCaptureKey) {\n void this.installCaptures();\n }\n }\n\n /** Returns local capture settings with the permitted remote switches. */\n private effectiveCapture(): CaptureOptions {\n const settings = { ...this.config.capture };\n const remote = this.remote.sampling?.current()?.capture;\n for (const key of REMOTE_CAPTURE_FLAGS) {\n const value = remote?.[key];\n if (settings.remoteToggles.includes(key) && value !== undefined) {\n if (value && typeof settings[key] === \"object\") {\n continue;\n }\n settings[key] = value;\n }\n }\n\n return settings;\n }\n\n /** Loads, builds and installs the enabled capture modules. It never rejects. */\n private async installCaptures(): Promise<void> {\n // A console-only runtime next to another version patches nothing. The other version does.\n if (this.degraded) {\n return;\n }\n\n const generation = ++this.captureGeneration;\n const settings = this.effectiveCapture();\n this.installedCaptureKey = captureKey(settings);\n const names: CaptureName[] = [];\n\n if (settings.errors || settings.rejections || settings.resourceErrors) {\n names.push(\"errors\");\n }\n if (settings.fetch || settings.xhr) {\n names.push(\"network\");\n }\n if (settings.interactions || settings.navigation) {\n names.push(\"interactions\");\n }\n if (settings.webVitals) {\n names.push(\"webVitals\");\n }\n if (settings.longFrames) {\n names.push(\"longFrames\");\n }\n // An empty list wraps nothing. Do not load the chunk for it.\n const consoleOn = Array.isArray(settings.console)\n ? settings.console.length > 0\n : settings.console;\n\n if (consoleOn) {\n names.push(\"console\");\n }\n if (settings.uncleanExit) {\n names.push(\"uncleanExit\");\n }\n if (settings.userTiming) {\n names.push(\"userTiming\");\n }\n\n if (settings.reports) {\n names.push(\"reports\");\n }\n if (settings.resourceTiming) {\n names.push(\"resourceTiming\");\n }\n if (settings.lifecycle) {\n names.push(\"lifecycle\");\n }\n\n const [classes, WebSocketCapture] = await Promise.all([\n Promise.all(names.map((name) => this.loadCapture(name))),\n settings.webSocket ? this.loadWebSocket() : undefined,\n ]);\n\n // Guard against a later install or a shutdown during the load. A stale capture leaks its listeners.\n if (generation !== this.captureGeneration || this.destroyed) {\n return;\n }\n\n // Swap the old set for the new set in one synchronous step. No interval runs without capture.\n this.uninstallCaptures();\n\n const ctx: CaptureContext = {\n isActive: () => !this.destroyed && !this.rotating,\n config: Object.assign(Object.create(this.config) as ResolvedConfig, { capture: settings }),\n diagnostics: this.diagnostics,\n breadcrumbs: this.breadcrumbs,\n tracing: this.tracing,\n logger: new OneLogger(() => this, CAPTURE_NAMESPACE),\n once: this.captureOnce,\n recordMetric: (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n },\n recordSpan: (span) => {\n this.recordSpan(span);\n },\n sessionId: () => this.identity.sessionId,\n };\n\n for (const CaptureModule of classes) {\n if (CaptureModule) {\n this.captures.push(new CaptureModule(ctx));\n }\n }\n\n const plugins = WebSocketCapture\n ? [...settings.plugins, new WebSocketCapture(this.diagnostics, ctx.config)]\n : settings.plugins;\n\n for (const plugin of plugins) {\n this.captures.push(this.pluginCapture(plugin));\n }\n\n for (const capture of this.captures) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not install the ${capture.name} capture.`,\n () => {\n capture.install();\n },\n );\n }\n }\n\n /** Uninstalls the active capture modules. */\n private uninstallCaptures(): void {\n for (const capture of this.captures) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not uninstall the ${capture.name} capture.`,\n () => {\n capture.uninstall();\n },\n );\n }\n this.captures.length = 0;\n }\n\n /**\n * Imports the WebSocket capture plugin. A failed import reports and skips it.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadWebSocket(): Promise<WebSocketClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the webSocket capture.\",\n async () => (await import(\"../capture/web-socket\")).WebSocketCapture,\n );\n }\n\n /**\n * Wraps a plugin as a capture module. The plugin gets public tools only.\n * @param plugin Plugin of the app, or a built-in plugin.\n * @returns The capture module.\n */\n private pluginCapture(plugin: CapturePlugin): Capture {\n const { name } = plugin;\n const record: RecordMetric = (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n };\n const ctx: PluginContext = {\n logger: new OneLogger(() => this, `${CAPTURE_NAMESPACE}.${name}`),\n counter: (metric, options = {}) => makeCounter(metric, options, record),\n histogram: (metric, options = {}) => makeHistogram(metric, options, record),\n addBreadcrumb: (message, data) => {\n this.addBreadcrumb(message, data);\n },\n ownRequest: runAsLibraryRequest,\n };\n\n return {\n name,\n install: () => {\n plugin.install(ctx);\n },\n uninstall: () => {\n plugin.uninstall();\n },\n };\n }\n\n /**\n * Imports one capture module. A failed import reports and skips that module only.\n * @param name Capture module name.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadCapture(name: CaptureName): Promise<CaptureClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n `The library could not load the ${name} capture.`,\n CAPTURE_LOADERS[name],\n );\n }\n\n /**\n * Attaches a Web Worker or MessagePort to the bus for record forwarding.\n * @param worker Target Worker or MessagePort instance.\n */\n registerWorker(worker: WorkerLike, options: SourceOptions = {}): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n if (this.destroyed) {\n return () => undefined;\n }\n\n // Attach on construction. The worker's handshake can time out while the bus starts.\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not register the worker.\",\n () => {\n detach = bus.attachWorker(worker, options);\n },\n );\n\n // Start the bus in bus.mode \"off\", where startup did not start it.\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /**\n * Registers a frame after the bus loads. Early removal cancels the registration.\n * @param frame Child frame or window.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\n registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) return;\n detach = this.diagnostics.guard(\"bus.send_failed\", \"The frame could not be registered.\", () =>\n bus.registerFrame(frame, options),\n );\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /** Flushes pending telemetry, unregisters listeners, and unpins the runtime instance. */\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n\n // The points of the open interval and the root span go out with the final flush.\n drainDeferred(this);\n this.meter.collect();\n this.tracing.end();\n this.destroyed = true;\n cancelDeferred(this);\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n\n if (!this.degraded) {\n removeEventListener(\"pagehide\", this.onPageHide);\n }\n\n this.uninstallCaptures();\n\n // Sender.destroy awaits a normal flush, then runs the exit flush. The records hold\n // their journey already. The journey and the bus can stop first.\n const closing = this.sender?.destroy();\n this.journey.destroy();\n // A record in the forward buffer waits for its microtask. The bus takes it before it stops.\n this.sendForwarded();\n this.bus?.destroy();\n // The delivery stack did not load before shutdown(). The held records are lost.\n this.drops.add(\"load_failed\", this.pendingRecords.take());\n await closing;\n // A load in progress destroys its own stack. shutdown() resolves only after that.\n await this.senderLoad;\n await this.rotation?.catch(() => undefined);\n await this.memoryStorage?.close();\n\n // A local runtime must not remove the runtime of the other version from the global key.\n if (ObservabilityRuntime.pinned() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime drops the settings of the app.\n (globalThis as Record<symbol, unknown>)[STOPPED_KEY] = this;\n }\n }\n\n /**\n * Routes a completed log record to the pipeline or forward buffer.\n * @param record Log record to emit, or null when the build dropped it.\n */\n emit(record: LogRecord | null): void {\n if (!record || this.destroyed || (this.rotating && !this.closingContext)) {\n return;\n }\n\n this.sessionTouch.touch(this.identity.sessionId);\n\n // An error first sends the records that minLevel or sampling dropped before it.\n const error = record.severityText === \"ERROR\" || record.severityText === \"FATAL\";\n const records = error ? [...this.debugBuffer.drain(), record] : [record];\n\n for (const one of records) {\n if (this.ready) {\n this.route(one);\n } else {\n this.bootBuffer.push(one);\n }\n }\n }\n\n /**\n * Sends a record to the forward buffer or to the local pipeline. The bus role selects\n * the path.\n * @param record Log record to route.\n */\n private route(record: LogRecord): void {\n if (this.role() === \"forwarder\") {\n this.forward(record);\n return;\n }\n\n this.deliver(record);\n }\n\n /**\n * Hands a record to the delivery stack. Holds the record while the stack loads.\n * Drops the record when nothing loads, for example in console-only mode.\n * @param record Log record to deliver.\n */\n private deliver(record: LogRecord): void {\n if (this.sender) {\n this.sender.push(record);\n return;\n }\n\n // Console-only mode has no destination. Count the drop. If not, no counter shows the loss.\n if (!this.senderLoad) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n // After a failed load, the config has a destination but no delivery stack.\n if (this.hasDestination()) {\n this.drops.add(\"load_failed\", [record]);\n }\n return;\n }\n\n this.pendingRecords.push(record);\n }\n\n /**\n * Counts a record that a full hold buffer drops. It gives the record to the onDrop report.\n * @param record Dropped record.\n */\n private dropHeld(record: LogRecord): void {\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n this.drops.add(\"buffer_full\", [record]);\n }\n\n /**\n * Batches records for asynchronous transmission to the upstream sender.\n * @param record Log record to forward.\n */\n private forward(record: LogRecord): void {\n this.forwardBuffer.push(record);\n if (this.forwardScheduled) {\n return;\n }\n this.forwardScheduled = true;\n\n queueMicrotask(() => {\n this.forwardScheduled = false;\n this.sendForwarded();\n });\n }\n\n /** Gives the records of the forward buffer to the bus. */\n private sendForwarded(): void {\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n if (records.length > 0) {\n this.bus?.sendRecords(records);\n }\n }\n\n /**\n * Validates, samples and queues records from child frames or workers.\n * A forwarded record arrives built. This is the first point in this context where\n * sampling can run. RecordBuilder samples a local record.\n * @param records Inbound payload from bus.\n */\n private ingestForwarded(records: unknown): void {\n if (this.destroyed) return;\n if (!Array.isArray(records)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n return;\n }\n const accepted: LogRecord[] = [];\n for (const record of records) {\n if (!isLogRecord(record)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n continue;\n }\n // A debug buffer record explains an error. Its key would give the same sampling drop again.\n if (\n record.attributes[ATTR_DEBUG_BUFFER] !== true &&\n !shouldSample(record, this.config, this.remote.sampling?.current() ?? null)\n ) {\n this.diagnostics.count(\"record.dropped_by_sampling\");\n continue;\n }\n\n // A child context without redact forwards raw records. The sender is the last gate.\n const redacted = this.builder.redactForwarded(record);\n if (redacted) {\n accepted.push(redacted);\n }\n }\n\n // Records that arrive while the context changes belong to neither identity. Report the loss\n // after sampling and redact. onDrop must not get action names or journey ids that redact masks.\n if (this.rotating) {\n this.drops.add(\"security_context\", accepted);\n return;\n }\n\n for (const record of accepted) {\n this.deliver(record);\n }\n }\n\n /** Flushes the startup records. It adds the active journey to records without a journey. */\n private releaseBootBuffer(): void {\n const buffered = this.bootBuffer.take();\n // A hook already saw each record. A key added now does not pass redact.\n const { processors, redact } = this.config;\n const journey = processors.length === 0 && redact === undefined ? this.journey.current() : null;\n\n for (const record of buffered) {\n if (journey && !record.attributes[\"journey.id\"]) {\n record.attributes[\"journey.id\"] = journey.id;\n record.attributes[\"journey.name\"] = journey.name;\n }\n this.route(record);\n }\n }\n\n /**\n * Gives lost records to the onDrop report.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n private readonly reportLoss: LossReporter = (reason, records, batchIds) => {\n this.drops.add(reason, records, batchIds);\n };\n\n /**\n * Gives the evicted batches to the onDrop report. It also emits a warning record. A throttle\n * limits the warning records.\n * @param result Storage prune summary metrics.\n * @param dropped The evicted batches.\n */\n private readonly reportGap = (result: PruneResult, dropped: readonly LogBatch[]): void => {\n this.drops.add(\n result.reason,\n dropped.flatMap((batch) => batch.records),\n dropped.map((batch) => batch.id),\n );\n\n const now = Date.now();\n if (now - this.lastGapAt < GAP_REPORT_THROTTLE_MS) {\n return;\n }\n this.lastGapAt = now;\n\n new OneLogger(() => this, STORAGE_NAMESPACE).warn(\n \"stored records were dropped before delivery\",\n {\n \"gap.batches\": result.batches,\n \"gap.records\": result.records,\n \"gap.reason\": result.reason,\n },\n );\n };\n\n /** Makes and stores a new tab ID after a tab ID collision. */\n private regenerateTabId(): void {\n const fresh = newId(this.diagnostics);\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.\",\n { was: this.identity.tabId, now: fresh },\n );\n\n (this.identity as { tabId: string }).tabId = fresh;\n persistTabId(fresh, this.diagnostics, this.stores);\n this.builder.invalidateResource();\n }\n\n /**\n * Starts a new session in this context. It sends the open metric points, starts a new trace,\n * ends the active journey and clears the breadcrumbs. Other tabs read the new id at their next\n * startup.\n */\n newSession(): void {\n if (this.destroyed) {\n return;\n }\n\n drainDeferred(this);\n this.resetSession(newId(this.diagnostics));\n }\n\n /**\n * Closes the work of the old session and starts the given session.\n * @param sessionId Id of the session to start.\n */\n private resetSession(sessionId: string): void {\n // Close the work of the old session first. Its points and its root span keep the old id.\n this.meter.collect();\n this.tracing.rotate(\"explicit\");\n this.journey.end();\n // A shared machine: the next user must not see the trail of the previous user.\n this.breadcrumbs.clear();\n this.debugBuffer.clear();\n\n (this.identity as { sessionId: string }).sessionId = sessionId;\n this.sessionTouch.restart(sessionId);\n this.builder.invalidateResource();\n }\n\n /**\n * Changes the delivery context in one operation. A second change must wait for this change.\n * @param update New identity, delivery settings and context attributes.\n * @param options Rule for records of the old context and the flush deadline.\n * @returns Promise that resolves when the change completes. Invalid settings reject it.\n */\n rotateSecurityContext(\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions = {},\n ): Promise<void> {\n // Check the promise, not the flag. \"carry\" clears the flag before it stores old batches again.\n if (this.rotation)\n return Promise.reject(new Error(\"A security-context rotation is already running.\"));\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? 5000;\n if (\n !isObject(update) ||\n !isObject(update.delivery) ||\n ![\"discard\", \"flush\", \"retain\", \"carry\"].includes(pending) ||\n !Number.isFinite(timeoutMs) ||\n timeoutMs < 0 ||\n (update.id !== undefined && (typeof update.id !== \"string\" || update.id.length === 0))\n ) {\n return Promise.reject(new Error(\"Invalid security-context rotation options.\"));\n }\n if (this.destroyed) return Promise.reject(new Error(\"The runtime has stopped.\"));\n drainDeferred(this);\n this.rotating = true;\n this.rotation = this.rotateContext(update, pending, timeoutMs).finally(() => {\n this.rotating = false;\n this.rotation = undefined;\n });\n return this.rotation;\n }\n\n /**\n * Checks new settings, stops old delivery and starts the new context.\n * @param update New identity, delivery settings and attributes.\n * @param pending Rule for the old records.\n * @param timeoutMs Maximum wait for an old-context flush, in milliseconds.\n * @returns Promise that resolves when the context change completes.\n */\n private async rotateContext(\n update: SecurityContextUpdate,\n pending: \"discard\" | \"flush\" | \"retain\" | \"carry\",\n timeoutMs: number,\n ): Promise<void> {\n await this.started;\n if (this.role() === \"forwarder\")\n throw new Error(\n \"Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.\",\n );\n await this.senderLoad;\n const previous = this.config.securityContext.id;\n const nextId = update.id ?? newId(this.diagnostics);\n if (nextId === previous)\n throw new Error(\"A rotation requires a different security-context id.\");\n // Check the new settings before the old sender stops. Invalid settings keep the old sender.\n const delivery = { ...DELIVERY_RESET, ...update.delivery };\n const before = this.diagnostics.snapshot()[\"config.invalid\"] ?? 0;\n // The base has no old delivery values. An invalid new value cannot fall back to an old one.\n const next = resolveConfig(\n this.allowed({ ...delivery, securityContext: { id: nextId } }),\n this.diagnostics,\n { ...this.config, ...DELIVERY_RESET },\n );\n if ((this.diagnostics.snapshot()[\"config.invalid\"] ?? 0) !== before)\n throw new Error(\"Invalid delivery settings for the next security context.\");\n // Copy the context now. A getter that throws then rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n // The base above has no endpoints. Remove the old endpoints from the ignore list here.\n // If they stay, network capture ignores calls to the old destination.\n const oldUrls = new Set<unknown>([\n this.config.endpoint,\n this.config.metricsEndpoint,\n this.config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n this.closingContext = true;\n try {\n this.meter.collect();\n this.tracing.end();\n this.journey.end();\n } finally {\n this.closingContext = false;\n }\n const held = [...this.bootBuffer.take(), ...this.pendingRecords.take(), ...this.forwardBuffer];\n this.forwardBuffer = [];\n const old = this.sender;\n this.sender = undefined;\n this.senderLoad = undefined;\n const retired = (await old?.retire(pending, timeoutMs, previous)) ?? {\n buffered: [],\n stored: [],\n };\n if (this.destroyed) return;\n const live = [...held, ...retired.buffered];\n const stored = retired.stored.flatMap((batch) => batch.records);\n if (pending !== \"retain\" && pending !== \"carry\") {\n this.drops.add(\"security_context\", [...live, ...stored]);\n }\n // Keep a lock change that the app made during the rotation.\n next.lockConfiguration = this.config.lockConfiguration;\n // Replace all delivery settings together. Do not keep old credentials or signal endpoints.\n applyResolvedConfig(this.config, next);\n this.identityEpoch++;\n this.remote.sampling = null;\n this.refreshCaptures();\n this.context.clear();\n if (context) this.context.setMany(context);\n this.breadcrumbs.clear();\n this.newSession();\n this.builder.invalidateResource();\n await this.syncSender();\n this.bus?.rotateContext();\n // New calls go to the new sender. A long carry then drops no logger call, and the report below\n // can give a record.\n this.rotating = false;\n if (pending === \"carry\") {\n await this.carry(live, retired.stored);\n }\n this.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n }\n\n /**\n * Moves the records of the old context into the new context.\n * @param live Records that were in memory. They go through the live buffer.\n * @param stored Batches that were stored. The new sender stores them again.\n * @returns Promise that resolves when the stored batches are stored again.\n */\n private async carry(live: LogRecord[], stored: LogBatch[]): Promise<void> {\n for (const record of live) {\n this.route(record);\n }\n\n // The live buffer does not take the stored backlog. It would exceed the buffer budget.\n // Without a new sender, the stored batches stay parked under the old id. Nothing is lost.\n if (this.sender) {\n await this.sender.adopt(stored, this.config.securityContext.id);\n }\n }\n\n /**\n * Collects the state of this runtime for a support ticket. The app decides where to send it.\n * @param health Health snapshot from the facade, with the logger cache counts.\n * @returns Promise that resolves to the JSON-safe bundle.\n */\n async debugBundle(health: ObservabilityHealth): Promise<DebugBundle> {\n const { configSummary } = await import(\"./debug-bundle\");\n // Build the breadcrumbs as a record. The privacy hooks then run, as in an error record.\n const { record } = this.builder.build(\n {\n level: \"INFO\",\n type: \"system\",\n body: \"debug bundle\",\n namespace: DIAGNOSTICS_NAMESPACE,\n payload: { [ATTR_BREADCRUMBS]: this.breadcrumbs.snapshot() },\n },\n true,\n );\n const attributes = record?.attributes ?? {};\n const crumbs = attributes[ATTR_BREADCRUMBS];\n const pageUrl = attributes[ATTR_PAGE_URL];\n\n return {\n createdAt: new Date().toISOString(),\n sdkVersion: this.sdkVersion,\n health,\n diagnostics: this.diagnostics.snapshot(),\n resource: record?.resource ?? {},\n pageUrl: typeof pageUrl === \"string\" ? pageUrl : \"\",\n breadcrumbs: Array.isArray(crumbs) ? crumbs : [],\n debugBuffer: this.debugBuffer.snapshot(),\n config: configSummary(this.config, this.limits, this.diagnostics),\n };\n }\n\n /**\n * Reads the state of this runtime. It does not wait for startup or the sender to load.\n * @returns State, delivery counts and policies. The facade adds the logger cache counts.\n */\n async health(): Promise<Omit<ObservabilityHealth, \"loggerCache\">> {\n const delivery = this.sender?.stats() ?? { pending: 0, inFlight: 0, lastSendAt: null };\n const issues: ObservabilityHealth[\"issues\"] = [];\n if (this.mismatchVersion) issues.push(\"runtime.version_mismatch\");\n if (this.contextMismatch) issues.push(\"security.context_mismatch\");\n if (this.ready && this.hasDestination() && this.role() === \"sender\" && !this.sender)\n issues.push(\"sender.unavailable\");\n const {\n sourcePolicy,\n validation,\n maxMessageBytes,\n maxRecordsPerMessage,\n maxMessagesPerSecond,\n maxTrackedSources,\n } = this.config.bus;\n return {\n ...delivery,\n pending:\n delivery.pending +\n this.bootBuffer.length +\n this.pendingRecords.length +\n this.forwardBuffer.length,\n stored: (await this.sender?.queueDepth()) ?? 0,\n sdkVersion: this.sdkVersion,\n owningSdkVersion: this.mismatchVersion,\n status: this.destroyed\n ? \"stopped\"\n : this.rotating\n ? \"rotating\"\n : issues.length\n ? \"degraded\"\n : !this.ready\n ? \"starting\"\n : \"ready\",\n mode:\n this.role() === \"forwarder\"\n ? \"forwarder\"\n : this.hasDestination()\n ? \"sender\"\n : \"console-only\",\n senderReady: this.sender !== undefined && !this.destroyed && !this.rotating,\n configurationLocked: this.config.lockConfiguration,\n issues,\n securityContext: { ...this.config.securityContext },\n storagePersistence: this.storagePersistence,\n bus: {\n sourcePolicy,\n validation,\n maxMessageBytes,\n maxRecordsPerMessage,\n maxMessagesPerSecond,\n maxTrackedSources,\n },\n };\n }\n\n /**\n * Reads the delivery state of this context.\n * @returns Promise that resolves to the counts and the time of the last accepted send.\n */\n async stats(): Promise<DeliveryStats> {\n // queueDepth() waits for a loading delivery stack. The held records are then in the pipeline.\n const stored = await this.queueDepth();\n const delivery = this.sender?.stats() ?? { pending: 0, inFlight: 0, lastSendAt: null };\n const held = this.bootBuffer.length + this.pendingRecords.length + this.forwardBuffer.length;\n\n return { ...delivery, pending: delivery.pending + held, stored };\n }\n\n /**\n * Removes stored records of one context or all contexts in the application namespace.\n * @param scope Part of storage to clear.\n * @returns Promise that resolves when removal completes.\n */\n async clearPersisted(scope: \"context\" | \"namespace\"): Promise<void> {\n await this.senderLoad;\n if (this.sender) {\n await this.sender.clearPersisted(scope, this.config.securityContext.id);\n return;\n }\n const [\n { createStorage, storageName },\n { ContextStorage },\n { storageLimits },\n { clearEmergencyContext },\n ] = await Promise.all([\n import(\"../storage/factory\"),\n import(\"../storage/context-storage\"),\n import(\"../models/storage\"),\n import(\"../storage/emergency-queue\"),\n ]);\n const namespace = this.config.persistence.namespace;\n const backing =\n this.memoryStorage ??\n (await createStorage(\n this.config.storage,\n storageName(namespace),\n storageLimits(this.config.retention),\n this.diagnostics,\n undefined,\n namespace,\n ));\n const store = new ContextStorage(backing, this.config.securityContext, namespace);\n try {\n if (scope === \"namespace\") await store.clearNamespace();\n else await store.clear();\n clearEmergencyContext(\n this.config.securityContext.id,\n this.diagnostics,\n namespace,\n scope === \"namespace\",\n );\n } finally {\n if (backing !== this.memoryStorage) await store.close();\n }\n }\n\n /**\n * Counts the batches held in storage after a failed or deferred delivery.\n * @returns Promise that resolves to the number of stored batches. A forwarder stores\n * nothing and reports 0.\n */\n async queueDepth(): Promise<number> {\n await this.senderLoad;\n return (await this.sender?.queueDepth()) ?? 0;\n }\n\n /**\n * Flushes all pending records in the pipeline or forward buffer.\n * @returns Promise that resolves when the library sends or hands off the queued records.\n */\n async flush(): Promise<void> {\n drainDeferred(this);\n this.meter.collect();\n\n // A record logged during startup waits in the boot buffer. Without this wait, flush() misses it.\n // After startup, do not wait. The handover of the forward buffer then stays synchronous.\n if (!this.ready) {\n await this.started;\n }\n\n if (this.role() === \"forwarder\") {\n this.sendForwarded();\n return;\n }\n\n await this.senderLoad;\n await this.sender?.flush();\n }\n}\n\n/**\n * Compares resolved settings without JSON conversion. Functions keep their object identity.\n * The seen map stops a cycle from causing a repeated comparison.\n * @param a First value.\n * @param b Second value.\n * @param seen Object pairs already compared.\n * @returns True if the values are equal.\n */\nfunction sameConfig(a: unknown, b: unknown, seen = new WeakMap<object, object>()): boolean {\n if (Object.is(a, b)) return true;\n if (a instanceof RegExp && b instanceof RegExp) return String(a) === String(b);\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) return false;\n if (seen.has(a)) return seen.get(a) === b;\n seen.set(a, b);\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n return (\n ak.length === bk.length &&\n ak.every(\n (key) => Object.hasOwn(b, key) && sameConfig(Reflect.get(a, key), Reflect.get(b, key), seen),\n )\n );\n}\n","import {\n TELEMETRY_SDK_VERSION,\n TRANSPORT_WORKER_PROTOCOL,\n TRANSPORT_WORKER_REFUSAL,\n TRANSPORT_WORKER_TYPE,\n} from \"../constants\";\nimport { Diagnostics, type DiagnosticHandler } from \"../core/diagnostics\";\nimport { isObject } from \"../utils/guards\";\n\nlet active: (() => void) | undefined;\n\n/** Installs the worker service synchronously before its delivery module loads. */\nexport function serveTransportWorker(\n options: { onDiagnostic?: DiagnosticHandler } = {},\n): () => void {\n if (active) {\n return active;\n }\n const diagnostics = new Diagnostics(options.onDiagnostic);\n if (typeof document !== \"undefined\" || typeof addEventListener !== \"function\") {\n diagnostics.report(\"config.invalid\", \"Call serveTransportWorker() in a dedicated worker.\");\n return () => undefined;\n }\n\n let stopped = false;\n let port: MessagePort | undefined;\n let detach: (() => void) | undefined;\n const onMessage = (event: MessageEvent<unknown>): void => {\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport worker could not read its connection.\",\n () => {\n const message = event.data;\n if (\n !isObject(message) ||\n message.p !== TRANSPORT_WORKER_PROTOCOL ||\n message.t !== TRANSPORT_WORKER_TYPE.connect\n ) {\n return;\n }\n if (event.ports.length === 0) {\n return;\n }\n const incoming = event.ports[0];\n if (port || message.v !== TELEMETRY_SDK_VERSION) {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n return;\n }\n\n port = incoming;\n void import(\"./worker-server\")\n .then((module) => {\n if (!stopped) {\n detach = module.serveWorkerPort(incoming, diagnostics);\n }\n })\n .catch((error: unknown) => {\n diagnostics.report(\n \"transport.http_error\",\n \"The transport worker delivery module could not load.\",\n undefined,\n error,\n );\n diagnostics.guard(\n \"transport.http_error\",\n \"The failed transport port could not be closed.\",\n () => {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n },\n );\n });\n },\n );\n };\n\n const stop = (): void => {\n if (stopped) {\n return;\n }\n stopped = true;\n active = undefined;\n removeEventListener(\"message\", onMessage);\n detach?.();\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport service could not close its port.\",\n () => {\n port?.postMessage(TRANSPORT_WORKER_REFUSAL);\n },\n );\n diagnostics.guard(\"transport.http_error\", \"The transport port could not close.\", () => {\n port?.close();\n });\n };\n addEventListener(\"message\", onMessage);\n active = stop;\n return stop;\n}\n","// src/transport/memory-transport.ts\n//\n// Gives tests a transport that keeps each batch in memory. A test then checks the records that\n// the library sends, with no network and no fetch mock.\n\nimport { HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { Transport, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** A transport that keeps each batch in memory, for tests. */\nexport interface MemoryTransport {\n /** Pass this function as `transport` to `configure()`. */\n transport: Transport;\n /**\n * Returns the records of each accepted batch, in send order.\n * @returns The accepted records.\n */\n records(): LogRecord[];\n /**\n * Returns each request, accepted or refused, in send order.\n * @returns The requests.\n */\n batches(): TransportRequest[];\n /** Forgets each batch. The answer that respondWith set stays. */\n clear(): void;\n /**\n * Sets the answer for each later batch. The default answer is 200.\n * @param status Status code to answer with, for example 413, 429 or 500.\n * @param retryAfterMs Delay to answer with, for 429 and 503.\n */\n respondWith(status: number, retryAfterMs?: number): void;\n}\n\n/**\n * Creates a transport that keeps each batch in memory. Use it in tests, with `configure()`.\n * @returns The memory transport.\n */\nexport function createMemoryTransport(): MemoryTransport {\n const sent: TransportRequest[] = [];\n const accepted: TransportRequest[] = [];\n let answer: TransportResponse = { status: HTTP_SUCCESS_MIN };\n\n return {\n transport: (request) => {\n sent.push(request);\n\n if (answer.status >= HTTP_SUCCESS_MIN && answer.status < HTTP_SUCCESS_END) {\n accepted.push(request);\n }\n\n return Promise.resolve({ ...answer });\n },\n records: () => accepted.flatMap((request) => [...request.records]),\n batches: () => [...sent],\n clear: () => {\n sent.length = 0;\n accepted.length = 0;\n },\n respondWith: (status, retryAfterMs) => {\n answer = retryAfterMs === undefined ? { status } : { status, retryAfterMs };\n },\n };\n}\n","// src/index.ts\n//\n// This file is the public entry point of the library. It exports the facade API,\n// logging primitives, and types.\n\nimport type { WorkerLike } from \"./bus/links\";\nimport type { Journey } from \"./core/journey\";\nimport { OneLogger, type OneLoggerOptions } from \"./core/logger\";\nimport { makeCounter, makeHistogram } from \"./core/meter\";\nimport { ObservabilityRuntime } from \"./core/runtime\";\nimport type { ObservabilityConfig } from \"./models/config\";\nimport type { SecurityContextUpdate, SecurityContextRotationOptions } from \"./models/config\";\nimport type { DebugBundle, ObservabilityHealth } from \"./models/health\";\nimport type { FrameOptions, SourceOptions } from \"./models/bus\";\nexport type { FrameOptions, SourceOptions, BusPermission } from \"./models/bus\";\nimport type { MetricType } from \"./models/log-record\";\nimport type { DeliveryStats } from \"./models/stats\";\nimport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n} from \"./models/metric\";\n\nexport { OneLogger };\nexport { serveTransportWorker } from \"./transport/worker-entry\";\nexport { createMemoryTransport, type MemoryTransport } from \"./transport/memory-transport\";\nexport type { Journey, ObservabilityConfig, OneLoggerOptions };\nexport type {\n DeliveryPolicy,\n BufferingPolicy,\n MetricsPolicy,\n CorrelationPolicy,\n DiagnosticsPolicy,\n PersistencePolicy,\n MetadataPolicy,\n CapturePolicy,\n BusOptions,\n CaptureOptions,\n InteractionOptions,\n ResourceTimingOptions,\n RemoteCaptureFlag,\n LoggerCacheOptions,\n SecurityContextOptions,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n DeliveryOptions,\n ConsoleOptions,\n ConsoleStyles,\n ExitTransport,\n Transport,\n TransportRequest,\n TransportResponse,\n} from \"./models/config\";\nexport type { DebugBundle, ObservabilityHealth } from \"./models/health\";\nexport type { WorkerLike } from \"./bus/links\";\nexport type { DiagnosticCode, DiagnosticEvent } from \"./core/diagnostics\";\nexport type { DropSummary, LossReason } from \"./models/drop\";\nexport type { LogLevel, LogRecord, LogType, MetricType } from \"./models/log-record\";\nexport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n} from \"./models/metric\";\nexport type { CapturePlugin, PluginContext } from \"./models/plugin\";\nexport type { LogSerializer, SerializedBatch } from \"./models/serializer\";\nexport type { DeliveryStats } from \"./models/stats\";\nexport type { StorageAdapter } from \"./models/storage\";\n\n/**\n * Cached logger instances keyed by namespace. This map never holds a scoped logger.\n * A logger finds the runtime on each write.\n * The cache stays valid across configure() and shutdown().\n */\nconst loggers = new Map<string, OneLogger>();\n\n/**\n * Retrieves the active runtime. After shutdown(), it returns the stopped runtime.\n * The stopped runtime does nothing. Before the first configure(), it starts a runtime\n * with default settings.\n * @returns Runtime instance.\n */\nfunction requireRuntime(): ObservabilityRuntime {\n const runtime = ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped();\n if (runtime) {\n return runtime;\n }\n\n // Start a default runtime. A log call before configure() then does not throw.\n return ObservabilityRuntime.configure({}, true);\n}\n\n/**\n * Removes stored logs. Pending records and requests can write to storage again.\n * @param scope Context or namespace whose stored records to remove.\n * @returns Promise that resolves when removal completes.\n */\nexport function clearPersistedLogs(scope: \"context\" | \"namespace\" = \"context\"): Promise<void> {\n if (![\"context\", \"namespace\"].includes(scope))\n return Promise.reject(new Error(\"Invalid persistence scope.\"));\n return requireRuntime().clearPersisted(scope);\n}\n\n/**\n * Initializes or reconfigures the observability runtime instance.\n * `payloadMode: \"defer\"` builds logger records in idle time. The debug buffer keeps immediate builds.\n * @param config Consumer configuration options.\n */\nexport function configure(config: Partial<ObservabilityConfig>): void {\n ObservabilityRuntime.configure(config);\n trimLoggerCache();\n}\n\n/**\n * Locks or unlocks configuration. The lock does not control access by other code of this origin.\n * @param locked True to refuse changes through configure().\n */\nexport function setConfigurationLocked(locked: boolean): void {\n requireRuntime().setConfigurationLocked(locked);\n}\n\n/**\n * Stops delivery for the old context and starts delivery for the new context.\n * @param update New identity, delivery settings and context attributes.\n * @param options Rule for old records and the flush deadline.\n * @returns Promise that resolves when the change completes.\n */\nexport function rotateSecurityContext(\n update: SecurityContextUpdate,\n options?: SecurityContextRotationOptions,\n): Promise<void> {\n return requireRuntime().rotateSecurityContext(update, options);\n}\n\n/**\n * Reads the runtime state, delivery counts and policies of this SDK copy.\n * @returns Promise that resolves to the current state.\n */\nexport async function getHealth(): Promise<ObservabilityHealth> {\n const runtime = requireRuntime();\n trimLoggerCache();\n return {\n ...(await runtime.health()),\n loggerCache: { ...runtime.config.loggerCache, size: loggers.size },\n };\n}\n\n/**\n * Collects the state of the library for a support ticket. The bundle has the health, the\n * diagnostic counters, the resource, the breadcrumbs, the debug buffer and a config summary.\n * The summary has no headers and no URL query. A plugin or a custom serializer shows only its\n * name. The privacy hooks process the breadcrumbs. A debug buffer record keeps its context\n * attributes. The app decides where to send the bundle.\n * @returns Promise that resolves to a JSON-safe bundle.\n */\nexport async function collectDebugBundle(): Promise<DebugBundle> {\n const health = await getHealth();\n return requireRuntime().debugBundle(health);\n}\n\n/**\n * Removes the least recently used loggers until the cache meets its limit.\n * @returns Cache limit, or null for no limit.\n */\nfunction trimLoggerCache(): number | null {\n const limit = (ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped())?.config\n .loggerCache.maxEntries;\n const max = limit === undefined ? 256 : limit;\n if (max !== null) {\n // A Map keeps insertion order. The first keys are the least recently used loggers.\n for (const key of loggers.keys()) {\n if (loggers.size <= max) {\n break;\n }\n loggers.delete(key);\n }\n }\n return max;\n}\n\n/**\n * Gives a namespace logger from the cache, or a new scoped logger.\n * @param namespace Application subsystem or module namespace.\n * @param options Context attributes for this logger only.\n * @returns Logger for the namespace. Options or a disabled cache give a new logger.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): OneLogger {\n const max = trimLoggerCache();\n if (options || max === 0) return new OneLogger(requireRuntime, namespace, options);\n\n let logger = loggers.get(namespace);\n\n logger ??= new OneLogger(requireRuntime, namespace);\n\n // Move a cached logger to the end. The first entry is then the least recently used logger.\n loggers.delete(namespace);\n loggers.set(namespace, logger);\n trimLoggerCache();\n\n return logger;\n}\n\n/**\n * Retrieves the default root logger instance.\n * @returns Root OneLogger instance for the \"app\" namespace.\n */\nfunction root(): OneLogger {\n return getLogger(\"app\");\n}\n\n/**\n * Logs a trace-level debug record.\n * @param message Detail message.\n * @param payload Optional contextual attributes.\n */\nexport function trace(message: string, payload?: Record<string, unknown>): void {\n root().trace(message, payload);\n}\n\n/**\n * Logs a debug-level record.\n * @param message Detail message.\n * @param payload Optional contextual attributes.\n */\nexport function debug(message: string, payload?: Record<string, unknown>): void {\n root().debug(message, payload);\n}\n\n/**\n * Logs an informational record.\n * @param message Informational message.\n * @param payload Optional contextual attributes.\n */\nexport function info(message: string, payload?: Record<string, unknown>): void {\n root().info(message, payload);\n}\n\n/**\n * Logs a warning record.\n * @param message Warning message.\n * @param payload Optional contextual attributes.\n */\nexport function warn(message: string, payload?: Record<string, unknown>): void {\n root().warn(message, payload);\n}\n\n/**\n * Logs an error record with causal error and breadcrumbs.\n * @param message Error summary.\n * @param err Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\nexport function error(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().error(message, err, payload);\n}\n\n/**\n * Logs a fatal record with causal error and breadcrumbs.\n * @param message Fatal error summary.\n * @param err Caught error instance or reason.\n * @param payload Optional contextual attributes.\n */\nexport function fatal(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().fatal(message, err, payload);\n}\n\n/**\n * Logs a discrete user interaction action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\nexport function logAction(name: string, payload?: Record<string, unknown>): void {\n root().logAction(name, payload);\n}\n\n/**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\nexport function logEvent(name: string, payload?: Record<string, unknown>): void {\n root().logEvent(name, payload);\n}\n\n/**\n * Logs a numerical metric measurement.\n * @param name Metric identifier.\n * @param value Measured value.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attributes Optional metric attributes.\n */\nexport function logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attributes?: Record<string, unknown>,\n): void {\n root().logMetric(name, value, unit, type, attributes);\n}\n\n/**\n * Gives a counter. The library sums its values in memory. It sends one point for each attribute\n * set at each interval. A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values.\n * @returns The counter.\n */\nexport function counter(name: string, options: InstrumentOptions = {}): Counter {\n return makeCounter(name, options, (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n });\n}\n\n/**\n * Gives a histogram. The library counts its values in buckets in memory. It sends one point for\n * each attribute set at each interval. A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values and the bucket boundaries.\n * @returns The histogram.\n */\nexport function histogram(name: string, options: HistogramOptions = {}): Histogram {\n return makeHistogram(name, options, (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n });\n}\n\n/**\n * Times an operation with named phases. Each phase and the total go into duration histograms.\n * With `tracesEndpoint`, the operation is a span with one child span for each phase.\n * @param name Operation name. Each name makes one series.\n * @param attributes Attribute set of each histogram point. Keep it small.\n * @returns The handle of the operation.\n */\nexport function startMeasure(name: string, attributes?: MetricAttributes): Measure {\n return requireRuntime().startMeasure(name, attributes);\n}\n\n/**\n * Measures the execution time of a synchronous function and logs a duration metric.\n * @param label Metric name prefix.\n * @param fn Synchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the timed function.\n */\nexport function timeSync<T>(label: string, fn: () => T, attributes?: Record<string, unknown>): T {\n return root().timeSync(label, fn, attributes);\n}\n\n/**\n * Measures the execution time of an asynchronous function and logs a duration metric.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Promise that resolves to the result of the timed function.\n */\nexport function timeAsync<T>(\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n): Promise<T> {\n return root().timeAsync(label, fn, attributes);\n}\n\n/**\n * Adds a breadcrumb to the trail. The next error record carries the trail.\n * @param message Description of the event.\n * @param data Optional metadata. The library copies it now.\n */\nexport function addBreadcrumb(message: string, data?: Record<string, unknown>): void {\n requireRuntime().addBreadcrumb(message, data);\n}\n\n/**\n * Sets a key-value pair on the ambient context. All later records include it.\n * @param key Attribute key.\n * @param value Attribute value.\n */\nexport function setContext(key: string, value: unknown): void {\n requireRuntime().context.set(key, value);\n}\n\n/**\n * Merges multiple key-value pairs into the ambient context.\n * @param values Key-value map of attributes to add.\n */\nexport function setContextMap(values: Record<string, unknown>): void {\n requireRuntime().context.setMany(values);\n}\n\n/**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to delete.\n */\nexport function removeContext(key: string): void {\n requireRuntime().context.remove(key);\n}\n\n/**\n * Starts a new journey correlation context.\n * @param name Journey workflow identifier.\n * @param options `parent` links the active journey as the parent. `id` sets the journey id, a\n * string of 1 to 64 letters, digits, \"_\", \".\", \":\" or \"-\". Without it, the library makes an id.\n * @returns Started Journey instance.\n */\nexport function startJourney(name: string, options?: { parent?: boolean; id?: string }): Journey {\n return requireRuntime().journey.start(name, options);\n}\n\n/** Terminates the active journey correlation context. */\nexport function endJourney(): void {\n requireRuntime().journey.end();\n}\n\n/**\n * Returns the currently active journey, or null if none is in progress.\n * @returns Active Journey instance or null.\n */\nexport function currentJourney(): Journey | null {\n return requireRuntime().journey.current();\n}\n\n/**\n * Serializes active journey metadata into a cross-context URL token.\n * @returns Serialized token string, or undefined if no journey is active.\n */\nexport function getJourneyToken(): string | undefined {\n return requireRuntime().journey.getToken();\n}\n\n/**\n * Adopts a serialized journey token into this application realm.\n * @param token Serialized journey token.\n * @returns True if the token is valid and the runtime adopts it.\n */\nexport function adoptJourney(token: string): boolean {\n return requireRuntime().journey.adopt(token, \"manual\", true);\n}\n\n/**\n * Connects a Web Worker or MessagePort to the document bus for record routing.\n * @param worker Target Worker or MessagePort instance.\n * @param options Permissions of the worker. The default permission is \"records\".\n * @returns Function that removes this registration.\n */\nexport function registerWorker(worker: WorkerLike, options?: SourceOptions): () => void {\n return requireRuntime().registerWorker(worker, options);\n}\n\n/**\n * Registers one frame or window at an exact origin.\n * @param frame Child frame or window to register.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\nexport function registerFrame(\n frame: HTMLIFrameElement | Window,\n options: FrameOptions,\n): () => void {\n return requireRuntime().registerFrame(frame, options);\n}\n\n/** Rotates trace context to begin a new distributed trace. */\nexport function startTrace(): void {\n requireRuntime().tracing.rotate(\"explicit\");\n}\n\n/**\n * Returns W3C traceparent headers for outgoing HTTP request propagation.\n * @returns Map of trace header keys and values.\n */\nexport function getTraceHeaders(): Record<string, string> {\n return requireRuntime().tracing.headers();\n}\n\n/**\n * Builds deferred calls and flushes pending batches across pipeline streams.\n * @returns Promise that resolves after the pipeline processes the queued batches.\n */\nexport function flush(): Promise<void> {\n return requireRuntime().flush();\n}\n\n/**\n * Counts the batches waiting in storage for delivery.\n * @returns Promise that resolves to the number of stored batches. A forwarder reports 0.\n * A forwarder does not store batches.\n */\nexport function getQueueDepth(): Promise<number> {\n return requireRuntime().queueDepth();\n}\n\n/**\n * Reads the delivery state of this context.\n * @returns Promise that resolves to the records that wait, the records in requests, the batches\n * in storage and the time of the last accepted send. A forwarder reports only its own buffers.\n */\nexport function getStats(): Promise<DeliveryStats> {\n return requireRuntime().stats();\n}\n\n/**\n * Starts new correlation in this tab. It ends the active journey and starts a new trace. Other\n * tabs read the new id at their next startup. Use rotateSecurityContext() at logout or at a\n * tenant change.\n */\nexport function newSession(): void {\n requireRuntime().newSession();\n}\n\n/**\n * Returns a snapshot of cumulative diagnostic event counts.\n * @returns Map of diagnostic fault codes to occurrence counts.\n */\nexport function getDiagnosticCounters(): Record<string, number> {\n return requireRuntime().diagnostics.snapshot();\n}\n\n/**\n * Flushes pending records and stops all runtime subsystems. It cancels a request that is still\n * open after the final flush. A stored batch of that request stays in storage.\n * @returns Promise that resolves when shutdown completes.\n */\nexport async function shutdown(): Promise<void> {\n await ObservabilityRuntime.current()?.destroy();\n}\n"],"mappings":"A,ujBAYA,SAASkJ,EAAQ,EAA2B,CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,EAAIC,GAAanJ,EAAAA,CAAkB,EAAIA,EAAAA,CAC5E,CAUA,SAASoJ,EACP,EACA,EACA,EACA,EACA,EACM,CACNC,EAAO,UAAU,GAAGC,EAAM,WAAYC,EAAU,KAAM,YAAa,CACjE,SACA,GAAGC,CACL,CAAC,CACH,CAUA,SAASC,EACP,EACA,EACA,EACA,EACA,EACM,CAEN,IAAMF,EAAWL,EAAQC,CAAS,EAClCE,EAAO,MAAM,GAAGC,EAAM,SAAUI,EAAO,CACrC,qBAAsBH,EACtB,OAAQ,UACR,GAAGC,CACL,CAAC,EACDJ,EAAOC,EAAQC,E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AAmB,CACjCpC,EAAe,CAAC,CAAC,QAAQ,OAAO,UAAU,CAC5C,CAMA,SAAgBqC,IAA0C,CACxD,OAAOrC,EAAe,CAAC,CAAC,QAAQ,QAAQ,CAC1C,CAMA,SAAgBsC,IAAuB,CACrC,OAAOtC,EAAe,CAAC,CAAC,MAAM,CAChC,CAOA,SAAgBuC,IAAiC,CAC/C,OAAOvC,EAAe,CAAC,CAAC,WAAW,CACrC,CAOA,SAAgBwC,IAAmC,CACjD,OAAOxC,EAAe,CAAC,CAAC,MAAM,CAChC,CAOA,SAAgByC,IAAmB,CACjCzC,EAAe,CAAC,CAAC,WAAW,CAC9B,CAMA,SAAgB0C,IAAgD,CAC9D,OAAO1C,EAAe,CAAC,CAAC,YAAY,SAAS,CAC/C,CAOA,eAAsB2C,IAA0B,CAC9C,MAAMjI,EAAqB,QAAQ,CAAC,EAAE,QAAQ,CAChD,C"}
1
+ {"version":3,"file":"index.cjs","names":["DURATION_PRECISION","timeSync","timeAsync","DEFER_IDLE_TIMEOUT_MS","DEFER_QUEUE_LIMIT","CAPTURE_NAMESPACE","STORAGE_NAMESPACE","DIAGNOSTICS_NAMESPACE","isErrorLike","ERROR_OWN_KEYS","isDataField","isObject","DEFAULT_METRIC_UNIT","METRIC_KEYS","timeSync","timeAsync","nowUnixNano","currentUrl","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","ATTR_JOURNEY_PARENT_ID","METRIC_KEYS","METRIC_DEFAULT_BOUNDARIES","ATTR_METRIC_OVERFLOW","RECORD_LIMITS","LEVEL_ORDER","isLibraryConsole","sanitize","randomHex","TRACE_MAX_AGE_MS","TRACEPARENT_HEADER","LEVEL_ORDER","BEACON_LIMIT_BYTES","PROFILER_PROBE_LIMIT","isObject","SERIALIZER_NAME_OTLP","CONSOLE_DEFAULT_STYLES","CONSOLE_DEFAULT_LEVEL","REMOTE_CAPTURE_FLAGS","RESOURCE_SLOW_MS","recordedUrl","DEFAULT_CONFIG","UNKNOWN_SERVICE_NAME","UNDEFAULTED_CONFIG_KEYS","CONFIG_SECTIONS","UNDEFAULTED_SECTION_KEYS","ATTR_DEBUG_BUFFER","DIAGNOSTIC_THROTTLE_MS","LIBRARY_LOG_PREFIX","attributeOf","ATTR_JOURNEY_ID","isActionRecord","isActionRecord","METRIC_DEFAULT_BOUNDARIES","ATTR_PAGE_URL","ATTR_JOURNEY_ID","ATTR_JOURNEY_NAME","METRIC_KEYS","SPAN_KEYS","LEVEL_BYPASS_TYPES","levelFor","LEVEL_ORDER","shouldSampleInput","currentUrl","recordedUrl","sanitizeWithSize","ATTR_SANITIZE_FAILED","ATTR_LOG_TYPE","ATTR_LOG_SEQ","ATTR_APP_NAMESPACE","ATTR_JOURNEY_PARENT_ID","truncate","nowUnixNano","SEVERITY_NUMBER","ATTR_ATTRIBUTES_DROPPED","ATTR_ATTRIBUTES_BYTES","ATTR_ERROR_DATA","ATTR_BREADCRUMBS","isLogRecord","isLogLevel","isObject","RESOURCE_SERVICE_NAME","RESOURCE_SERVICE_VERSION","RESOURCE_DEPLOYMENT_ENVIRONMENT","RESOURCE_TELEMETRY_SDK_NAME","TELEMETRY_SDK_NAME","RESOURCE_TELEMETRY_SDK_VERSION","TELEMETRY_SDK_VERSION","RESOURCE_TELEMETRY_SDK_LANGUAGE","TELEMETRY_SDK_LANGUAGE","RESOURCE_HOST_PLATFORM","RESOURCE_SESSION_ID","RESOURCE_TAB_ID","RESOURCE_CONTEXT_ID","RESOURCE_BROWSER_USER_AGENT","RESOURCE_OPENFIN_UUID","RESOURCE_OPENFIN_NAME","SPAN_KEYS","RUNTIME_GLOBAL_KEY","RUNTIME_STOPPED_KEY","isObject","recordedUrl","TELEMETRY_SDK_VERSION","DIAGNOSTICS_NAMESPACE","detectPlatform","newId","memoryStores","BROWSER_STORES","resolveIdentity","SessionTouch","sampleKey","JOURNEY_OPTIONS","JourneyEngine","truncate","sanitize","TRACE_NAMESPACE","METRIC_NAMESPACE","profilerCore","REMOTE_CAPTURE_FLAGS","CAPTURE_NAMESPACE","INSTRUMENT_OPTIONS_FAULT","runAsLibraryRequest","isLogRecord","shouldSample","STORAGE_NAMESPACE","ATTR_BREADCRUMBS","ATTR_PAGE_URL","isObject","TRANSPORT_WORKER_TYPE","TRANSPORT_WORKER_REFUSAL","INSTRUMENT_OPTIONS_FAULT","profilerCore","require_constants","require_log_record","require_error_like","require_guards","require_unref","require_platform","require_profiler","require_library_console","require_sanitize","require_identity","require_library_request","require_batch","require_journey","require_sampling","elapsed","startedAt","finish","logger","label","duration","attributes","fail","error","timeSync$1","result","fn","timeAsync$1","queues","cancel","idle","queue","schedule","drain","owner","deadline","work","index","deferWrite","capacity","limit","diagnostics","drainDeferred","cancelDeferred","_work","LIBRARY_NAMESPACES","toError","known","value","copy","text","consoleError","reason","errorData","source","errorLike","data","count","key","field","isPlainObject","proto","levelTypeFor","namespace","own","copyPayload","payload","OneLogger","bind","options","message","name","runtime","copied","unit","type","snapshot","level","body","journey","input","hooks","keepsCrumb","protectedCrumb","dropped","safe","record","crumb","ships","asPayload","asError","shown","clean","OVERFLOW_KEY","RECORD_KEYS","cleanAttributes","copyBounds","bounds","i","isAscending","bound","fieldsOf","point","def","start","series","readOptions","fault","makeCounter","makeHistogram","boundaries","Meter","intervalMs","emit","policy","instrument","instruments","one","found","valid","set","size","buckets","METHOD","ConsoleSink","settings","limits","prefix","method","details","styles","Sequence","TRACE_ID_PATTERN","SPAN_ID_PATTERN","NON_ZERO","isUsableSpanContext","context","newTraceId","newSpanId","mintAmbient","traceparent","traceId","spanId","traceFlags","toTraceContext","ambient","TraceEngine","maxAgeMs","load","spans","otel","span","spanContext","old","next","carrier","\"traceparent\"","fromOtel","ctx","kept","flags","client","BreadcrumbBuffer","recent","LEVEL_NAMES","COMPRESSION_VALUES","CREDENTIALS_VALUES","STORAGE_VALUES","IDENTITY_VALUES","BUS_MODE_VALUES","OPENFIN_ROLE_VALUES","JOURNEY_SCOPE_VALUES","CONSOLE_METHOD_VALUES","RETENTION_MODE_VALUES","BATCHING_RANGES","RETENTION_RANGES","LIMIT_RANGES","JOURNEY_AGE_RANGE","DURATION_RANGE","COUNT_RANGE","POSITIVE_RANGE","CLICK_WAIT_RANGE","isStrings","entry","isFunctions","isFunctionOrNull","isHeaders","isRecord","keepKind","fallback","test","reportInvalid","expected","POLICY_RULES","resolveDiagnosticRecords","CAPTURE_FLAG_KEYS","SANDBOX_ORIGIN","LEVEL_EXPECTED","listOf","CONSOLE_CAPTURE_EXPECTED","PATTERN_LIST_EXPECTED","TARGET_LIST_EXPECTED","ORIGIN_LIST_EXPECTED","STRING_LIST_EXPECTED","DIAGNOSTIC_RECORDS_EXPECTED","quoted","values","describeValue","resolveChoice","match","accepted","resolveBoolean","resolveNonNegative","resolveInteger","min","max","range","resolveCacheLimit","previous","resolveRanges","given","keys","ranges","section","base","toLevel","upper","resolveLevel","resolveMinLevels","levels","raw","resolveList","entries","accept","toProcessor","toPlugin","toStringEntry","toPattern","toConsoleMethod","toOrigin","origin","toTarget","isStringRecord","resolveHeaders","isSerializer","resolveSerializer","requested","CONSOLE_STYLE_KEYS","validStyles","resolveConsoleLevel","resolveConsole","resolveSampling","resolveBus","resolveJourney","resolveRetention","resolveCaptureConsole","resolveCapture","capture","resolveResourceTiming","resolveInteractions","ignore","ignoreSelector","actionAttribute","SIGNAL_OFF","resolveSignalEndpoint","url","serializer","resolvePolicy","rules","choice","custom","resolved","resolveConfig","policies","merged","rate","maxRate","rates","ns","r","reportUnknownKeys","sectionKeys","applyResolvedConfig","target","ContextStore","DebugBuffer","enabled","maxRecords","oldest","Diagnostics","handler","throttleMs","consoleFallback","total","code","by","now","event","addCapped","list","DropReporter","config","records","batchIds","summary","id","summaries","onDrop","HoldBuffer","action","TOTAL_DURATION","PHASE_DURATION","createMeasure","startMs","open","ended","epoch","at","closePhase","sinks","outcome","fields","ERROR_ATTR_PREFIX","REDACTABLE_INDEX_KEYS","HOOK_STAGES","FIXED_KEYS","fixedOf","asAttributes","RecordBuilder","deps","minLevel","debug","forConsole","traceCtx","tracing","activeJourney","sampled","remote","seq","sequence","pageUrl","bytes","fromContext","fromProvider","fromScope","fromPayload","stages","hook","keptBytes","breadcrumbs","crumbBytes","redact","current","stage","remeasured","fixed","changed","candidate","provider","platform","identity","US_PER_MS","ROOT_NAMES","unixNano","ms","rootSpan","spanFields","CAPTURE_LOADERS","pluginIds","lastPluginId","pluginId","plugin","RUNTIME_KEY","STOPPED_KEY","SENDER_SECTIONS","DELIVERY_RESET","ROUTING_KEYS","NOTICE_CODES","captureKey","recordDetail","detail","consoleOnly","sends","ownVersion","ObservabilityRuntime","locked","mismatch","keeps","points","core","sink","consent","bus","reply","local","pinned","stopped","implicit","foundText","sameConfig","processors","probe","refused","maxProbes","sections","built","captures","journeyReady","Bus","rotating","shared","sender","Sender","storage","state","wire","framePhases","framePacing","replay","generation","replayKey","names","profiler","classes","WebSocketCapture","CaptureModule","plugins","metric","cancelled","detach","worker","frame","closing","redacted","buffered","batch","fresh","sessionId","pending","timeoutMs","update","nextId","delivery","before","oldUrls","newUrls","held","retired","live","stored","crumbs","configSummary","issues","scope","backing","createStorage","storageName","storageLimits","store","ContextStorage","clearEmergencyContext","a","b","seen","ak","bk","active","serveTransportWorker","port","onMessage","incoming","module","stop","createMemoryTransport","sent","answer","request","retryAfterMs","loggers","requireRuntime","clearPersistedLogs","configure","trimLoggerCache","setConfigurationLocked","rotateSecurityContext","getHealth","collectDebugBundle","health","getLogger","root","trace","info","warn","err","fatal","logAction","logEvent","logMetric","optionsFault","counter","histogram","startMeasure","startReplay","stopReplay","timeSync","timeAsync","addBreadcrumb","setContext","setContextMap","removeContext","startJourney","endJourney","currentJourney","getJourneyToken","adoptJourney","token","registerWorker","registerFrame","startTrace","getTraceHeaders","flush","getQueueDepth","getStats","newSession","getDiagnosticCounters","shutdown"],"sources":["../src/utils/timer.ts","../src/core/deferred.ts","../src/core/logger.ts","../src/core/meter.ts","../src/utils/console.ts","../src/utils/sequence.ts","../src/utils/tracing.ts","../src/core/breadcrumbs.ts","../src/core/config.ts","../src/core/context.ts","../src/core/debug-buffer.ts","../src/core/diagnostics.ts","../src/core/drops.ts","../src/core/hold-buffer.ts","../src/core/measure.ts","../src/core/record.ts","../src/core/spans.ts","../src/core/runtime.ts","../src/transport/worker-entry.ts","../src/transport/memory-transport.ts","../src/index.ts"],"sourcesContent":["// src/utils/timer.ts\n//\n// Logs the duration of synchronous and asynchronous operations as metrics.\n\nimport type { CaptureLogger } from \"../capture/types\";\nimport { DURATION_PRECISION } from \"../constants\";\n\n/**\n * Calculates elapsed milliseconds, rounded to the configured precision.\n * @param startedAt Performance timestamp recorded at operation start.\n * @returns Elapsed duration in milliseconds.\n */\nfunction elapsed(startedAt: number): number {\n return Math.round((performance.now() - startedAt) * DURATION_PRECISION) / DURATION_PRECISION;\n}\n\n/**\n * Logs the operation duration as a histogram metric, for each outcome.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param duration Elapsed duration in milliseconds.\n * @param status Outcome status string.\n * @param attributes Optional contextual attributes.\n */\nfunction finish(\n logger: CaptureLogger,\n label: string,\n duration: number,\n status: string,\n attributes?: Record<string, unknown>,\n): void {\n logger.logMetric(`${label}.duration`, duration, \"ms\", \"histogram\", {\n status,\n ...attributes,\n });\n}\n\n/**\n * Logs an operation failure and its FAILURE duration histogram.\n * @param logger Target telemetry logger.\n * @param label Operation label.\n * @param startedAt Performance timestamp recorded at operation start.\n * @param error Caught error instance or thrown value.\n * @param attributes Optional contextual attributes.\n */\nfunction fail(\n logger: CaptureLogger,\n label: string,\n startedAt: number,\n error: unknown,\n attributes?: Record<string, unknown>,\n): void {\n // Read the duration once, so the error record and the metric report the same value.\n const duration = elapsed(startedAt);\n logger.error(`${label} failed`, error, {\n \"action.duration_ms\": duration,\n status: \"FAILURE\",\n ...attributes,\n });\n finish(logger, label, duration, \"FAILURE\", attributes);\n}\n\n/**\n * Executes and measures the duration of a synchronous function.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param fn Synchronous function to execute.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the wrapped function.\n */\nexport function timeSync<T>(\n logger: CaptureLogger,\n label: string,\n fn: () => T,\n attributes?: Record<string, unknown>,\n): T {\n const startedAt = performance.now();\n try {\n const result = fn();\n finish(logger, label, elapsed(startedAt), \"SUCCESS\", attributes);\n return result;\n } catch (error) {\n // Rethrow, so the caller keeps its control flow.\n fail(logger, label, startedAt, error, attributes);\n throw error;\n }\n}\n\n/**\n * Executes and measures the duration of an asynchronous promise-returning function.\n * @param logger Target telemetry logger.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to execute.\n * @param attributes Optional contextual attributes.\n * @returns A promise that resolves to the wrapped function's result.\n */\nexport async function timeAsync<T>(\n logger: CaptureLogger,\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n): Promise<T> {\n const startedAt = performance.now();\n try {\n const result = await fn();\n finish(logger, label, elapsed(startedAt), \"SUCCESS\", attributes);\n return result;\n } catch (error) {\n // Rethrow, so the caller keeps its control flow.\n fail(logger, label, startedAt, error, attributes);\n throw error;\n }\n}\n","import { DEFER_IDLE_TIMEOUT_MS, DEFER_QUEUE_LIMIT } from \"../constants\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** One runtime's pending logger calls. A stopped runtime releases every payload reference. */\ninterface DeferredQueue {\n work: (() => void)[];\n diagnostics: Diagnostics;\n draining: boolean;\n idle?: number;\n timer?: ReturnType<typeof setTimeout>;\n}\n\nconst queues = new WeakMap<object, DeferredQueue>();\n\n/** Cancels the scheduled callback before a synchronous drain or a shutdown. */\nfunction cancel(queue: DeferredQueue): void {\n const idle = queue.idle;\n if (idle !== undefined) {\n queue.diagnostics.guard(\"pipeline.crashed\", \"The idle callback could not be cancelled.\", () => {\n cancelIdleCallback(idle);\n });\n queue.idle = undefined;\n }\n\n clearTimeout(queue.timer);\n queue.timer = undefined;\n}\n\n/** Schedules one idle callback, or a timer in browsers without the idle API. */\nfunction schedule(owner: object, queue: DeferredQueue): void {\n if (typeof requestIdleCallback === \"function\" && typeof cancelIdleCallback === \"function\") {\n queue.idle = queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The idle callback could not be scheduled.\",\n () =>\n requestIdleCallback(\n (deadline) => {\n drain(owner, queue, deadline);\n },\n { timeout: DEFER_IDLE_TIMEOUT_MS },\n ),\n );\n if (queue.idle !== undefined) {\n return;\n }\n }\n\n queue.timer = setTimeout(() => {\n drain(owner, queue);\n }, 0);\n unrefTimer(queue.timer);\n}\n\n/** Builds a bounded group of calls. Reentrant calls wait for the next callback. */\nfunction drain(owner: object, queue: DeferredQueue, deadline?: IdleDeadline): void {\n if (queues.get(owner) !== queue || queue.draining) {\n return;\n }\n\n cancel(queue);\n queue.draining = true;\n const work = queue.work;\n queue.work = [];\n let index = 0;\n\n while (\n index < work.length &&\n (!deadline || (deadline.didTimeout && index === 0) || deadline.timeRemaining() > 0)\n ) {\n queue.diagnostics.guard(\n \"pipeline.crashed\",\n \"The library could not build a deferred record.\",\n work[index],\n );\n index++;\n if (queues.get(owner) !== queue) {\n return;\n }\n }\n\n queue.work = [...work.slice(index), ...queue.work];\n queue.draining = false;\n if (queue.work.length > 0) {\n schedule(owner, queue);\n } else {\n queues.delete(owner);\n }\n}\n\n/** Queues a call without reading its payload. A full queue builds its pending calls first. */\nexport function deferWrite(\n owner: object,\n work: () => void,\n diagnostics: Diagnostics,\n limit: number,\n): void {\n let queue = queues.get(owner);\n const capacity = limit > 0 ? Math.min(limit, DEFER_QUEUE_LIMIT) : DEFER_QUEUE_LIMIT;\n if (queue && queue.work.length >= capacity && !queue.draining) {\n drain(owner, queue);\n queue = queues.get(owner);\n }\n\n if (queue) {\n if (queue.work.length >= capacity) {\n diagnostics.count(\"record.dropped_by_ceiling\");\n return;\n }\n queue.work.push(work);\n return;\n }\n\n queue = { work: [work], diagnostics, draining: false };\n queues.set(owner, queue);\n schedule(owner, queue);\n}\n\n/** Builds pending calls before a flush, a session change or a delivery identity change. */\nexport function drainDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n drain(owner, queue);\n }\n}\n\n/** Releases calls that a hook queues during shutdown. No records were built for them. */\nexport function cancelDeferred(owner: object): void {\n const queue = queues.get(owner);\n if (queue) {\n cancel(queue);\n queues.delete(owner);\n for (const _work of queue.work) {\n queue.diagnostics.count(\"record.dropped_by_ceiling\");\n }\n queue.work = [];\n }\n}\n","// src/core/logger.ts\n//\n// Namespaced logger facade with scoped log methods and metric timers.\n\nimport {\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_SANITIZE_FAILED,\n CAPTURE_NAMESPACE,\n DEFAULT_METRIC_UNIT,\n DIAGNOSTICS_NAMESPACE,\n METRIC_KEYS,\n STORAGE_NAMESPACE,\n} from \"../constants\";\nimport {\n type LogLevel,\n type LogRecord,\n type LogType,\n type MetricType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { ERROR_OWN_KEYS, isDataField, isErrorLike } from \"../utils/error-like\";\nimport { isObject } from \"../utils/guards\";\nimport { timeAsync, timeSync } from \"../utils/timer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { DropReason, RecordSnapshot } from \"./record\";\nimport { deferWrite } from \"./deferred\";\nimport { currentUrl } from \"../utils/platform\";\nimport type { ObservabilityRuntime } from \"./runtime\";\n\n/** The library's own namespaces. Their records get log.type \"system\". */\nconst LIBRARY_NAMESPACES: readonly string[] = [\n CAPTURE_NAMESPACE,\n STORAGE_NAMESPACE,\n DIAGNOSTICS_NAMESPACE,\n];\n\n/** Configuration options for a scoped OneLogger instance. */\nexport interface OneLoggerOptions {\n /** Contextual attributes merged into all records emitted by this logger. */\n scopedContext?: Record<string, unknown>;\n}\n\n/**\n * Turns any thrown value into an Error. A real error is copied with its name, message and stack.\n * @param value Caught error instance or primitive value.\n * @param diagnostics Diagnostics reporter.\n * @returns Normalized Error instance.\n */\nfunction toError(value: unknown, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof and from any property read, and a Proxy around\n // an Error passes instanceof, so read its fields here, inside the guard.\n const known = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n (): Error | undefined => {\n if (!(value instanceof Error) && !isErrorLike(value)) {\n return undefined;\n }\n\n const copy = new Error(value.message);\n copy.name = value.name;\n copy.stack = value.stack;\n return copy;\n },\n );\n\n if (known) {\n return known;\n }\n\n // String() throws on a null-prototype object and on a throwing toString. log.error() runs\n // inside the consumer's catch block, so it must not throw out of it.\n const text = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not convert the error reason to text.\",\n () => String(value),\n );\n\n return new Error(text ?? typeof value);\n}\n\n/**\n * Returns the error the console prints. The console shows a real Error's cause and own\n * fields, while the record keeps the copy from toError().\n * @param reason Error reason.\n * @param copy Normalized copy of the reason.\n * @param diagnostics Diagnostics reporter.\n * @returns The reason if it is an Error, otherwise the copy.\n */\nfunction consoleError(reason: unknown, copy: Error, diagnostics: Diagnostics): Error {\n // A Proxy reason can throw from instanceof.\n const original = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error reason.\",\n () => (reason instanceof Error ? reason : copy),\n );\n\n return original ?? copy;\n}\n\n/**\n * Reads an error reason's data for the error.data attribute. Keeps only own fields whose\n * value is a string, number or boolean.\n * @param value Error reason.\n * @param diagnostics Diagnostics reporter.\n * @returns An object reason's fields, a primitive reason, or undefined. A string reason\n * returns undefined because error.message already holds it.\n */\nfunction errorData(value: unknown, diagnostics: Diagnostics): unknown {\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\") {\n return value;\n }\n\n if (typeof value !== \"object\" || value === null) {\n return undefined;\n }\n\n return diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the properties of the error reason.\",\n () => {\n const source = value as Record<string, unknown>;\n const errorLike = isErrorLike(value);\n const data: Record<string, unknown> = {};\n let count = 0;\n\n // An object field, such as an AxiosError's config, can hold credentials.\n for (const key of Object.keys(source)) {\n const field = source[key];\n if ((!errorLike || !ERROR_OWN_KEYS.has(key)) && isDataField(field)) {\n data[key] = field;\n count++;\n }\n }\n\n return count === 0 ? undefined : data;\n },\n );\n}\n\n/**\n * Checks whether a value is an attribute bag rather than an error reason. Works across\n * realms, because an object literal from an iframe has that realm's Object.prototype, whose\n * own prototype is also null.\n * @param value Value found in the error slot.\n * @returns True if the value is a plain object.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!isObject(value)) {\n return false;\n }\n if (value instanceof Error) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n\n/**\n * Picks the log.type the level methods use for a namespace.\n * @param namespace Logger namespace.\n * @returns \"system\" for one of the library's namespaces, \"log\" for any other.\n */\nfunction levelTypeFor(namespace: string): LogType {\n const library = LIBRARY_NAMESPACES.some(\n (own) => namespace === own || namespace.startsWith(`${own}.`),\n );\n\n return library ? \"system\" : \"log\";\n}\n\n/**\n * Copies a caller payload, so a Proxy with a throwing trap can't throw out of a log call.\n * @param payload Caller payload.\n * @param diagnostics Diagnostics reporter.\n * @returns The copy, or a marker attribute when the payload can't be read.\n */\nfunction copyPayload(\n payload: Record<string, unknown> | undefined,\n diagnostics: Diagnostics,\n): Record<string, unknown> {\n if (payload === undefined) {\n return {};\n }\n\n const copied = diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the payload.\",\n () => ({ ...payload }),\n );\n\n return copied ?? { [ATTR_SANITIZE_FAILED]: true };\n}\n\n/** Namespaced logger instance for recording structured events, metrics, and errors. */\nexport class OneLogger {\n /** log.type the level methods use. \"system\" only for the library's own namespaces. */\n private readonly levelType: LogType;\n\n /**\n * @param bind Returns the runtime for each write, so a logger created before configure()\n * still writes to the configured runtime.\n * @param namespace Application subsystem or module namespace.\n * @param options Scoped context options.\n */\n constructor(\n private readonly bind: () => ObservabilityRuntime,\n readonly namespace: string,\n private readonly options: OneLoggerOptions = {},\n ) {\n this.levelType = levelTypeFor(namespace);\n }\n\n /**\n * Creates a child logger with a nested namespace and merged scoped context.\n * @param namespace Sub-namespace appended with dot notation.\n * @param options Additional scoped context attributes.\n * @returns Nested child OneLogger instance.\n */\n child(namespace: string, options: OneLoggerOptions = {}): OneLogger {\n return new OneLogger(this.bind, `${this.namespace}.${namespace}`, {\n scopedContext: {\n ...this.options.scopedContext,\n ...options.scopedContext,\n },\n });\n }\n\n /**\n * Logs a trace-level debug record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n trace = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"TRACE\", this.levelType, message, payload);\n };\n\n /**\n * Logs a debug-level record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n debug = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"DEBUG\", this.levelType, message, payload);\n };\n\n /**\n * Logs an informational record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n info = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", this.levelType, message, payload);\n };\n\n /**\n * Logs a warning record.\n * @param message Log message.\n * @param payload Optional contextual attributes.\n */\n warn = (message: string, payload?: Record<string, unknown>): void => {\n this.write(\"WARN\", this.levelType, message, payload);\n };\n\n /**\n * Logs an error record with the breadcrumb history. When payload is omitted, a plain\n * object in the error slot is used as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n error = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"ERROR\", message, error, payload);\n };\n\n /**\n * Logs a fatal error record. When payload is omitted, a plain object in the error slot\n * is used as the payload.\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n fatal = (message: string, error?: unknown, payload?: Record<string, unknown>): void => {\n this.writeError(\"FATAL\", message, error, payload);\n };\n\n /**\n * Logs a user action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\n logAction = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"action\", name, payload);\n };\n\n /**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\n logEvent = (name: string, payload?: Record<string, unknown>): void => {\n this.write(\"INFO\", \"event\", name, payload);\n };\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric identifier.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attributes Optional metric attributes.\n */\n logMetric = (\n name: string,\n value: number,\n unit = DEFAULT_METRIC_UNIT,\n type: MetricType = \"gauge\",\n attributes?: Record<string, unknown>,\n ): void => {\n // NaN and Infinity become null in JSON, which a backend then reads as a false zero.\n if (!Number.isFinite(value)) {\n this.bind().diagnostics.report(\n \"record.dropped_malformed\",\n \"The metric value is not a finite number. The library dropped the metric.\",\n { \"metric.name\": name },\n );\n return;\n }\n\n const runtime = this.bind();\n this.submit(runtime, \"INFO\", \"metric\", (snapshot) => {\n // Copy the caller's attributes first so the metric fields win.\n const copied = copyPayload(attributes, runtime.diagnostics);\n const payload = {\n ...copied,\n \"metric.name\": name,\n \"metric.value\": value,\n \"metric.unit\": unit,\n \"metric.type\": type,\n [METRIC_KEYS.attributeKeys]: Object.keys(copied),\n };\n this.writeNow(runtime, \"INFO\", \"metric\", name, payload, true, snapshot);\n });\n };\n\n /**\n * Times a synchronous function execution and records a duration metric.\n * @param label Metric name prefix.\n * @param fn Synchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Result returned by the timed function.\n */\n timeSync = <T>(label: string, fn: () => T, attributes?: Record<string, unknown>): T =>\n timeSync(this, label, fn, attributes);\n\n /**\n * Times an asynchronous function execution and records a duration metric.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to time.\n * @param attributes Optional contextual attributes.\n * @returns Promise that resolves to the result of the timed function.\n */\n timeAsync = <T>(\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n ): Promise<T> => timeAsync(this, label, fn, attributes);\n\n /**\n * Builds and emits a standard log record, and prints it to the console.\n * @param level Severity level.\n * @param type Record classification.\n * @param body Primary message.\n * @param payload Optional contextual attributes.\n */\n private write(\n level: LogLevel,\n type: LogType,\n body: string,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, type, (snapshot) => {\n this.writeNow(runtime, level, type, body, payload, false, snapshot);\n });\n }\n\n /** Runs a call right away, or queues it without reading its payload. */\n private submit(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n work: (snapshot?: RecordSnapshot) => void,\n ): void {\n if (runtime.isDestroyed()) {\n return;\n }\n if (runtime.isRotating()) {\n runtime.diagnostics.count(\"record.dropped_during_rotation\");\n return;\n }\n\n if (\n runtime.config.payloadMode === \"defer\" &&\n runtime.config.enabled &&\n !runtime.config.debugBuffer.enabled &&\n // A deferred diagnostic record is built outside its loop guard, so a hook failure would loop.\n this.namespace !== DIAGNOSTICS_NAMESPACE\n ) {\n if (\n !runtime.builder.isEnabled(level, this.namespace, type) &&\n !this.mirrors(runtime, level)\n ) {\n return;\n }\n\n const journey = runtime.journey.current();\n const snapshot: RecordSnapshot = {\n timeUnixNano: nowUnixNano(),\n trace: runtime.tracing.resolve(),\n journey: journey ? { ...journey } : null,\n context: runtime.context.getAll(),\n url: currentUrl(runtime.diagnostics),\n };\n deferWrite(\n runtime,\n () => {\n work(snapshot);\n },\n runtime.diagnostics,\n runtime.config.buffering.maxPendingRecords,\n );\n return;\n }\n\n work();\n }\n\n /** Builds a standard record once the call's payload is ready to read. */\n private writeNow(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n type: LogType,\n body: string,\n payload: Record<string, unknown> | undefined,\n copied: boolean,\n snapshot?: RecordSnapshot,\n ): void {\n // minLevel limits what we send, and the console level limits what we print. minLevel doesn't\n // apply to an action or a metric, and the debug buffer keeps records below it.\n const keepsDropped = runtime.config.enabled && runtime.config.debugBuffer.enabled;\n if (!keepsDropped && !runtime.builder.isEnabled(level, this.namespace, type)) {\n if (this.mirrors(runtime, level)) {\n this.print(runtime, level, body, payload, undefined, null, undefined, snapshot);\n }\n\n return;\n }\n\n const input = {\n snapshot,\n level,\n type,\n body,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: copied ? payload : copyPayload(payload, runtime.diagnostics),\n };\n const { record, dropped } = runtime.builder.build(input);\n const hooks = Boolean(runtime.config.redact) || runtime.config.processors.length > 0;\n // Only run the hooks on a sampled-out record if a breadcrumb keeps its message.\n const keepsCrumb = type !== \"metric\" && runtime.config.capturePolicy.breadcrumbs > 0;\n const protectedCrumb =\n dropped === \"sampling\" && hooks && keepsCrumb\n ? runtime.builder.build(input, true)\n : undefined;\n const safe = record ?? protectedCrumb?.record ?? null;\n const crumb = safe ? safe.body : dropped === \"sampling\" && !hooks ? body : undefined;\n if (keepsCrumb && crumb !== undefined) {\n runtime.breadcrumbs.push({\n t: snapshot ? Number(snapshot.timeUnixNano.slice(0, -6)) : Date.now(),\n category: type === \"action\" ? \"action\" : type === \"event\" ? \"event\" : \"log\",\n message: crumb,\n });\n }\n this.print(\n runtime,\n level,\n body,\n payload,\n undefined,\n safe,\n protectedCrumb?.dropped ?? dropped,\n snapshot,\n );\n runtime.emit(record);\n }\n\n /**\n * Builds and emits an error record with breadcrumbs, and prints it to the console.\n * @param level Severity level (\"ERROR\" or \"FATAL\").\n * @param message Error description.\n * @param error Caught error instance, reason, or payload.\n * @param payload Optional contextual attributes.\n */\n private writeError(\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload?: Record<string, unknown>,\n ): void {\n const runtime = this.bind();\n this.submit(runtime, level, this.levelType, (snapshot) => {\n this.writeErrorNow(runtime, level, message, error, payload, snapshot);\n });\n }\n\n /** Builds an error record once the deferred queue releases its payload. */\n private writeErrorNow(\n runtime: ObservabilityRuntime,\n level: \"ERROR\" | \"FATAL\",\n message: string,\n error: unknown,\n payload: Record<string, unknown> | undefined,\n snapshot?: RecordSnapshot,\n ): void {\n const ships = runtime.builder.isEnabled(level, this.namespace);\n\n if (!ships && !this.mirrors(runtime, level)) {\n return;\n }\n\n // Every sibling method takes (name, payload?), so callers expect log.error(\"failed\", { id })\n // to work. Treated as an error reason, that object would put \"[object Object]\" in\n // error.message and drop the caller's fields. A Proxy in the error slot can throw on the check.\n const asPayload =\n payload === undefined &&\n (runtime.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the error slot.\",\n () => isPlainObject(error),\n ) ??\n false);\n const attributes = asPayload ? (error as Record<string, unknown>) : payload;\n const reason = asPayload ? undefined : error;\n const asError = reason === undefined ? undefined : toError(reason, runtime.diagnostics);\n const shown =\n asError === undefined ? undefined : consoleError(reason, asError, runtime.diagnostics);\n\n if (!ships) {\n this.print(runtime, level, message, attributes, shown, null, undefined, snapshot);\n return;\n }\n\n const data = asError ? errorData(reason, runtime.diagnostics) : undefined;\n\n const { record, dropped } = runtime.builder.build({\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(attributes, runtime.diagnostics),\n ...(asError\n ? {\n \"error.type\": asError.name,\n \"error.message\": asError.message,\n \"error.stack_trace\": asError.stack,\n }\n : {}),\n ...(data === undefined ? {} : { [ATTR_ERROR_DATA]: data }),\n [ATTR_BREADCRUMBS]: runtime.breadcrumbs.snapshot(),\n },\n });\n\n this.print(runtime, level, message, attributes, shown, record, dropped, snapshot);\n runtime.emit(record);\n }\n\n /**\n * Prints one log line. With a redact hook or processors, the line shows only what they\n * returned. A host can record console arguments, so the console must not show what the hooks\n * remove.\n * @param runtime The runtime for this write.\n * @param level Severity level.\n * @param message Primary message.\n * @param payload Caller payload.\n * @param error The error from an error call.\n * @param record Built record, or null if it was never built or redact dropped it.\n * @param dropped Why the builder dropped the record, if it did.\n */\n private print(\n runtime: ObservabilityRuntime,\n level: LogLevel,\n message: string,\n payload: Record<string, unknown> | undefined,\n error: Error | undefined,\n record: LogRecord | null,\n dropped?: DropReason,\n snapshot?: RecordSnapshot,\n ): void {\n if (!runtime.config.redact && runtime.config.processors.length === 0) {\n runtime.console.write(this.namespace, level, message, payload, error);\n return;\n }\n\n // The record's attributes hold the error fields after redact.\n if (record) {\n runtime.console.write(this.namespace, level, record.body, record.attributes);\n return;\n }\n\n // A record dropped by a hook or the shape check prints nothing. Its text never passed redact.\n if (dropped === \"processor\" || dropped === \"redact\" || dropped === \"malformed\") {\n return;\n }\n\n if (!runtime.config.enabled || !runtime.console.accepts(level)) return;\n // Use the record builder without the delivery level and sampling checks. Don't process\n // a record again if a hook refused it, and don't send this one or add it as a breadcrumb.\n const clean = runtime.builder.build(\n {\n snapshot,\n level,\n type: this.levelType,\n body: message,\n namespace: this.namespace,\n scoped: this.options.scopedContext,\n payload: {\n ...copyPayload(payload, runtime.diagnostics),\n ...(error\n ? {\n \"error.type\": error.name,\n \"error.message\": error.message,\n \"error.stack_trace\": error.stack,\n }\n : {}),\n },\n },\n true,\n ).record;\n if (clean) runtime.console.write(this.namespace, level, clean.body, clean.attributes);\n }\n\n /**\n * Checks whether the console prints a level that we don't send.\n * @param runtime The runtime for this write.\n * @param level Severity level.\n * @returns True if logging is on and the console accepts the level.\n */\n private mirrors(runtime: ObservabilityRuntime, level: LogLevel): boolean {\n return runtime.config.enabled && runtime.console.accepts(level);\n }\n}\n","// src/core/meter.ts\n//\n// Sums counter and histogram values in memory. At every interval it emits one point per\n// instrument and attribute set, so a thousand adds produce one record, not a thousand.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_METRIC_OVERFLOW,\n ATTR_PAGE_URL,\n DEFAULT_METRIC_UNIT,\n METRIC_DEFAULT_BOUNDARIES,\n METRIC_KEYS,\n} from \"../constants\";\nimport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentDef,\n InstrumentOptions,\n MetricAttributes,\n} from \"../models/metric\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** One attribute set's sums in the current interval. */\ninterface Series {\n /** The series' attribute set. */\n attributes: MetricAttributes;\n /** Number of values. */\n count: number;\n /** Sum of the values. */\n sum: number;\n /** Smallest value. */\n min: number;\n /** Largest value. */\n max: number;\n /** Count per histogram bucket. A counter has none. */\n buckets: number[];\n}\n\n/** One instrument's series in the current interval. */\ninterface Instrument {\n /** Definition taken from the interval's first value. */\n def: InstrumentDef;\n /** Series by attribute set key. */\n series: Map<string, Series>;\n}\n\n/** Key of the overflow series. An attribute set's key is JSON text, which starts with \"{\". */\nconst OVERFLOW_KEY = \"overflow\";\n\n/** Keys the record builder sets. It overwrites a call attribute with the same name. */\nconst RECORD_KEYS = new Set<string>([\n ATTR_LOG_TYPE,\n ATTR_LOG_SEQ,\n ATTR_APP_NAMESPACE,\n ATTR_PAGE_URL,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n]);\n\n/**\n * Keeps the string, finite number and boolean attributes, in key order. Two calls with the same\n * set in a different key order then share one series.\n * @param attributes The call's attribute set.\n * @returns The clean attribute set.\n */\nfunction cleanAttributes(attributes: MetricAttributes = {}): MetricAttributes {\n const clean: MetricAttributes = {};\n\n for (const key of Object.keys(attributes).sort()) {\n // The builder and the serializer replace or remove these keys. Keeping them would give\n // every value its own series with the same output.\n if (key.startsWith(\"metric.\") || RECORD_KEYS.has(key)) {\n continue;\n }\n\n const value: unknown = attributes[key];\n const finite = typeof value === \"number\" && Number.isFinite(value);\n if (typeof value === \"string\" || typeof value === \"boolean\" || finite) {\n clean[key] = value;\n }\n }\n\n return clean;\n}\n\n/**\n * Copies a list of boundaries by index, so a custom iterator on the app's array has no effect.\n * @param bounds Value of the boundaries option.\n * @param limit Maximum number of boundaries. 0 means no limit.\n * @returns A plain array with at most one value more than the limit, or null if the value\n * isn't an array.\n */\nfunction copyBounds(bounds: unknown, limit: number): unknown[] | null {\n if (!Array.isArray(bounds)) {\n return null;\n }\n\n // One more than the limit, so isAscending rejects a list that is too long.\n const count = limit === 0 ? bounds.length : Math.min(bounds.length, limit + 1);\n return Array.from({ length: count }, (_unused, i): unknown => bounds[i]);\n}\n\n/**\n * Checks a list of histogram boundaries.\n * @param bounds Value of the boundaries option.\n * @param limit Maximum number of boundaries. 0 means no limit.\n * @returns True for finite numbers in ascending order, no more of them than the limit.\n */\nfunction isAscending(bounds: unknown, limit: number): bounds is number[] {\n return (\n Array.isArray(bounds) &&\n (limit === 0 || bounds.length <= limit) &&\n bounds.every(\n (bound: unknown, i) =>\n typeof bound === \"number\" &&\n Number.isFinite(bound) &&\n (i === 0 || bound > (bounds[i - 1] as number)),\n )\n );\n}\n\n/**\n * Builds the metric fields for one point. The call's attributes stay out.\n * @param def The instrument's definition.\n * @param series The attribute set's sums.\n * @param start Start of the interval, in Unix nanoseconds.\n * @returns The point's metric fields.\n */\nfunction fieldsOf(def: InstrumentDef, series: Series, start: string): Record<string, unknown> {\n const point: Record<string, unknown> = {\n \"metric.name\": def.name,\n \"metric.unit\": def.unit,\n \"metric.type\": def.kind,\n [METRIC_KEYS.start]: start,\n [METRIC_KEYS.attributeKeys]: Object.keys(series.attributes),\n };\n\n if (def.kind === \"counter\") {\n point[\"metric.value\"] = series.sum;\n return point;\n }\n\n return {\n ...point,\n [METRIC_KEYS.count]: series.count,\n [METRIC_KEYS.sum]: series.sum,\n [METRIC_KEYS.min]: series.min,\n [METRIC_KEYS.max]: series.max,\n [METRIC_KEYS.bounds]: def.boundaries,\n [METRIC_KEYS.buckets]: series.buckets,\n };\n}\n\n/** Adds a value to one of the runtime's instruments. */\nexport type RecordMetric = (\n def: InstrumentDef,\n value: number,\n attributes?: MetricAttributes,\n) => void;\n\n/** Called with whatever reading an options object threw. */\nexport type OptionsFault = (error: unknown) => void;\n\n/**\n * Reads an instrument's options. A getter or a Proxy trap on them can throw, and a JavaScript\n * caller can pass null.\n * @param options Options from the app.\n * @param fault Reports options that couldn't be read.\n * @returns The unit and the boundaries. Anything the app didn't set is undefined.\n */\nfunction readOptions(\n options: HistogramOptions,\n fault: OptionsFault,\n): { unit: string | undefined; boundaries: readonly number[] | undefined } {\n try {\n return { unit: options.unit, boundaries: options.boundaries };\n } catch (error) {\n fault(error);\n return { unit: undefined, boundaries: undefined };\n }\n}\n\n/**\n * Creates a counter handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values.\n * @param record Adds a value to the instrument.\n * @param fault Reports options that couldn't be read.\n * @returns The counter.\n */\nexport function makeCounter(\n name: string,\n options: InstrumentOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Counter {\n const def: InstrumentDef = {\n name,\n kind: \"counter\",\n unit: readOptions(options, fault).unit ?? DEFAULT_METRIC_UNIT,\n boundaries: [],\n };\n\n return {\n add: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/**\n * Creates a histogram handle. Never throws into the app.\n * @param name Metric name.\n * @param options Unit for the values, and the bucket boundaries.\n * @param record Adds a value to the instrument.\n * @param fault Reports options that couldn't be read.\n * @returns The histogram.\n */\nexport function makeHistogram(\n name: string,\n options: HistogramOptions,\n record: RecordMetric,\n fault: OptionsFault,\n): Histogram {\n const { unit, boundaries } = readOptions(options, fault);\n const def: InstrumentDef = {\n name,\n kind: \"histogram\",\n unit: unit ?? DEFAULT_METRIC_UNIT,\n boundaries: boundaries ?? METRIC_DEFAULT_BOUNDARIES,\n };\n\n return {\n record: (value, attributes) => {\n record(def, value, attributes);\n },\n };\n}\n\n/** Sums the values of counter and histogram instruments over one interval. */\nexport class Meter {\n /** Instruments with a value in the current interval. */\n private readonly instruments = new Map<string, Instrument>();\n\n /** Timer for the current interval. Runs only while a value is waiting. */\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** Time of the interval's first value, in epoch milliseconds. */\n private startedAt = 0;\n\n /**\n * @param intervalMs Returns the interval length, in milliseconds.\n * @param emit Builds and sends the record for one point from the call attributes and the\n * metric fields.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly intervalMs: () => number,\n private readonly emit: (\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ) => void,\n private readonly diagnostics: Diagnostics,\n private readonly policy = { maxSeries: 100, maxInstruments: 1000, maxHistogramBoundaries: 50 },\n ) {}\n\n /**\n * Adds a value to the series for its attribute set. Never throws into the app.\n * @param def The instrument's definition.\n * @param value Value to add.\n * @param attributes The value's attribute set.\n */\n record(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // NaN and Infinity become null in JSON, and a negative add breaks a counter's sum.\n if (!Number.isFinite(value) || (def.kind === \"counter\" && value < 0)) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The value of the metric ${def.name} is not valid. The library dropped it.`,\n { \"metric.name\": def.name },\n );\n return;\n }\n\n // A getter or a Proxy trap on the attributes can throw.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n `The library could not read the attributes of the metric ${def.name}.`,\n () => {\n const instrument = this.instrumentOf(def);\n if (instrument) {\n this.add(instrument, value, cleanAttributes(attributes));\n this.arm();\n }\n },\n );\n }\n\n /** Sends one point per series in the interval, then starts a new interval. */\n collect(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n const start = `${String(this.startedAt)}000000`;\n const instruments = [...this.instruments.values()];\n this.instruments.clear();\n\n for (const { def, series } of instruments) {\n for (const one of series.values()) {\n this.emit(def.name, one.attributes, fieldsOf(def, one, start));\n }\n }\n }\n\n /**\n * Finds the interval's instrument. The first value of the interval sets its definition.\n * @param def The call's definition.\n * @returns The instrument, or null when the name has another kind.\n */\n private instrumentOf(def: InstrumentDef): Instrument | null {\n const found = this.instruments.get(def.name);\n\n if (found) {\n if (found.def.kind === def.kind) {\n return found;\n }\n\n this.diagnostics.report(\n \"record.dropped_malformed\",\n `The metric ${def.name} is a counter and a histogram. The library dropped the value.`,\n { \"metric.name\": def.name },\n );\n return null;\n }\n\n if (this.policy.maxInstruments && this.instruments.size >= this.policy.maxInstruments) {\n this.diagnostics.count(\"record.dropped_by_ceiling\");\n return null;\n }\n // Copy before the check, so a later change to the app's array can't change the buckets.\n const copy = copyBounds(def.boundaries, this.policy.maxHistogramBoundaries);\n const valid = isAscending(copy, this.policy.maxHistogramBoundaries);\n if (def.kind === \"histogram\" && !valid) {\n this.diagnostics.report(\n \"config.invalid\",\n `The boundaries of the metric ${def.name} must meet metrics.maxHistogramBoundaries and contain finite numbers in ascending order. The library uses the default boundaries.`,\n );\n }\n\n const instrument: Instrument = {\n def: { ...def, boundaries: valid ? copy : [...METRIC_DEFAULT_BOUNDARIES] },\n series: new Map(),\n };\n this.instruments.set(def.name, instrument);\n return instrument;\n }\n\n /**\n * Adds a value to an attribute set's series.\n * @param instrument The value's instrument.\n * @param value Value to add.\n * @param attributes Clean attribute set.\n */\n private add(instrument: Instrument, value: number, attributes: MetricAttributes): void {\n let key = JSON.stringify(attributes);\n let series = instrument.series.get(key);\n let set = attributes;\n\n // Cap the series, or a storm of attribute sets grows memory and the payload without limit.\n if (!series && this.policy.maxSeries > 0 && instrument.series.size >= this.policy.maxSeries) {\n key = OVERFLOW_KEY;\n series = instrument.series.get(key);\n set = { [ATTR_METRIC_OVERFLOW]: true };\n }\n\n if (!series) {\n // A histogram has one more bucket than it has boundaries. The last has no upper bound.\n const size = instrument.def.kind === \"histogram\" ? instrument.def.boundaries.length + 1 : 0;\n const buckets = new Array<number>(size).fill(0);\n series = { attributes: set, count: 0, sum: 0, min: value, max: value, buckets };\n instrument.series.set(key, series);\n }\n\n series.count += 1;\n series.sum += value;\n series.min = Math.min(series.min, value);\n series.max = Math.max(series.max, value);\n\n if (series.buckets.length > 0) {\n const index = instrument.def.boundaries.findIndex((bound) => value <= bound);\n series.buckets[index === -1 ? series.buckets.length - 1 : index] += 1;\n }\n }\n\n /** Starts the interval's timer on its first value. An idle meter has no timer. */\n private arm(): void {\n if (this.timer !== null) {\n return;\n }\n\n this.startedAt = Date.now();\n this.timer = setTimeout(() => {\n this.collect();\n }, this.intervalMs());\n unrefTimer(this.timer);\n }\n}\n","// src/utils/console.ts\n//\n// Formats and mirrors log records to the developer console during local execution\n\nimport { LEVEL_ORDER, RECORD_LIMITS } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConsole } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport { isLibraryConsole, runAsLibraryConsole } from \"./library-console\";\nimport { type SanitizeLimits, sanitize } from \"./sanitize\";\n\n/** Maps each log level to its console method. */\nconst METHOD: Record<LogLevel, \"debug\" | \"info\" | \"warn\" | \"error\"> = {\n TRACE: \"debug\",\n DEBUG: \"debug\",\n INFO: \"info\",\n WARN: \"warn\",\n ERROR: \"error\",\n FATAL: \"error\",\n};\n\n/** Mirrors log records directly to browser or Node console methods based on severity. */\nexport class ConsoleSink {\n /**\n * @param settings Console level and styles. A null level prints nothing.\n * @param diagnostics Diagnostics reporter.\n * @param limits Size limits for the printed payload. Same as the record limits.\n */\n constructor(\n private settings: ResolvedConsole,\n private diagnostics: Diagnostics,\n private readonly limits: SanitizeLimits = RECORD_LIMITS,\n ) {}\n\n /**\n * Replaces the console level and styles.\n * @param settings Console level and styles. A null level prints nothing.\n */\n update(settings: ResolvedConsole): void {\n this.settings = settings;\n }\n\n /**\n * Checks whether a level clears the console threshold.\n * @param level Severity level of the record.\n * @returns True if the sink prints this level.\n */\n accepts(level: LogLevel): boolean {\n if (this.settings.level === null) {\n return false;\n }\n\n // Guard against a level that is not a key of LEVEL_ORDER, for example \"toString\".\n if (!Object.hasOwn(LEVEL_ORDER, this.settings.level)) {\n return false;\n }\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[this.settings.level];\n }\n\n /**\n * Prints a styled log line if the level clears the console threshold.\n * @param namespace Logger namespace, shown in the prefix.\n * @param level Severity level of the record.\n * @param message Primary log message.\n * @param payload Caller payload. The sink prints a sanitized copy.\n * @param error Error to print before the payload.\n */\n write(\n namespace: string,\n level: LogLevel,\n message: string,\n payload?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.accepts(level)) {\n return;\n }\n // Guard against a missing console. Some worker realms don't define it.\n if (typeof console === \"undefined\") {\n return;\n }\n\n // Guard against a loop: a host console wrapper can call the logger, which would print again.\n // The console capture also records inside this scope, and its line is already in devtools.\n if (isLibraryConsole()) {\n return;\n }\n\n // Pass the namespace as a %s argument, so a %o or %c in the namespace prints as text.\n // The last %c resets the style, so the message prints in the default style.\n const prefix = `%c[%s]%c[${level}]%c`;\n const { styles } = this.settings;\n const method = METHOD[level];\n\n // A host can replace console methods with ones that throw. The guard keeps that error\n // from breaking the caller's log call.\n this.diagnostics.guard(\n \"handler.threw\",\n `The library could not print to console.${method}.`,\n () => {\n const details: unknown[] = [];\n\n if (error !== undefined) {\n details.push(error);\n }\n\n // Devtools keeps a reference to every logged object. A copy releases the caller's object.\n if (payload !== undefined) {\n details.push(sanitize(payload, this.limits, this.diagnostics));\n }\n\n // The console capture skips calls in this scope, so it doesn't record a mirrored line.\n runAsLibraryConsole(() => {\n console[method](\n prefix,\n styles.namespace,\n namespace,\n styles[level],\n \"\",\n message,\n ...details,\n );\n });\n },\n );\n }\n}\n","// src/utils/sequence.ts\n//\n// Generates monotonic sequence numbers that order each context's records. Timestamps can't\n// order records, because a clock can step and two records can share a millisecond. Each\n// context has its own counter, because a shared counter shows gaps and a gap looks like a\n// lost record. The counter never resets, because a reset would repeat numbers in one context.\n\n/** Monotonic sequence counter establishing total record ordering within an execution context. */\nexport class Sequence {\n /** Last emitted sequence counter value. */\n private value = 0;\n\n /**\n * Increments and returns the next monotonic sequence number starting at 1.\n * @returns Next sequence number.\n */\n next(): number {\n return ++this.value;\n }\n}\n","// src/utils/tracing.ts\n//\n// Manages ambient distributed trace contexts, OpenTelemetry span integration, and W3C\n// traceparent headers. Consecutive records share one trace id, because a new trace id for\n// every record would give each trace only one span.\n\nimport {\n SPAN_ID_BYTES,\n TRACE_FLAGS_MASK,\n TRACE_FLAGS_SAMPLED,\n TRACE_ID_BYTES,\n TRACE_MAX_AGE_MS,\n TRACEPARENT_HEADER,\n TRACEPARENT_VERSION,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { OtelApi, OtelLoader, OtelSpanContext } from \"../models/config\";\nimport { randomHex } from \"./identity\";\n\n/** The W3C format fixes these hex widths. A span context with any other width is unusable. */\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\n/** Matches a digit that isn't zero. A span that hasn't started reports an all-zero id. */\nconst NON_ZERO = /[1-9a-f]/;\n\n/**\n * Checks whether a span context can carry correlation. Replaces isSpanContextValid from the\n * peer package, which isn't available when the peer isn't installed.\n * @param context The span context reported by the host.\n * @returns True if both ids have the W3C width and neither is all zeros.\n */\nfunction isUsableSpanContext(context: OtelSpanContext): boolean {\n return (\n TRACE_ID_PATTERN.test(context.traceId) &&\n NON_ZERO.test(context.traceId) &&\n SPAN_ID_PATTERN.test(context.spanId) &&\n NON_ZERO.test(context.spanId)\n );\n}\n\n/** W3C trace context fields attached to log records and network headers. */\nexport interface TraceContext {\n /** Hexadecimal 32-character W3C trace identifier. */\n traceId: string;\n /** Hexadecimal 16-character W3C span identifier. */\n spanId: string;\n /** Bitfield byte containing W3C trace flags. */\n traceFlags: number;\n}\n\n/** Why the ambient trace context rotated. */\nexport type RotateReason = \"start\" | \"interaction\" | \"navigation\" | \"explicit\" | \"maxAge\";\n\n/** An ambient trace that ended. Its root span covers it. */\nexport interface EndedTrace {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the root span. */\n spanId: string;\n /** Why the trace started. */\n reason: RotateReason;\n /** Start time in epoch milliseconds. */\n startedAt: number;\n /** End time in epoch milliseconds. */\n endedAt: number;\n}\n\n/** The client span that a traceparent header names. */\nexport interface ClientSpan {\n /** Trace ID. */\n traceId: string;\n /** Span ID of the client span. */\n spanId: string;\n /** Span ID of the trace's root span. */\n parentSpanId: string;\n}\n\n/** One request's headers, and the client span they name. */\nexport interface RequestTrace {\n /** Header map containing traceparent. */\n headers: Record<string, string>;\n /** The request's client span. Undefined when the library records no span for it. */\n span?: ClientSpan;\n}\n\n/** The runtime's span decisions. */\nexport interface SpanHooks {\n /**\n * Checks whether the library records spans.\n * @returns True when there is a traces endpoint.\n */\n enabled(): boolean;\n /**\n * Checks whether sampling keeps a trace's spans.\n * @param traceId Trace ID.\n * @returns True if the library sends the trace's spans.\n */\n keeps(traceId: string): boolean;\n /**\n * Receives an ambient trace that ended.\n * @param ended The trace.\n */\n onEnd(ended: EndedTrace): void;\n}\n\n/** Internal trace context tracking creation timestamp for expiration. */\ninterface AmbientTrace extends TraceContext {\n /** Creation timestamp in epoch milliseconds. */\n startedAt: number;\n /** Why the trace started. */\n reason: RotateReason;\n /** True once the root span has ended. It ends only once. */\n ended: boolean;\n}\n\n/**\n * Generates a random 32-character hex string in the W3C trace ID format. Use it to start\n * your own trace. The backend drops an id with the wrong width without reporting an error.\n * @returns 32-character hexadecimal trace ID.\n */\nexport function newTraceId(): string {\n return randomHex(TRACE_ID_BYTES);\n}\n\n/**\n * Generates a random 16-character hex string conforming to W3C span ID format.\n * @returns 16-character hexadecimal span ID.\n */\nexport function newSpanId(): string {\n return randomHex(SPAN_ID_BYTES);\n}\n\n/**\n * Creates a new AmbientTrace with the sampled trace flag set. The flag is always set, because\n * sampling runs before the library builds the record.\n * @param reason Why the trace starts.\n * @returns The initialized AmbientTrace.\n */\nfunction mintAmbient(reason: RotateReason): AmbientTrace {\n return {\n traceId: newTraceId(),\n spanId: newSpanId(),\n traceFlags: TRACE_FLAGS_SAMPLED,\n startedAt: Date.now(),\n reason,\n ended: false,\n };\n}\n\n/**\n * Formats a W3C traceparent value.\n * @param traceId Trace ID.\n * @param spanId The caller's span ID.\n * @param traceFlags Trace flags.\n * @returns The traceparent value.\n */\nfunction traceparent(traceId: string, spanId: string, traceFlags: number): string {\n // Mask the trace flags to a 2-digit hex byte, as the W3C specification requires.\n // trace-flags is a bitfield, not a boolean, and a fixed 00 or 01 would discard upstream flags.\n const flags = (traceFlags & TRACE_FLAGS_MASK).toString(16).padStart(2, \"0\");\n return `${TRACEPARENT_VERSION}-${traceId}-${spanId}-${flags}`;\n}\n\n/**\n * Creates a defensive copy of a TraceContext from an AmbientTrace.\n * @param ambient Source ambient trace object.\n * @returns Defensive copy of TraceContext.\n */\nfunction toTraceContext(ambient: AmbientTrace): TraceContext {\n return {\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n traceFlags: ambient.traceFlags,\n };\n}\n\n/** Manages ambient distributed trace contexts and resolves active OpenTelemetry spans. */\nexport class TraceEngine {\n /**\n * The active ambient trace context. This state lives on the instance, not the module,\n * because two runtimes in one document must not share a trace id.\n */\n private ambient: AmbientTrace = mintAmbient(\"start\");\n\n /** The optional peer, once loaded. Undefined while it loads or when it is absent. */\n private otel: OtelApi | undefined;\n\n /**\n * @param diagnostics Diagnostics reporter.\n * @param maxAgeMs Maximum lifetime of an un-rotated ambient trace in milliseconds.\n * @param load Loader for the OpenTelemetry API. If it isn't set, OTel is off.\n * Do not import the peer by name, because the Vite dev server fails if the peer isn't\n * installed.\n * @param spans The runtime's span decisions. Without them, the library records no span.\n */\n constructor(\n private readonly diagnostics: Diagnostics,\n private readonly maxAgeMs = TRACE_MAX_AGE_MS,\n private readonly load?: OtelLoader,\n private readonly spans?: SpanHooks,\n ) {}\n\n /**\n * Loads the OpenTelemetry API. Until the load completes, records use the ambient trace.\n * If there is no loader or the load fails, all records use the ambient trace.\n * @returns A promise that resolves when the attempt settles.\n */\n async loadOtel(): Promise<void> {\n if (!this.load) {\n return;\n }\n\n try {\n this.otel = await this.load();\n } catch (error) {\n this.diagnostics.report(\n \"trace.otel_failed\",\n \"The library could not load @opentelemetry/api. Records use the trace ids of the library.\",\n undefined,\n error,\n );\n }\n }\n\n /**\n * Resolves trace context, prioritizing active OpenTelemetry spans over the ambient trace.\n * @returns Active TraceContext.\n */\n resolve(): TraceContext {\n return this.activeSpanContext() ?? this.ambientContext();\n }\n\n /**\n * Reads the ambient trace, rotating it first if it is too old.\n * @returns The ambient TraceContext.\n */\n private ambientContext(): TraceContext {\n // Rotate the ambient trace once it is older than maxAgeMs. This is checked on read, not on\n // a timer, because a timer would keep this instance alive for the life of the document.\n if (Date.now() - this.ambient.startedAt > this.maxAgeMs) {\n this.rotate(\"maxAge\");\n }\n return toTraceContext(this.ambient);\n }\n\n /**\n * Reads the host's active span, if the peer module loaded and a span is running.\n * @returns The active span's trace context, or undefined.\n */\n private activeSpanContext(): TraceContext | undefined {\n const otel = this.otel;\n if (!otel) {\n return undefined;\n }\n\n return this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not read the active OpenTelemetry span.\",\n (): TraceContext | undefined => {\n const span = otel.trace.getActiveSpan();\n if (span === undefined) {\n return undefined;\n }\n const spanContext = span.spanContext();\n if (!isUsableSpanContext(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n };\n },\n );\n }\n\n /**\n * Rotates the ambient trace context to mark the start of a new logical operation, and ends\n * the old trace's root span.\n * @param reason The event that triggers the rotation.\n * @returns The newly created TraceContext.\n */\n rotate(reason: RotateReason): TraceContext {\n // Set the new trace first, so a record that a hook makes inside onEnd joins the new trace.\n // Otherwise that record would rotate again, and its trace would get no root span.\n const old = this.ambient;\n this.ambient = mintAmbient(reason);\n const next = toTraceContext(this.ambient);\n this.finish(old);\n return next;\n }\n\n /**\n * Ends the ambient trace's root span, once. Later records can still use the trace. The exit\n * flush calls this, because a closing document has no later rotation.\n */\n end(): void {\n this.finish(this.ambient);\n }\n\n /**\n * Ends a trace's root span, once.\n * @param ambient The trace to end.\n */\n private finish(ambient: AmbientTrace): void {\n if (ambient.ended) {\n return;\n }\n\n ambient.ended = true;\n this.spans?.onEnd({\n traceId: ambient.traceId,\n spanId: ambient.spanId,\n reason: ambient.reason,\n startedAt: ambient.startedAt,\n endedAt: Date.now(),\n });\n }\n\n /**\n * Generates W3C traceparent headers with the registered OpenTelemetry propagators. Falls\n * back to the ambient trace when OpenTelemetry provides no traceparent.\n * @returns Header map containing traceparent.\n */\n headers(): Record<string, string> {\n return this.trace(false).headers;\n }\n\n /**\n * Generates the headers for one request from the network capture. With spans on, the\n * traceparent names a new client span of the ambient trace.\n * @returns The headers, and the client span that the library records.\n */\n request(): RequestTrace {\n return this.trace(true);\n }\n\n /**\n * Generates the trace headers.\n * @param client True to name a new client span in the traceparent.\n * @returns The headers, and the client span that the library records.\n */\n private trace(client: boolean): RequestTrace {\n const carrier: Record<string, string> = {};\n const otel = this.otel;\n if (otel) {\n this.diagnostics.guard(\n \"trace.otel_failed\",\n \"The library could not add the OpenTelemetry headers.\",\n () => {\n otel.propagation.inject(otel.context.active(), carrier);\n },\n );\n }\n if (carrier[TRACEPARENT_HEADER]) {\n return { headers: carrier };\n }\n\n // The peer keeps its own spans, so the library records no span for one of the peer's traces.\n const fromOtel = this.activeSpanContext();\n const ctx = fromOtel ?? this.ambientContext();\n const spans = fromOtel ? undefined : this.spans;\n\n if (!spans?.enabled()) {\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, ctx.spanId, ctx.traceFlags);\n return { headers: carrier };\n }\n\n // Clear the sampled flag on a trace that sampling drops, so a downstream service drops its\n // spans too. The whole trace stays or goes.\n const kept = spans.keeps(ctx.traceId);\n const flags = kept ? ctx.traceFlags : ctx.traceFlags & ~TRACE_FLAGS_SAMPLED;\n const spanId = client ? newSpanId() : ctx.spanId;\n carrier[TRACEPARENT_HEADER] = traceparent(ctx.traceId, spanId, flags);\n\n if (!client || !kept) {\n return { headers: carrier };\n }\n\n return { headers: carrier, span: { traceId: ctx.traceId, spanId, parentSpanId: ctx.spanId } };\n }\n}\n","// src/core/breadcrumbs.ts\n//\n// A ring buffer that keeps a bounded, time-ordered trail of recent user and system events.\n// Breadcrumbs are never sent as records of their own. They reach the backend inside the\n// payload of an error record. Nothing in this file throws.\n\nimport { BREADCRUMB_MIN_CAPACITY } from \"../constants\";\n\n/** Category of a breadcrumb event. */\nexport type BreadcrumbCategory =\n | \"log\"\n | \"action\"\n | \"event\"\n | \"click\"\n | \"navigation\"\n | \"http\"\n | \"console\"\n | \"frame\"\n | \"profile\"\n | \"custom\";\n\n/** Short summary of one event, kept so an error record can carry it. */\nexport interface Breadcrumb {\n /** Timestamp in epoch milliseconds. */\n t: number;\n /** Category of the event. */\n category: BreadcrumbCategory;\n /** Human-readable description of the event. */\n message: string;\n /** Optional contextual metadata. */\n data?: Record<string, unknown>;\n}\n\n/** Fixed-size ring buffer that keeps recent breadcrumbs in time order. */\nexport class BreadcrumbBuffer {\n /** The ring's backing array. */\n private buffer: (Breadcrumb | undefined)[];\n\n /** Next write index in the circular buffer. */\n private pointer = 0;\n\n /**\n * True once the pointer has wrapped past the capacity. The pointer alone can't tell an\n * empty ring from one that wrapped back to index 0.\n */\n private filled = false;\n\n /** Maximum number of breadcrumbs the buffer keeps. */\n private capacity: number;\n\n /**\n * @param capacity Maximum number of breadcrumbs. 0 turns the buffer off. Any other value\n * below the minimum size is raised to it.\n */\n constructor(capacity: number) {\n this.capacity = capacity === 0 ? 0 : Math.max(capacity, BREADCRUMB_MIN_CAPACITY);\n this.buffer = new Array<Breadcrumb | undefined>(this.capacity);\n }\n\n /**\n * Changes the capacity, keeping the most recent breadcrumbs that fit.\n * @param capacity New capacity. Pass 0 to drop the stored breadcrumbs and turn the buffer off.\n */\n resize(capacity: number): void {\n const recent = this.snapshot().slice(-capacity);\n this.capacity = capacity;\n this.buffer = new Array<Breadcrumb | undefined>(capacity);\n this.pointer = 0;\n this.filled = false;\n if (capacity) for (const crumb of recent) this.push(crumb);\n }\n\n /**\n * Adds a breadcrumb. When the buffer is full, it overwrites the oldest one.\n * @param crumb Breadcrumb to add.\n */\n push(crumb: Breadcrumb): void {\n if (this.capacity === 0) return;\n this.buffer[this.pointer] = crumb;\n this.pointer = (this.pointer + 1) % this.capacity;\n if (this.pointer === 0) {\n this.filled = true;\n }\n }\n\n /** Removes all breadcrumbs, so a new session never carries the previous user's trail. */\n clear(): void {\n this.buffer.fill(undefined);\n this.pointer = 0;\n this.filled = false;\n }\n\n /**\n * Returns all stored breadcrumbs, oldest to newest.\n * @returns The breadcrumbs in time order.\n */\n snapshot(): Breadcrumb[] {\n const ordered = this.filled\n ? [...this.buffer.slice(this.pointer), ...this.buffer.slice(0, this.pointer)]\n : this.buffer.slice(0, this.pointer);\n return ordered.filter((crumb): crumb is Breadcrumb => crumb !== undefined);\n }\n}\n","// src/core/config.ts\n//\n// Resolves partial consumer options into a validated config, and updates the live config.\n// Two rules to follow here, because breaking either one fails silently:\n// 1. Merge a reconfigure onto the current config, not onto the defaults.\n// 2. Change the resolved object in place, never replace it. Subsystems keep the\n// reference they got at construction.\n// No function in this file throws to the caller.\n\nimport {\n ACTION_ATTRIBUTE_DEFAULT,\n BEACON_LIMIT_BYTES,\n CONFIG_SECTIONS,\n CONSOLE_DEFAULT_LEVEL,\n CONSOLE_DEFAULT_STYLES,\n DEAD_CLICK_MS,\n DEFAULT_CONFIG,\n LEVEL_ORDER,\n PROFILER_PROBE_LIMIT,\n REMOTE_CAPTURE_FLAGS,\n RESOURCE_SLOW_MS,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\n SAMPLING_RATE_FALLBACK,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n SERIALIZER_NAME_ECS,\n SERIALIZER_NAME_OTLP,\n UNDEFAULTED_CONFIG_KEYS,\n UNDEFAULTED_SECTION_KEYS,\n UNKNOWN_SERVICE_NAME,\n} from \"../constants\";\nimport type {\n BatchingOptions,\n BusOptions,\n CaptureOptions,\n CapturedConsoleMethod,\n ConsoleOption,\n ConsoleStyles,\n JourneyOptions,\n LimitOptions,\n ObservabilityConfig,\n ResolvedConfig,\n ResolvedConsole,\n RetentionOptions,\n SamplingOptions,\n SerializerChoice,\n} from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { CapturePlugin } from \"../models/plugin\";\nimport type { LogSerializer } from \"../models/serializer\";\nimport { isObject } from \"../utils/guards\";\nimport { recordedUrl } from \"../utils/platform\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Level names in severity order. */\nconst LEVEL_NAMES = Object.keys(LEVEL_ORDER) as readonly LogLevel[];\n\n/** Accepted values for each choice option. */\nconst COMPRESSION_VALUES = [\"gzip\", \"none\"] as const;\nconst CREDENTIALS_VALUES = [\"omit\", \"same-origin\", \"include\"] as const;\nconst STORAGE_VALUES = [\"auto\", \"indexeddb\", \"localstorage\", \"memory\", \"none\"] as const;\nconst IDENTITY_VALUES = [\"storage\", \"memory\"] as const;\nconst BUS_MODE_VALUES = [\"auto\", \"sender\", \"forwarder\", \"off\"] as const;\nconst OPENFIN_ROLE_VALUES = [\"auto\", \"provider\", \"client\"] as const;\nconst JOURNEY_SCOPE_VALUES = [\"auto\", \"context\", \"tab\", \"origin\"] as const;\nconst CONSOLE_METHOD_VALUES = [\"error\", \"warn\", \"info\", \"log\"] as const;\nconst RETENTION_MODE_VALUES = [\"limited\", \"until-delivered\"] as const;\n\n/** Lowest and highest value an integer option accepts. */\ntype Range = readonly [min: number, max: number];\n\n/** Accepted range for each batching key. */\nconst BATCHING_RANGES: Record<keyof BatchingOptions, Range> = {\n logFlushIntervalMs: [100, 60_000],\n logBatchSize: [1, 1000],\n metricFlushIntervalMs: [100, 60_000],\n metricBatchSize: [1, 1000],\n};\n\n/** Accepted range for each numeric retention key. */\nconst RETENTION_RANGES: Record<Exclude<keyof RetentionOptions, \"mode\">, Range> = {\n maxBatches: [1, 5000],\n maxAgeMs: [60_000, 7 * 24 * 60 * 60 * 1000],\n maxAttempts: [1, 20],\n};\n\n/**\n * Accepted range for each record limit. maxRecordBytes tops out at one beacon, and the body\n * and error fields don't count toward it. An exit batch larger than one beacon goes to the\n * emergency queue.\n */\nconst LIMIT_RANGES: Record<keyof LimitOptions, Range> = {\n maxBodyChars: [256, 65_536],\n maxAttributeChars: [256, 65_536],\n maxAttributeCount: [1, 1024],\n maxStackChars: [256, 65_536],\n maxDepth: [1, 16],\n maxArrayLength: [1, 10_000],\n maxNodes: [100, 100_000],\n maxRecordBytes: [1024, BEACON_LIMIT_BYTES],\n};\n\n/** Accepted range for journey.maxAgeMs. */\nconst JOURNEY_AGE_RANGE: Range = [60_000, 24 * 60 * 60 * 1000];\n\n/** Range for a duration. The maximum is the largest delay a browser timer accepts. */\nconst DURATION_RANGE: Range = [0, 2_147_483_647];\n\n/** Range for a count. Zero turns the limit off. */\nconst COUNT_RANGE: Range = [0, Number.MAX_SAFE_INTEGER];\n\n/** Range for a count that must be at least 1. */\nconst POSITIVE_RANGE: Range = [1, Number.MAX_SAFE_INTEGER];\n\n/** Range for the rage click and dead click detection waits. */\nconst CLICK_WAIT_RANGE: Range = [100, 10_000];\n\n/** The keys of a policy section whose values are numbers. */\ntype NumberKeys<T> = { [K in keyof T]: T[K] extends number ? K : never }[keyof T];\n\n/** The policy sections resolvePolicy() checks. */\ntype PolicySection =\n | \"capturePolicy\"\n | \"metadata\"\n | \"persistence\"\n | \"diagnostics\"\n | \"correlation\"\n | \"metrics\"\n | \"buffering\"\n | \"delivery\"\n | \"debugBuffer\"\n | \"profiler\"\n | \"replay\";\n\n/**\n * Reads one policy key the generic checks can't handle, for example a list.\n * @param key Full config key for the diagnostic message.\n * @param value The value the consumer passed.\n * @param fallback The current value.\n * @param diagnostics Diagnostics reporter.\n * @returns The value to use.\n */\ntype CustomResolver = (\n key: string,\n value: unknown,\n fallback: unknown,\n diagnostics: Diagnostics,\n) => unknown;\n\n/** True for an array of strings. */\nconst isStrings = (value: unknown): boolean =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n\n/** True for an array of functions. */\nconst isFunctions = (value: unknown): boolean =>\n Array.isArray(value) && value.every((entry) => typeof entry === \"function\");\n\n/** True for a function or null. */\nconst isFunctionOrNull = (value: unknown): boolean => value === null || typeof value === \"function\";\n\n/** True for request headers: an object of strings, a function, or null. */\nconst isHeaders = (value: unknown): boolean =>\n isFunctionOrNull(value) ||\n (isRecord(value) && Object.values(value as object).every((entry) => typeof entry === \"string\"));\n\n/** True for an object that isn't an array. */\nconst isRecord = (value: unknown): boolean =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Builds the resolver for a key whose value isn't a number, a boolean or a string.\n * @param test Checks the value.\n * @param expected What the report says was expected.\n * @returns The resolver. A value that fails the test is ignored, and the current one stays.\n */\nfunction keepKind(test: (value: unknown) => boolean, expected: string): CustomResolver {\n return (key, value, fallback, diagnostics) => {\n if (value === undefined) {\n return fallback;\n }\n\n // null is a valid value for some keys, and it replaces the current value.\n if (test(value)) {\n return value;\n }\n\n reportInvalid(diagnostics, key, expected, value, \"the current value\");\n return fallback;\n };\n}\n\n/** Rules for one policy section. Every number key must have a range. */\ninterface PolicyRules<T> {\n /** Accepted range for each number key. */\n ranges: Record<NumberKeys<T>, Range>;\n /** Accepted values for each choice key. */\n choices?: Partial<Record<keyof T, readonly string[]>>;\n /** Resolver for each key with any other value type. */\n custom?: Partial<Record<keyof T, CustomResolver>>;\n}\n\n/** Rules for every policy section. A new number key without a range won't compile. */\nconst POLICY_RULES: { [K in PolicySection]: PolicyRules<ResolvedConfig[K]> } = {\n capturePolicy: {\n ranges: {\n // A larger capacity fails as an invalid array allocation.\n breadcrumbs: [0, 1_000_000],\n errorDedupeMs: DURATION_RANGE,\n maxErrorSignatures: COUNT_RANGE,\n errorsPerWindow: COUNT_RANGE,\n consolePerWindow: COUNT_RANGE,\n longFramesPerWindow: COUNT_RANGE,\n webSocketPerWindow: COUNT_RANGE,\n reportsPerWindow: COUNT_RANGE,\n resourcesPerWindow: COUNT_RANGE,\n lifecyclePerWindow: COUNT_RANGE,\n windowMs: DURATION_RANGE,\n errorCeiling: COUNT_RANGE,\n },\n },\n metadata: { ranges: {} },\n persistence: { ranges: {} },\n diagnostics: {\n ranges: { throttleMs: DURATION_RANGE },\n custom: { records: resolveDiagnosticRecords },\n },\n correlation: {\n ranges: {\n sessionIdleMs: DURATION_RANGE,\n sessionTouchMs: DURATION_RANGE,\n traceMaxAgeMs: DURATION_RANGE,\n },\n },\n metrics: {\n ranges: {\n maxSeries: COUNT_RANGE,\n maxInstruments: COUNT_RANGE,\n maxHistogramBoundaries: COUNT_RANGE,\n },\n },\n buffering: {\n ranges: { maxPendingRecords: COUNT_RANGE, maxPendingBytes: COUNT_RANGE },\n choices: { overflow: [\"drop-oldest\", \"drop-newest\", \"persist\"] },\n },\n delivery: {\n ranges: {\n requestTimeoutMs: [1, DURATION_RANGE[1]],\n maxConcurrentRequests: POSITIVE_RANGE,\n retryBaseDelayMs: DURATION_RANGE,\n retryMaxDelayMs: DURATION_RANGE,\n retryIdleDelayMs: DURATION_RANGE,\n batchesPerDrain: POSITIVE_RANGE,\n },\n choices: { priority: [\"low\", \"auto\", \"high\"] },\n },\n debugBuffer: { ranges: { maxRecords: [1, 10_000], maxAgeMs: DURATION_RANGE } },\n profiler: { ranges: { flushIntervalMs: [1000, 600_000], maxProbes: [1, PROFILER_PROBE_LIMIT] } },\n replay: {\n ranges: {\n bufferMs: [5000, 600_000],\n maxBufferBytes: [100_000, 200_000_000],\n afterErrorMs: [0, 600_000],\n uploadsPerWindow: COUNT_RANGE,\n batchSize: [1, 10_000],\n batchBytes: [10_000, 10_000_000],\n flushIntervalMs: [100, 60_000],\n maxQueueBytes: [100_000, 200_000_000],\n maxAttempts: [1, 10],\n },\n choices: { mode: [\"onError\"] },\n custom: {\n maskSelectors: keepKind(isStrings, \"a list of strings\"),\n blockSelectors: keepKind(isStrings, \"a list of strings\"),\n loader: keepKind(isFunctionOrNull, \"a function or null\"),\n onSegment: keepKind(isFunctionOrNull, \"a function or null\"),\n headers: keepKind(isHeaders, \"an object of strings, a function or null\"),\n plugins: keepKind(isFunctions, \"a list of functions\"),\n recordOptions: keepKind(isRecord, \"an object\"),\n },\n },\n};\n\n/** The boolean keys of the capture section. */\nconst CAPTURE_FLAG_KEYS = [\n \"errors\",\n \"rejections\",\n \"resourceErrors\",\n \"fetch\",\n \"xhr\",\n \"httpMetrics\",\n \"navigation\",\n \"webVitals\",\n \"longFrames\",\n \"fullUrls\",\n \"webSocket\",\n \"uncleanExit\",\n \"userTiming\",\n \"serverTiming\",\n \"reports\",\n \"lifecycle\",\n] as const;\n\n/** The origin of a sandboxed frame that lacks allow-same-origin. */\nconst SANDBOX_ORIGIN = \"null\";\n\n/** How each expected value reads in a config.invalid message. */\nconst LEVEL_EXPECTED = `a level name: ${listOf(LEVEL_NAMES)}`;\nconst CONSOLE_CAPTURE_EXPECTED = `true, false or a list of ${listOf(CONSOLE_METHOD_VALUES)}`;\nconst PATTERN_LIST_EXPECTED = \"a list of strings and RegExp patterns\";\nconst TARGET_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://api.example\" and RegExp patterns';\nconst ORIGIN_LIST_EXPECTED =\n 'a list of origin URLs such as \"https://app.example\". For a sandboxed frame, set bus.mode: \"sender\" in the frame';\nconst STRING_LIST_EXPECTED = \"a list of strings\";\nconst DIAGNOSTIC_RECORDS_EXPECTED = \"true, false or a list of diagnostic codes\";\n\n/** Function form of the headers option. */\ntype HeadersFunction = () => Record<string, string> | Promise<Record<string, string>>;\n\n/** The headers option. */\ntype HeadersOption = ObservabilityConfig[\"headers\"];\n\n/**\n * Formats a list of values as text, for example `\"a\", \"b\" or \"c\"`.\n * @param values Values to list.\n * @returns The text.\n */\nfunction listOf(values: readonly string[]): string {\n const quoted = values.map((value) => `\"${value}\"`);\n return `${quoted.slice(0, -1).join(\", \")} or ${quoted[quoted.length - 1]}`;\n}\n\n/**\n * Describes a config value for a message. Never prints an object or a function.\n * @param value The value the consumer passed.\n * @returns Short text for the value.\n */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"string\") {\n return `\"${value}\"`;\n }\n\n if (typeof value === \"function\") {\n return \"a function\";\n }\n\n if (typeof value === \"object\" && value !== null) {\n return \"an object\";\n }\n\n return String(value);\n}\n\n/**\n * Reports a value the option doesn't accept.\n * @param diagnostics Diagnostics reporter.\n * @param key Config key, for example `bus.mode`.\n * @param expected Describes the accepted values.\n * @param value The value the consumer passed.\n * @param kept Describes the value that stays in effect.\n */\nfunction reportInvalid(\n diagnostics: Diagnostics,\n key: string,\n expected: string,\n value: unknown,\n kept: string,\n): void {\n diagnostics.report(\n \"config.invalid\",\n `${key} must be ${expected}. The value is ${describeValue(value)}. The library keeps ${kept}.`,\n );\n}\n\n/**\n * Reads an option that takes one value from a fixed list.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param accepted Accepted values.\n * @param fallback The current value.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value isn't accepted.\n */\nfunction resolveChoice<T extends string>(\n key: string,\n value: unknown,\n accepted: readonly T[],\n fallback: T,\n diagnostics: Diagnostics,\n): T {\n if (value === undefined) {\n return fallback;\n }\n\n const match = accepted.find((entry) => entry === value);\n if (match !== undefined) {\n return match;\n }\n\n reportInvalid(diagnostics, key, listOf(accepted), value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads a boolean option.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current value.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value isn't a boolean.\n */\nfunction resolveBoolean(\n key: string,\n value: unknown,\n fallback: boolean,\n diagnostics: Diagnostics,\n): boolean {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"true or false\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that takes a finite number, 0 or more.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current value.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value isn't accepted.\n */\nfunction resolveNonNegative(\n key: string,\n value: unknown,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"a finite number of 0 or more\", value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads an option that takes an integer in a range.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param range Lowest and highest accepted value.\n * @param fallback The current value.\n * @param diagnostics Diagnostics reporter.\n * @returns The value, or the fallback when the value isn't accepted.\n */\nfunction resolveInteger(\n key: string,\n value: unknown,\n range: Range,\n fallback: number,\n diagnostics: Diagnostics,\n): number {\n if (value === undefined) {\n return fallback;\n }\n\n const [min, max] = range;\n if (typeof value === \"number\" && Number.isInteger(value) && value >= min && value <= max) {\n return value;\n }\n\n const expected = `an integer from ${String(min)} to ${String(max)}`;\n reportInvalid(diagnostics, key, expected, value, String(fallback));\n return fallback;\n}\n\n/**\n * Checks the logger cache limit. An invalid value keeps the current limit, including null.\n * @param value The limit the app supplied.\n * @param previous The current limit. Null allows an unlimited cache.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid limit, or the current one.\n */\nfunction resolveCacheLimit(\n value: unknown,\n previous: number | null,\n diagnostics: Diagnostics,\n): number | null {\n if (value === undefined) return previous;\n if (value === null) return null;\n if (typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0) return value;\n reportInvalid(\n diagnostics,\n \"loggerCache.maxEntries\",\n \"a nonnegative safe integer or null\",\n value,\n String(previous),\n );\n return previous;\n}\n\n/**\n * Merges and checks a section of integer options. The keys come only from `ranges`.\n * @param section Section name, for example `batching`.\n * @param input The values the consumer passed.\n * @param base The current values.\n * @param ranges Accepted range for each key.\n * @param diagnostics Diagnostics reporter.\n * @returns The value for every key in `ranges`.\n */\nfunction resolveRanges<K extends string>(\n section: string,\n input: Partial<Record<NoInfer<K>, unknown>> | undefined,\n base: Record<NoInfer<K>, number>,\n ranges: Record<K, Range>,\n diagnostics: Diagnostics,\n): Record<K, number> {\n const given: Partial<Record<K, unknown>> = input ?? {};\n const keys = Object.keys(ranges) as K[];\n\n return Object.fromEntries(\n keys.map((key): [K, number] => [\n key,\n resolveInteger(`${section}.${key}`, given[key], ranges[key], base[key], diagnostics),\n ]),\n ) as Record<K, number>;\n}\n\n/**\n * Reads a level name, ignoring case.\n * @param value The value the consumer passed.\n * @returns The level, or undefined when the value isn't a level name.\n */\nfunction toLevel(value: unknown): LogLevel | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const upper = value.toUpperCase();\n return LEVEL_NAMES.find((level) => level === upper);\n}\n\n/**\n * Reads a level option. Without this check, an unknown level silently drops every record.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current level.\n * @param diagnostics Diagnostics reporter.\n * @returns The level, or the fallback when the value isn't a level name.\n */\nfunction resolveLevel(\n key: string,\n value: unknown,\n fallback: LogLevel,\n diagnostics: Diagnostics,\n): LogLevel {\n if (value === undefined) {\n return fallback;\n }\n\n const level = toLevel(value);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(diagnostics, key, LEVEL_EXPECTED, value, `\"${fallback}\"`);\n return fallback;\n}\n\n/**\n * Reads the minLevels option. Keeps every valid prefix and reports the rest. A new map\n * replaces the current one.\n * @param value The value the consumer passed.\n * @param fallback The current levels.\n * @param diagnostics Diagnostics reporter.\n * @returns The level for each namespace prefix.\n */\nfunction resolveMinLevels(\n value: unknown,\n fallback: Record<string, LogLevel>,\n diagnostics: Diagnostics,\n): Record<string, LogLevel> {\n if (value === undefined) {\n return fallback;\n }\n\n if (!isObject(value)) {\n reportInvalid(diagnostics, \"minLevels\", \"an object of level names\", value, \"the current value\");\n return fallback;\n }\n\n const levels: [string, LogLevel][] = [];\n for (const [prefix, raw] of Object.entries(value)) {\n const level = toLevel(raw);\n if (prefix !== \"\" && level !== undefined) {\n levels.push([prefix, level]);\n } else {\n reportInvalid(diagnostics, `minLevels[\"${prefix}\"]`, LEVEL_EXPECTED, raw, \"minLevel for it\");\n }\n }\n\n // fromEntries creates own properties, so a \"__proto__\" key can't change the prototype.\n return Object.fromEntries(levels);\n}\n\n/**\n * Reads a list option. Keeps every accepted entry and reports the rest.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current list.\n * @param expected Describes the accepted list.\n * @param accept Converts an entry, or returns undefined to reject it.\n * @param diagnostics Diagnostics reporter.\n * @returns The accepted entries, or the fallback when the value isn't a list.\n */\nfunction resolveList<T>(\n key: string,\n value: unknown,\n fallback: T[],\n expected: string,\n accept: (entry: unknown) => T | undefined,\n diagnostics: Diagnostics,\n): T[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(diagnostics, key, expected, value, \"the current list\");\n return fallback;\n }\n\n const kept: T[] = [];\n const entries: unknown[] = value;\n\n for (const entry of entries) {\n const accepted = accept(entry);\n if (accepted === undefined) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the ${key} entry ${describeValue(entry)}. ${key} must be ${expected}.`,\n );\n continue;\n }\n kept.push(accepted);\n }\n\n return kept;\n}\n\n/**\n * Accepts a function entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toProcessor(entry: unknown): ResolvedConfig[\"processors\"][number] | undefined {\n return typeof entry === \"function\" ? (entry as ResolvedConfig[\"processors\"][number]) : undefined;\n}\n\n/**\n * Accepts a capture plugin entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toPlugin(entry: unknown): CapturePlugin | undefined {\n const valid =\n isObject(entry) &&\n typeof entry.name === \"string\" &&\n entry.name !== \"\" &&\n typeof entry.install === \"function\" &&\n typeof entry.uninstall === \"function\";\n\n return valid ? (entry as unknown as CapturePlugin) : undefined;\n}\n\n/**\n * Reads diagnostics.records. A list keeps its string entries and reports the rest.\n * @param key Full config key.\n * @param value The value the consumer passed.\n * @param fallback The current value.\n * @param diagnostics Diagnostics reporter.\n * @returns True, false or the list of codes.\n */\nfunction resolveDiagnosticRecords(\n key: string,\n value: unknown,\n fallback: unknown,\n diagnostics: Diagnostics,\n): unknown {\n if (value === undefined || typeof value === \"boolean\") {\n return value ?? fallback;\n }\n\n if (Array.isArray(value)) {\n return resolveList(key, value, [], DIAGNOSTIC_RECORDS_EXPECTED, toStringEntry, diagnostics);\n }\n\n reportInvalid(diagnostics, key, DIAGNOSTIC_RECORDS_EXPECTED, value, \"the current value\");\n return fallback;\n}\n\n/**\n * Accepts a string entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toStringEntry(entry: unknown): string | undefined {\n return typeof entry === \"string\" ? entry : undefined;\n}\n\n/**\n * Accepts a string or a RegExp entry.\n * @param entry List entry.\n * @returns The entry, or undefined.\n */\nfunction toPattern(entry: unknown): string | RegExp | undefined {\n return typeof entry === \"string\" || entry instanceof RegExp ? entry : undefined;\n}\n\n/**\n * Accepts a console method name.\n * @param entry List entry.\n * @returns The method, or undefined.\n */\nfunction toConsoleMethod(entry: unknown): CapturedConsoleMethod | undefined {\n return CONSOLE_METHOD_VALUES.find((method) => method === entry);\n}\n\n/**\n * Reads an origin entry. A URL with a path is reduced to its origin.\n * @param entry List entry.\n * @returns The origin, or undefined. resolveList reports the rejected entry.\n */\nfunction toOrigin(entry: unknown): string | undefined {\n if (typeof entry !== \"string\") {\n return undefined;\n }\n\n // Every sandboxed and data: document has the opaque origin \"null\", so a single entry\n // would trust all of them.\n try {\n const { origin } = new URL(entry);\n return origin === SANDBOX_ORIGIN ? undefined : origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads a trace header target. A string is reduced to its origin, and a RegExp is kept as is.\n * @param entry List entry.\n * @returns The target, or undefined. resolveList reports the rejected entry.\n */\nfunction toTarget(entry: unknown): string | RegExp | undefined {\n return entry instanceof RegExp ? entry : toOrigin(entry);\n}\n\n/**\n * Checks whether a value is an object of string values.\n * @param value Value to test.\n * @returns True for an object whose values are all strings.\n */\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n if (!isObject(value)) {\n return false;\n }\n\n const values: unknown[] = Object.values(value);\n return values.every((entry) => typeof entry === \"string\");\n}\n\n/**\n * Reads the headers option.\n * @param value The value the consumer passed.\n * @param fallback The current headers.\n * @param diagnostics Diagnostics reporter.\n * @returns The headers, undefined for an explicit undefined, or the fallback for a bad value.\n */\nfunction resolveHeaders(\n value: unknown,\n fallback: HeadersOption,\n diagnostics: Diagnostics,\n): HeadersOption {\n // An explicit undefined clears the headers, so the old token isn't sent after logout.\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value === \"function\") {\n return value as HeadersFunction;\n }\n\n if (isStringRecord(value)) {\n return value;\n }\n\n // The value can hold a token, and this message can become a record.\n diagnostics.report(\n \"config.invalid\",\n \"headers must be an object of strings or a function. The library keeps the current headers.\",\n );\n return fallback;\n}\n\n/**\n * Checks if a value implements the LogSerializer interface.\n * @param value Value to check.\n * @returns True if value implements serialize.\n */\nfunction isSerializer(value: unknown): value is LogSerializer {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const serialize: unknown = Reflect.get(value, \"serialize\");\n return typeof serialize === \"function\";\n}\n\n/**\n * Validates the serializer option. A name stays a name here, because the transport picks\n * the implementation.\n * @param requested Serializer name or custom serializer implementation.\n * @param previous The current serializer option.\n * @param diagnostics Diagnostics reporter.\n * @returns Valid serializer option.\n */\nfunction resolveSerializer(\n requested: unknown,\n previous: SerializerChoice | undefined,\n diagnostics: Diagnostics,\n): SerializerChoice {\n if (requested === undefined) {\n return previous ?? SERIALIZER_NAME_OTLP;\n }\n if (requested === SERIALIZER_NAME_OTLP || requested === SERIALIZER_NAME_ECS) {\n return requested;\n }\n if (isSerializer(requested)) {\n return requested;\n }\n\n diagnostics.report(\n \"config.invalid\",\n `serializer must be \"${SERIALIZER_NAME_OTLP}\", \"${SERIALIZER_NAME_ECS}\" or an implementation. The library uses \"${SERIALIZER_NAME_OTLP}\".`,\n );\n return SERIALIZER_NAME_OTLP;\n}\n\n/** The style keys the console option accepts. */\nconst CONSOLE_STYLE_KEYS = new Set(Object.keys(CONSOLE_DEFAULT_STYLES));\n\n/**\n * Keeps the valid entries of a console styles object and reports every entry it drops.\n * @param styles The styles the consumer passed.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid styles.\n */\nfunction validStyles(styles: ConsoleStyles | undefined, diagnostics: Diagnostics): ConsoleStyles {\n const valid: Record<string, string> = {};\n const entries: [string, unknown][] = Object.entries(styles ?? {});\n\n for (const [key, value] of entries) {\n if (!CONSOLE_STYLE_KEYS.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown console.styles key \"${key}\". Check the spelling.`,\n );\n continue;\n }\n\n if (typeof value !== \"string\") {\n diagnostics.report(\n \"config.invalid\",\n `console.styles.${key} must be a string. The library keeps the current style.`,\n );\n continue;\n }\n\n valid[key] = value;\n }\n\n return valid;\n}\n\n/**\n * Reads the level from the console option's object form.\n * @param requested The level the consumer passed.\n * @param previous The current console level. Null means the console is off.\n * @param diagnostics Diagnostics reporter.\n * @returns The level. An unknown level keeps the current one.\n */\nfunction resolveConsoleLevel(\n requested: unknown,\n previous: LogLevel | null,\n diagnostics: Diagnostics,\n): LogLevel | null {\n if (requested === undefined) {\n return previous ?? CONSOLE_DEFAULT_LEVEL;\n }\n\n const level = toLevel(requested);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(\n diagnostics,\n \"console.level\",\n LEVEL_EXPECTED,\n requested,\n \"the current console level\",\n );\n return previous;\n}\n\n/**\n * Normalizes the console option into a level and a set of styles.\n * @param requested Consumer console option.\n * @param previous The current console settings.\n * @param diagnostics Diagnostics reporter.\n * @returns Console settings. The level is null when the console is off.\n */\nfunction resolveConsole(\n requested: ConsoleOption | undefined,\n previous: ResolvedConsole,\n diagnostics: Diagnostics,\n): ResolvedConsole {\n if (requested === undefined) {\n return previous;\n }\n if (requested === false) {\n return { level: null, styles: previous.styles };\n }\n if (requested === true) {\n return { level: CONSOLE_DEFAULT_LEVEL, styles: previous.styles };\n }\n if (typeof requested === \"string\") {\n const level = toLevel(requested);\n if (level === undefined) {\n reportInvalid(diagnostics, \"console\", LEVEL_EXPECTED, requested, \"the current console level\");\n return previous;\n }\n\n return { level, styles: previous.styles };\n }\n\n // Guard against null and other values the type doesn't allow.\n if (typeof requested !== \"object\" || (requested as unknown) === null) {\n diagnostics.report(\n \"config.invalid\",\n \"console must be a boolean, a level or an object. The current console settings stay.\",\n );\n return previous;\n }\n\n return {\n level: resolveConsoleLevel(requested.level, previous.level, diagnostics),\n styles: { ...previous.styles, ...validStyles(requested.styles, diagnostics) },\n };\n}\n\n/**\n * Merges and checks the sampling section. resolveConfig checks the rates after the merge.\n * @param input The sampling options the consumer passed.\n * @param base The current sampling options.\n * @param diagnostics Diagnostics reporter.\n * @returns The sampling options.\n */\nfunction resolveSampling(\n input: Partial<SamplingOptions> | undefined,\n base: SamplingOptions,\n diagnostics: Diagnostics,\n): SamplingOptions {\n const given = input ?? {};\n\n return {\n ...base,\n ...given,\n rates: { ...base.rates, ...given.rates },\n alwaysSampleTypes: resolveList(\n \"sampling.alwaysSampleTypes\",\n given.alwaysSampleTypes,\n base.alwaysSampleTypes,\n STRING_LIST_EXPECTED,\n toStringEntry,\n diagnostics,\n ),\n alwaysSampleFrom: resolveLevel(\n \"sampling.alwaysSampleFrom\",\n given.alwaysSampleFrom,\n base.alwaysSampleFrom,\n diagnostics,\n ),\n remote: resolveBoolean(\"sampling.remote\", given.remote, base.remote, diagnostics),\n };\n}\n\n/**\n * Merges and checks the bus section.\n * @param input The bus options the consumer passed.\n * @param base The current bus options.\n * @param diagnostics Diagnostics reporter.\n * @returns The bus options. Every trusted origin is a bare origin.\n */\nfunction resolveBus(\n input: Partial<BusOptions> | undefined,\n base: BusOptions,\n diagnostics: Diagnostics,\n): BusOptions {\n const given = input ?? {};\n\n return {\n maxTrackedSources: resolveInteger(\n \"bus.maxTrackedSources\",\n given.maxTrackedSources,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxTrackedSources,\n diagnostics,\n ),\n sourcePolicy: resolveChoice(\n \"bus.sourcePolicy\",\n given.sourcePolicy,\n [\"registered\", \"trusted-origin\"],\n base.sourcePolicy,\n diagnostics,\n ),\n validation: resolveChoice(\n \"bus.validation\",\n given.validation,\n [\"strict\", \"envelope\"],\n base.validation,\n diagnostics,\n ),\n maxMessageBytes: resolveInteger(\n \"bus.maxMessageBytes\",\n given.maxMessageBytes,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxMessageBytes,\n diagnostics,\n ),\n maxRecordsPerMessage: resolveInteger(\n \"bus.maxRecordsPerMessage\",\n given.maxRecordsPerMessage,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxRecordsPerMessage,\n diagnostics,\n ),\n maxMessagesPerSecond: resolveInteger(\n \"bus.maxMessagesPerSecond\",\n given.maxMessagesPerSecond,\n [0, Number.MAX_SAFE_INTEGER],\n base.maxMessagesPerSecond,\n diagnostics,\n ),\n mode: resolveChoice(\"bus.mode\", given.mode, BUS_MODE_VALUES, base.mode, diagnostics),\n // Compare origins, not URLs. Otherwise an entry with a path never matches event.origin.\n trustedOrigins: resolveList(\n \"bus.trustedOrigins\",\n given.trustedOrigins,\n base.trustedOrigins,\n ORIGIN_LIST_EXPECTED,\n toOrigin,\n diagnostics,\n ),\n openFinRole: resolveChoice(\n \"bus.openFinRole\",\n given.openFinRole,\n OPENFIN_ROLE_VALUES,\n base.openFinRole,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the journey section.\n * @param input The journey options the consumer passed.\n * @param base The current journey options.\n * @param diagnostics Diagnostics reporter.\n * @returns The journey options.\n */\nfunction resolveJourney(\n input: Partial<JourneyOptions> | undefined,\n base: JourneyOptions,\n diagnostics: Diagnostics,\n): JourneyOptions {\n const given = input ?? {};\n\n return {\n scope: resolveChoice(\n \"journey.scope\",\n given.scope,\n JOURNEY_SCOPE_VALUES,\n base.scope,\n diagnostics,\n ),\n maxAgeMs: resolveInteger(\n \"journey.maxAgeMs\",\n given.maxAgeMs,\n JOURNEY_AGE_RANGE,\n base.maxAgeMs,\n diagnostics,\n ),\n };\n}\n\n/**\n * Merges and checks the retention section.\n * @param input The retention options the consumer passed.\n * @param base The current retention options.\n * @param diagnostics Diagnostics reporter.\n * @returns The retention options.\n */\nfunction resolveRetention(\n input: Partial<RetentionOptions> | undefined,\n base: RetentionOptions,\n diagnostics: Diagnostics,\n): RetentionOptions {\n const given = input ?? {};\n\n return {\n mode: resolveChoice(\n \"retention.mode\",\n given.mode,\n RETENTION_MODE_VALUES,\n base.mode,\n diagnostics,\n ),\n ...resolveRanges(\"retention\", given, base, RETENTION_RANGES, diagnostics),\n };\n}\n\n/**\n * Reads capture.console.\n * @param value The value the consumer passed.\n * @param fallback The current value.\n * @param diagnostics Diagnostics reporter.\n * @returns A boolean, or the accepted method names.\n */\nfunction resolveCaptureConsole(\n value: unknown,\n fallback: boolean | CapturedConsoleMethod[],\n diagnostics: Diagnostics,\n): boolean | CapturedConsoleMethod[] {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n if (!Array.isArray(value)) {\n reportInvalid(\n diagnostics,\n \"capture.console\",\n CONSOLE_CAPTURE_EXPECTED,\n value,\n \"the current value\",\n );\n return fallback;\n }\n\n return resolveList(\n \"capture.console\",\n value,\n [],\n CONSOLE_CAPTURE_EXPECTED,\n toConsoleMethod,\n diagnostics,\n );\n}\n\n/**\n * Merges and checks the capture section.\n * @param input The capture options the consumer passed.\n * @param base The current capture options.\n * @param diagnostics Diagnostics reporter.\n * @returns The capture options.\n */\nfunction resolveCapture(\n input: Partial<CaptureOptions> | undefined,\n base: CaptureOptions,\n diagnostics: Diagnostics,\n): CaptureOptions {\n const given = input ?? {};\n const capture: CaptureOptions = {\n ...base,\n ...given,\n remoteToggles: resolveList(\n \"capture.remoteToggles\",\n given.remoteToggles,\n base.remoteToggles,\n \"a list of capture switch names without privacy controls\",\n (value) => REMOTE_CAPTURE_FLAGS.find((key) => key === value),\n diagnostics,\n ),\n resourceTiming: resolveResourceTiming(given.resourceTiming, base.resourceTiming, diagnostics),\n interactions: resolveInteractions(given.interactions, base.interactions, diagnostics),\n console: resolveCaptureConsole(given.console, base.console, diagnostics),\n longFrameMs: resolveNonNegative(\n \"capture.longFrameMs\",\n given.longFrameMs,\n base.longFrameMs,\n diagnostics,\n ),\n ignoreUrls: resolveList(\n \"capture.ignoreUrls\",\n given.ignoreUrls,\n base.ignoreUrls,\n PATTERN_LIST_EXPECTED,\n toPattern,\n diagnostics,\n ),\n userTimingInclude: resolveList(\n \"capture.userTimingInclude\",\n given.userTimingInclude,\n base.userTimingInclude,\n PATTERN_LIST_EXPECTED,\n toPattern,\n diagnostics,\n ),\n // A string target is an origin, because a substring test would also match a query value\n // or a longer host.\n propagateTraceHeaderTo: resolveList(\n \"capture.propagateTraceHeaderTo\",\n given.propagateTraceHeaderTo,\n base.propagateTraceHeaderTo,\n TARGET_LIST_EXPECTED,\n toTarget,\n diagnostics,\n ),\n plugins: resolveList(\n \"capture.plugins\",\n given.plugins,\n base.plugins,\n \"a list of objects with a name, install() and uninstall()\",\n toPlugin,\n diagnostics,\n ),\n };\n\n for (const key of CAPTURE_FLAG_KEYS) {\n capture[key] = resolveBoolean(`capture.${key}`, given[key], base[key], diagnostics);\n }\n\n return capture;\n}\n\n/** Checks the resource timing settings. An invalid value keeps the current settings. */\nfunction resolveResourceTiming(\n value: unknown,\n base: CaptureOptions[\"resourceTiming\"],\n diagnostics: Diagnostics,\n): CaptureOptions[\"resourceTiming\"] {\n if (value === undefined) {\n return base;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (!isObject(value)) {\n diagnostics.report(\n \"config.invalid\",\n \"capture.resourceTiming must be a boolean or an options object.\",\n );\n return base;\n }\n\n return {\n slowMs: resolveNonNegative(\n \"capture.resourceTiming.slowMs\",\n value.slowMs,\n typeof base === \"object\" ? (base.slowMs ?? RESOURCE_SLOW_MS) : RESOURCE_SLOW_MS,\n diagnostics,\n ),\n };\n}\n\n/**\n * Checks the click settings. An invalid value never turns on text or selector capture.\n * @param value The settings the app supplied.\n * @param base The current settings.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid settings, with invalid values replaced by the current ones.\n */\nfunction resolveInteractions(\n value: CaptureOptions[\"interactions\"] | undefined,\n base: CaptureOptions[\"interactions\"],\n diagnostics: Diagnostics,\n): CaptureOptions[\"interactions\"] {\n if (value === undefined) return base;\n if (typeof value === \"boolean\") return value;\n if (!isObject(value)) {\n diagnostics.report(\n \"config.invalid\",\n \"capture.interactions must be a boolean or an options object.\",\n );\n return base;\n }\n const previous = typeof base === \"object\" ? base : {};\n const ignore = value.ignoreSelector;\n let ignoreSelector = ignore === undefined ? previous.ignoreSelector : ignore;\n if (ignoreSelector !== undefined && ignoreSelector !== null) {\n try {\n if (typeof ignoreSelector !== \"string\") throw new Error(\"Invalid selector\");\n if (typeof document !== \"undefined\") document.createElement(\"div\").matches(ignoreSelector);\n } catch {\n diagnostics.report(\n \"config.invalid\",\n \"capture.interactions.ignoreSelector must be a valid CSS selector or null.\",\n );\n ignoreSelector = previous.ignoreSelector;\n }\n }\n // The name goes into a CSS attribute selector. Letters, digits, hyphens and underscores need\n // no escaping, and any other name keeps the current attribute.\n let actionAttribute = previous.actionAttribute ?? ACTION_ATTRIBUTE_DEFAULT;\n if (value.actionAttribute !== undefined) {\n if (typeof value.actionAttribute === \"string\" && /^[a-z][\\w-]*$/i.test(value.actionAttribute)) {\n actionAttribute = value.actionAttribute;\n } else {\n reportInvalid(\n diagnostics,\n \"capture.interactions.actionAttribute\",\n \"an attribute name of letters, digits, hyphens and underscores\",\n value.actionAttribute,\n `\"${actionAttribute}\"`,\n );\n }\n }\n return {\n actionAttribute,\n text: resolveBoolean(\n \"capture.interactions.text\",\n value.text,\n previous.text ?? false,\n diagnostics,\n ),\n selector: resolveBoolean(\n \"capture.interactions.selector\",\n value.selector,\n previous.selector ?? false,\n diagnostics,\n ),\n ignoreSelector:\n typeof ignoreSelector === \"string\" || ignoreSelector === null ? ignoreSelector : undefined,\n maxTextChars: resolveInteger(\n \"capture.interactions.maxTextChars\",\n value.maxTextChars,\n [0, Number.MAX_SAFE_INTEGER],\n previous.maxTextChars ?? 50,\n diagnostics,\n ),\n rageClicks: resolveBoolean(\n \"capture.interactions.rageClicks\",\n value.rageClicks,\n previous.rageClicks ?? false,\n diagnostics,\n ),\n rageClickCount: resolveInteger(\n \"capture.interactions.rageClickCount\",\n value.rageClickCount,\n [2, 20],\n previous.rageClickCount ?? RAGE_CLICK_COUNT,\n diagnostics,\n ),\n rageClickWindowMs: resolveInteger(\n \"capture.interactions.rageClickWindowMs\",\n value.rageClickWindowMs,\n CLICK_WAIT_RANGE,\n previous.rageClickWindowMs ?? RAGE_CLICK_WINDOW_MS,\n diagnostics,\n ),\n deadClicks: resolveBoolean(\n \"capture.interactions.deadClicks\",\n value.deadClicks,\n previous.deadClicks ?? false,\n diagnostics,\n ),\n deadClickMs: resolveInteger(\n \"capture.interactions.deadClickMs\",\n value.deadClickMs,\n CLICK_WAIT_RANGE,\n previous.deadClickMs ?? DEAD_CLICK_MS,\n diagnostics,\n ),\n };\n}\n\n/** What happens for each key when its signal endpoint is off. */\nconst SIGNAL_OFF = {\n metricsEndpoint: \"The library sends metric records as log records.\",\n tracesEndpoint: \"The library sends no span.\",\n} as const;\n\n/**\n * Validates the metrics or traces endpoint. Only the OTLP serializer has these formats.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current value.\n * @param serializer Resolved serializer option.\n * @param diagnostics Diagnostics reporter.\n * @returns A valid absolute URL, or \"\" to turn the endpoint off.\n */\nfunction resolveSignalEndpoint(\n key: keyof typeof SIGNAL_OFF,\n value: unknown,\n fallback: string,\n serializer: SerializerChoice,\n diagnostics: Diagnostics,\n): string {\n let url = fallback;\n\n if (typeof value === \"string\" && value !== \"\") {\n try {\n new URL(value);\n url = value;\n } catch (error) {\n diagnostics.report(\n \"config.invalid\",\n `${key} is not a valid absolute URL: ${recordedUrl(value, false)}. The library keeps the current value.`,\n undefined,\n error,\n );\n }\n } else if (value === \"\") {\n url = \"\";\n } else if (value !== undefined) {\n reportInvalid(diagnostics, key, \"a URL string\", value, \"the current value\");\n }\n\n // A custom or ECS serializer can't encode a metrics or traces request.\n if (url !== \"\" && serializer !== SERIALIZER_NAME_OTLP) {\n diagnostics.report(\n \"config.invalid\",\n `${key} needs serializer \"${SERIALIZER_NAME_OTLP}\". ${SIGNAL_OFF[key]}`,\n );\n return \"\";\n }\n\n return url;\n}\n\n/** The rules in the form resolvePolicy() reads. POLICY_RULES holds the typed form. */\ninterface PolicyLookup {\n /** Accepted range for each number key. */\n ranges: Partial<Record<string, Range>>;\n /** Accepted values for each choice key. */\n choices?: Partial<Record<string, readonly string[]>>;\n /** Resolver for each key with any other value type. */\n custom?: Partial<Record<string, CustomResolver>>;\n}\n\n/**\n * Checks one policy section. An invalid value keeps the current value.\n * @param name Section name for diagnostic messages.\n * @param input The settings the app supplied.\n * @param base The current settings.\n * @param rules The section's ranges and choices.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid section.\n */\nfunction resolvePolicy<T extends object>(\n name: string,\n input: Partial<T> | undefined,\n base: T,\n rules: PolicyLookup,\n diagnostics: Diagnostics,\n): T {\n const next = { ...base };\n for (const key of Object.keys(base) as (keyof T & string)[]) {\n const value: unknown = input?.[key];\n const fallback: unknown = base[key];\n const range = rules.ranges[key];\n const choice = rules.choices?.[key];\n const custom = rules.custom?.[key];\n let resolved: unknown = fallback;\n if (custom) {\n resolved = custom(`${name}.${key}`, value, fallback, diagnostics);\n } else if (typeof fallback === \"number\" && range) {\n resolved = resolveInteger(`${name}.${key}`, value, range, fallback, diagnostics);\n } else if (typeof fallback === \"boolean\") {\n resolved = resolveBoolean(`${name}.${key}`, value, fallback, diagnostics);\n } else if (choice) {\n resolved = resolveChoice(`${name}.${key}`, value, choice, String(fallback), diagnostics);\n } else if (value === undefined || typeof value === \"string\") {\n resolved = value ?? fallback;\n } else {\n reportInvalid(diagnostics, `${name}.${key}`, \"a string\", value, String(fallback));\n }\n Object.assign(next, { [key]: resolved });\n }\n return next;\n}\n\n/**\n * Resolves partial configuration input into a validated ResolvedConfig.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n * @param previous The active configuration, for an incremental reconfigure.\n * @returns Complete, validated configuration object.\n */\nexport function resolveConfig(\n input: Partial<ObservabilityConfig>,\n diagnostics: Diagnostics,\n previous?: ResolvedConfig,\n): ResolvedConfig {\n const base = previous ?? DEFAULT_CONFIG;\n\n // Check every policy section against its own rules. POLICY_RULES key order is the report order.\n const policies = Object.fromEntries(\n (Object.keys(POLICY_RULES) as PolicySection[]).map((key) => [\n key,\n resolvePolicy(key, input[key], base[key], POLICY_RULES[key], diagnostics),\n ]),\n ) as Pick<ResolvedConfig, PolicySection>;\n const merged: ResolvedConfig = {\n ...base,\n ...input,\n ...policies,\n\n lockConfiguration: resolveBoolean(\n \"lockConfiguration\",\n input.lockConfiguration,\n base.lockConfiguration,\n diagnostics,\n ),\n loggerCache: {\n maxEntries: resolveCacheLimit(\n input.loggerCache?.maxEntries,\n base.loggerCache.maxEntries,\n diagnostics,\n ),\n },\n securityContext: {\n id:\n typeof input.securityContext?.id === \"string\"\n ? input.securityContext.id || base.securityContext.id\n : base.securityContext.id,\n isolation: resolveBoolean(\n \"securityContext.isolation\",\n input.securityContext?.isolation,\n base.securityContext.isolation,\n diagnostics,\n ),\n },\n // An unset environment variable arrives as undefined, so keep the current endpoint.\n endpoint: input.endpoint === undefined ? base.endpoint : input.endpoint,\n // A bad value reports config.invalid and the current value stays. Without this check, a bad\n // minLevel silently drops every record.\n enabled: resolveBoolean(\"enabled\", input.enabled, base.enabled, diagnostics),\n payloadMode: resolveChoice(\n \"payloadMode\",\n input.payloadMode,\n [\"copy\", \"defer\"] as const,\n base.payloadMode,\n diagnostics,\n ),\n minLevel: resolveLevel(\"minLevel\", input.minLevel, base.minLevel, diagnostics),\n minLevels: resolveMinLevels(input.minLevels, base.minLevels, diagnostics),\n processors: resolveList(\n \"processors\",\n input.processors,\n base.processors,\n \"a list of functions\",\n toProcessor,\n diagnostics,\n ),\n compression: resolveChoice(\n \"compression\",\n input.compression,\n COMPRESSION_VALUES,\n base.compression,\n diagnostics,\n ),\n credentials: resolveChoice(\n \"credentials\",\n input.credentials,\n CREDENTIALS_VALUES,\n base.credentials,\n diagnostics,\n ),\n headers:\n \"headers\" in input ? resolveHeaders(input.headers, base.headers, diagnostics) : base.headers,\n storage: resolveChoice(\"storage\", input.storage, STORAGE_VALUES, base.storage, diagnostics),\n identity: resolveChoice(\n \"identity\",\n input.identity,\n IDENTITY_VALUES,\n base.identity,\n diagnostics,\n ),\n // Replaces the raw value from the object merge with the validated one. A name stays a name.\n serializer: resolveSerializer(input.serializer, previous?.serializer, diagnostics),\n console: resolveConsole(input.console, base.console, diagnostics),\n sampling: resolveSampling(input.sampling, base.sampling, diagnostics),\n bus: resolveBus(input.bus, base.bus, diagnostics),\n batching: resolveRanges(\n \"batching\",\n input.batching,\n base.batching,\n BATCHING_RANGES,\n diagnostics,\n ),\n retention: resolveRetention(input.retention, base.retention, diagnostics),\n limits: resolveRanges(\"limits\", input.limits, base.limits, LIMIT_RANGES, diagnostics),\n journey: resolveJourney(input.journey, base.journey, diagnostics),\n capture: resolveCapture(input.capture, base.capture, diagnostics),\n };\n\n for (const key of [\"metricsEndpoint\", \"tracesEndpoint\"] as const) {\n merged[key] = resolveSignalEndpoint(key, input[key], base[key], merged.serializer, diagnostics);\n }\n\n // Guard against a value that can't send and keep the current function. Without a transport,\n // the pipeline drops every batch.\n if (merged.transport !== undefined && typeof merged.transport !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transport must be a function. The library ignores the value.\",\n );\n merged.transport = base.transport;\n }\n\n if (merged.onDrop !== undefined && typeof merged.onDrop !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"onDrop must be a function. The library ignores the value.\",\n );\n merged.onDrop = base.onDrop;\n }\n\n if (merged.contextProvider !== undefined && typeof merged.contextProvider !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must be a function. The library ignores the value.\",\n );\n merged.contextProvider = base.contextProvider;\n }\n\n if (merged.transportWorker !== undefined && typeof merged.transportWorker !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transportWorker must be a function. The library keeps the current value.\",\n );\n merged.transportWorker = base.transportWorker;\n }\n\n if (merged.transportOnExit !== undefined && typeof merged.transportOnExit !== \"function\") {\n diagnostics.report(\n \"config.invalid\",\n \"transportOnExit must be a function. The library ignores the value.\",\n );\n merged.transportOnExit = base.transportOnExit;\n }\n\n // null selects console-only mode and is valid, so report only an empty string.\n // A custom transport needs no endpoint.\n if (merged.endpoint === \"\") {\n if (merged.transport === undefined) {\n diagnostics.report(\n \"config.invalid\",\n \"endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.\",\n );\n }\n } else if (merged.endpoint !== null) {\n try {\n new URL(merged.endpoint);\n } catch (error) {\n diagnostics.report(\n \"config.invalid\",\n `endpoint is not a valid absolute URL: ${recordedUrl(merged.endpoint, false)}.`,\n undefined,\n error,\n );\n }\n }\n\n // Only the delivery stack sends, and it loads only with an endpoint or a custom transport.\n for (const key of [\"metricsEndpoint\", \"tracesEndpoint\"] as const) {\n if (merged[key] !== \"\" && merged.endpoint === null && !merged.transport) {\n diagnostics.report(\n \"config.invalid\",\n `${key} needs endpoint or transport. The library sends nothing to ${key}.`,\n );\n }\n }\n\n if (!merged.serviceName) {\n diagnostics.report(\n \"config.invalid\",\n `serviceName is missing. Every record reports service.name as '${UNKNOWN_SERVICE_NAME}'.`,\n );\n merged.serviceName = UNKNOWN_SERVICE_NAME;\n }\n\n const rate: unknown = merged.sampling.defaultRate;\n if (typeof rate !== \"number\" || rate < SAMPLING_RATE_MIN || rate > SAMPLING_RATE_MAX) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.defaultRate must be 0..1. The value is ${String(rate)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.defaultRate = SAMPLING_RATE_FALLBACK;\n }\n\n const maxRate: unknown = merged.sampling.remoteMaxRate;\n // The negated range test also rejects NaN.\n if (\n typeof maxRate !== \"number\" ||\n !(maxRate >= SAMPLING_RATE_MIN && maxRate <= SAMPLING_RATE_MAX)\n ) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.remoteMaxRate must be 0..1. The value is ${String(maxRate)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.remoteMaxRate = SAMPLING_RATE_FALLBACK;\n }\n\n const rates: [string, unknown][] = Object.entries(merged.sampling.rates);\n for (const [ns, r] of rates) {\n if (typeof r !== \"number\" || r < SAMPLING_RATE_MIN || r > SAMPLING_RATE_MAX) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.rates[\"${ns}\"] must be 0..1. The value is ${String(r)}. The library uses ${String(SAMPLING_RATE_FALLBACK)}.`,\n );\n merged.sampling.rates[ns] = SAMPLING_RATE_FALLBACK;\n }\n }\n\n // Swap the previous endpoints in the ignore list for the new ones to prevent a self-logging\n // loop. Otherwise one failed POST logs another failed POST without end.\n merged.capture.ignoreUrls = merged.capture.ignoreUrls.filter(\n (url) =>\n url !== previous?.endpoint &&\n url !== previous?.metricsEndpoint &&\n url !== previous?.tracesEndpoint &&\n url !== previous?.replay.endpoint,\n );\n for (const url of [\n merged.endpoint,\n merged.metricsEndpoint,\n merged.tracesEndpoint,\n merged.replay.endpoint,\n ]) {\n if (url && !merged.capture.ignoreUrls.includes(url)) {\n merged.capture.ignoreUrls = [...merged.capture.ignoreUrls, url];\n }\n }\n\n if (merged.delivery.retryMaxDelayMs < merged.delivery.retryBaseDelayMs) {\n diagnostics.report(\n \"config.invalid\",\n \"delivery.retryMaxDelayMs must be at least retryBaseDelayMs.\",\n );\n merged.delivery.retryBaseDelayMs = base.delivery.retryBaseDelayMs;\n merged.delivery.retryMaxDelayMs = base.delivery.retryMaxDelayMs;\n }\n if (\n merged.capture.urlTransform !== undefined &&\n typeof merged.capture.urlTransform !== \"function\"\n ) {\n diagnostics.report(\"config.invalid\", \"capture.urlTransform must be a function.\");\n merged.capture.urlTransform = base.capture.urlTransform;\n }\n reportUnknownKeys(input, diagnostics);\n\n return merged;\n}\n\n/**\n * Reports every config key the schema doesn't know, at the top level and one level inside\n * each section. A typo passes the `Partial` type check and has no effect, for example\n * `remoteUrl` for `endpoint` or `capture.webVital` for `capture.webVitals`. Namespace keys\n * under `sampling.rates` are free-form and one level deeper, so the check skips them.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n */\nfunction reportUnknownKeys(input: Partial<ObservabilityConfig>, diagnostics: Diagnostics): void {\n const known = new Set<string>([...Object.keys(DEFAULT_CONFIG), ...UNDEFAULTED_CONFIG_KEYS]);\n\n for (const key of Object.keys(input)) {\n if (!known.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown config key \"${key}\". Check the spelling.`,\n );\n }\n }\n\n for (const section of CONFIG_SECTIONS) {\n const values: unknown = input[section];\n\n if (typeof values !== \"object\" || values === null) {\n continue;\n }\n\n const sectionKeys = new Set<string>([\n ...Object.keys(DEFAULT_CONFIG[section]),\n ...UNDEFAULTED_SECTION_KEYS[section],\n ]);\n\n for (const key of Object.keys(values)) {\n if (!sectionKeys.has(key)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown config key \"${section}.${key}\". Check the spelling.`,\n );\n }\n }\n }\n}\n\n/**\n * Changes the active configuration object in place, so subsystems holding a section\n * reference see the update.\n * @param target Active configuration object to change.\n * @param next Configuration object with the new values.\n */\nexport function applyResolvedConfig(target: ResolvedConfig, next: ResolvedConfig): void {\n for (const key of Object.keys(next) as (keyof ResolvedConfig)[]) {\n // The cast widens the tuple so includes accepts any string key. With satisfies, the tuple\n // stays narrow and every non-section key fails to compile.\n if ((CONFIG_SECTIONS as readonly string[]).includes(key)) {\n continue;\n }\n Object.assign(target, { [key]: next[key] });\n }\n\n // Merge every section object in place to keep its reference. A new object would leave\n // subsystems on the old section they got at construction.\n for (const section of CONFIG_SECTIONS) {\n Object.assign(target[section] as object, next[section] as object);\n }\n}\n","// src/core/context.ts\n//\n// Stores the ambient context attributes that the logger merges into every later record.\n// Keep the store per instance, not at module level: all runtimes in a realm share a module Map.\n\n/** Key-value store for ambient context attributes attached to log records. */\nexport class ContextStore {\n /** Backing store mapping attribute keys to raw values. */\n private readonly map = new Map<string, unknown>();\n\n /**\n * Sets one ambient context attribute.\n * @param key Attribute key.\n * @param value Raw attribute value.\n */\n set(key: string, value: unknown): void {\n this.map.set(key, value);\n }\n\n /**\n * Merges several key-value pairs into the ambient context.\n * @param values Attributes to merge.\n */\n setMany(values: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(values)) {\n this.map.set(key, value);\n }\n }\n\n /**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to remove.\n */\n remove(key: string): void {\n this.map.delete(key);\n }\n\n /** Removes all ambient context attributes. */\n clear(): void {\n this.map.clear();\n }\n\n /**\n * Returns a copy of all ambient context attributes, so a merge target or a sanitizer\n * can't change the store.\n * @returns Plain object with the stored key-value pairs.\n */\n getAll(): Record<string, unknown> {\n return Object.fromEntries(this.map);\n }\n}\n","// src/core/debug-buffer.ts\n//\n// Keeps the recent records that minLevel or sampling dropped. An error record from this context\n// sends them out first, so they show what happened before the error.\n\nimport { ATTR_DEBUG_BUFFER } from \"../constants\";\nimport type { DebugBufferPolicy } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** One kept record, with the time the buffer took it. */\ninterface Kept {\n /** Epoch time in milliseconds when the buffer took the record. */\n at: number;\n /** Built record. The privacy hooks have already run on it. */\n record: LogRecord;\n}\n\n/** Bounded list of the records that were dropped by level or by sampling. */\nexport class DebugBuffer {\n /** Kept records, oldest first. Can grow to twice maxRecords between trims. */\n private kept: Kept[] = [];\n\n /**\n * @param policy Returns the current settings. A later configure() can change them.\n */\n constructor(private readonly policy: () => DebugBufferPolicy) {}\n\n /**\n * Keeps a record. When the buffer is full, the oldest record goes first.\n * @param record Built record. The privacy hooks have already run on it.\n */\n push(record: LogRecord): void {\n const { enabled, maxRecords } = this.policy();\n if (!enabled) {\n return;\n }\n\n this.kept.push({ at: Date.now(), record });\n // Trim in steps. Trimming on every push would copy the whole list each time.\n if (this.kept.length >= maxRecords * 2) {\n this.kept = this.kept.slice(-maxRecords);\n }\n }\n\n /**\n * Takes the kept records that aren't too old and empties the buffer.\n * @returns The records, oldest first, each with `uiobs.debug_buffer: true`.\n */\n drain(): LogRecord[] {\n const kept = this.live();\n this.kept = [];\n\n return kept.map(({ record }) => ({\n ...record,\n attributes: { ...record.attributes, [ATTR_DEBUG_BUFFER]: true },\n }));\n }\n\n /**\n * Returns the kept records without taking them.\n * @returns The records, oldest first.\n */\n snapshot(): LogRecord[] {\n return this.live().map(({ record }) => record);\n }\n\n /**\n * Returns the kept records that the current settings allow. A disabled buffer empties itself.\n * @returns The records, oldest first.\n */\n private live(): Kept[] {\n const { enabled, maxRecords, maxAgeMs } = this.policy();\n if (!enabled) {\n this.kept = [];\n return [];\n }\n\n const oldest = maxAgeMs === 0 ? -Infinity : Date.now() - maxAgeMs;\n\n return this.kept.slice(-maxRecords).filter((entry) => entry.at >= oldest);\n }\n\n /** Removes every kept record, so nothing from an old session or identity goes out. */\n clear(): void {\n this.kept = [];\n }\n}\n","// src/core/diagnostics.ts\n//\n// Reports the library's internal errors. Emits are rate limited, but every event is counted.\n\nimport { DIAGNOSTIC_THROTTLE_MS, LIBRARY_LOG_PREFIX } from \"../constants\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\n\n/** Closed set of diagnostic event codes emitted by library subsystems. */\nexport type DiagnosticCode =\n | \"config.locked\"\n | \"security.rotated\"\n | \"security.context_mismatch\"\n | \"record.dropped_during_rotation\"\n | \"bus.rejected_message\"\n | \"config.invalid\"\n | \"config.reconfigured\"\n | \"record.sanitize_failed\"\n | \"record.truncated\"\n | \"record.dropped_by_level\"\n | \"record.dropped_by_sampling\"\n | \"record.dropped_by_ceiling\"\n | \"record.dropped_by_processor\"\n | \"record.dropped_by_redact\"\n | \"record.dropped_boot_buffer_full\"\n | \"record.dropped_malformed\"\n | \"record.dropped_no_destination\"\n | \"runtime.version_mismatch\"\n | \"journey.expired\"\n | \"journey.adopted\"\n | \"journey.token_too_large\"\n | \"trace.otel_failed\"\n | \"bus.role_resolved\"\n | \"bus.no_owner\"\n | \"bus.handshake_timeout\"\n | \"bus.untrusted_origin\"\n | \"bus.send_failed\"\n | \"transport.http_error\"\n | \"transport.timeout\"\n | \"transport.batch_split\"\n | \"transport.throttled\"\n | \"transport.dropped_permanent\"\n | \"transport.rejected_credentials\"\n | \"transport.serialize_failed\"\n | \"storage.unavailable\"\n | \"storage.degraded\"\n | \"storage.quota_exceeded\"\n | \"storage.evicted\"\n | \"storage.dead_lettered\"\n | \"pipeline.crashed\"\n | \"capture.install_failed\"\n | \"capture.rate_limited\"\n | \"capture.header_failed\"\n | \"capture.record_failed\"\n | \"capture.transport_request\"\n | \"openfin.unavailable\"\n | \"platform.api_blocked\"\n | \"handler.threw\";\n\n/** Diagnostic event payload dispatched to consumer handlers. */\nexport interface DiagnosticEvent {\n /** Diagnostic fault code. */\n code: DiagnosticCode;\n /** Human-readable description. */\n message: string;\n /** Structured context metadata. */\n detail?: Record<string, unknown>;\n /** Caught error instance or reason. */\n cause?: unknown;\n /** Event timestamp in epoch milliseconds. */\n at: number;\n /** Total count of this code since startup, including rate-limited occurrences. */\n count: number;\n}\n\n/** Consumer callback for receiving rate-limited diagnostic events. */\nexport type DiagnosticHandler = (event: DiagnosticEvent) => void;\n\n/** Reports internal errors. Dispatch is rate limited, but every event is counted. */\nexport class Diagnostics {\n /** Running occurrence counts per diagnostic code. */\n private readonly counters = new Map<DiagnosticCode, number>();\n\n /** Timestamp of the last emitted event per code, in epoch milliseconds. */\n private readonly lastEmitted = new Map<DiagnosticCode, number>();\n\n /**\n * @param handler Optional listener for diagnostic events.\n * @param throttleMs Minimum time in milliseconds between emitted events for one code.\n * @param consoleFallback True to print a fixed warning if the diagnostic handler throws.\n */\n constructor(\n private handler?: DiagnosticHandler,\n private throttleMs = DIAGNOSTIC_THROTTLE_MS,\n private consoleFallback = false,\n ) {}\n\n /**\n * Changes the report interval and the console fallback rule.\n * @param throttleMs Minimum wait between reports of one code, in milliseconds.\n * @param consoleFallback True to print a fixed warning if the handler throws.\n */\n setPolicy(throttleMs: number, consoleFallback: boolean): void {\n this.throttleMs = throttleMs;\n this.consoleFallback = consoleFallback;\n }\n\n /**\n * Replaces or removes the active diagnostic event handler.\n * @param handler New diagnostic event handler.\n */\n setHandler(handler?: DiagnosticHandler): void {\n this.handler = handler;\n }\n\n /**\n * Increments the count for a code without calling the handler.\n * @param code Diagnostic code to increment.\n * @param by Amount to add.\n * @returns New total for the code.\n */\n count(code: DiagnosticCode, by = 1): number {\n const total = (this.counters.get(code) ?? 0) + by;\n this.counters.set(code, total);\n return total;\n }\n\n /**\n * Bumps the counter for the code and, once the throttle window has passed, sends the event\n * to the handler. Never throws.\n * @param code Diagnostic code.\n * @param message Event description.\n * @param detail Optional structured metadata.\n * @param cause Caught error instance or reason.\n * @returns False if the throttle dropped the event.\n */\n report(\n code: DiagnosticCode,\n message: string,\n detail?: Record<string, unknown>,\n cause?: unknown,\n ): boolean {\n const count = this.count(code);\n const now = Date.now();\n const last = this.lastEmitted.get(code) ?? 0;\n if (now - last < this.throttleMs) {\n return false;\n }\n this.lastEmitted.set(code, now);\n\n const event: DiagnosticEvent = {\n code,\n message,\n detail,\n cause,\n at: now,\n count,\n };\n\n const { handler } = this;\n\n if (!handler) {\n return true;\n }\n try {\n // Console capture skips anything the handler logs inside this scope. Without the scope,\n // the line becomes a record, and a failed send of that record raises a new diagnostic.\n runAsLibraryConsole(() => {\n handler(event);\n });\n } catch (_handlerError) {\n // Bump the counter directly. Calling report() here would recurse when the handler throws.\n this.count(\"handler.threw\");\n if (this.consoleFallback && typeof console !== \"undefined\") {\n // Console capture skips calls made in this scope.\n runAsLibraryConsole(() => {\n // eslint-disable-next-line no-console -- Fallback sink when diagnostic handler throws.\n console.warn(`${LIBRARY_LOG_PREFIX} The onDiagnostic handler threw an error.`);\n });\n }\n }\n\n return true;\n }\n\n /**\n * Runs a synchronous function and reports anything it throws to diagnostics.\n * @param code Diagnostic code to report on throw.\n * @param message ASD-STE100 sentence that states the failure. The handler receives it as the\n * event message.\n * @param fn Function to run.\n * @returns The function's return value, or undefined if it threw.\n */\n guard<T>(code: DiagnosticCode, message: string, fn: () => T): T | undefined {\n try {\n return fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Runs an asynchronous function and reports a rejected promise to diagnostics.\n * @param code Diagnostic code to report on rejection.\n * @param message ASD-STE100 sentence that states the failure. The handler receives it as the\n * event message.\n * @param fn Async function to run.\n * @returns Promise that resolves to the return value, or to undefined on rejection.\n */\n async guardAsync<T>(\n code: DiagnosticCode,\n message: string,\n fn: () => Promise<T>,\n ): Promise<T | undefined> {\n try {\n return await fn();\n } catch (error) {\n this.report(code, message, undefined, error);\n return undefined;\n }\n }\n\n /**\n * Returns a copy of the cumulative diagnostic counts since initialization.\n * @returns Map of diagnostic codes to occurrence counts.\n */\n snapshot(): Record<string, number> {\n return Object.fromEntries(this.counters);\n }\n}\n","// src/core/drops.ts\n//\n// Collects lost records into onDrop summaries and sends one summary per reason after the\n// current task. A storm of losses then makes one call, not one per record.\n\nimport { ATTR_JOURNEY_ID, DROP_SUMMARY_MAX_ITEMS } from \"../constants\";\nimport { attributeOf, isActionRecord } from \"../models/batch\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { DropSummary, LossReason } from \"../models/drop\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { runAsLibraryConsole } from \"../utils/library-console\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/**\n * Adds a value to a summary list. The list keeps each value once, up to the limit.\n * @param list Summary list.\n * @param value Value to add.\n */\nfunction addCapped(list: string[], value: string): void {\n if (list.length < DROP_SUMMARY_MAX_ITEMS && !list.includes(value)) {\n list.push(value);\n }\n}\n\n/** Collects lost records and hands the onDrop hook one summary per reason. */\nexport class DropReporter {\n /** Summaries waiting for the end of the task, one per reason. */\n private readonly pending = new Map<LossReason, DropSummary>();\n\n /** True while a microtask is waiting to send the summaries. */\n private scheduled = false;\n\n /** True while the hook runs. A loss the hook itself causes isn't reported again. */\n private reporting = false;\n\n /**\n * @param config Active configuration. `onDrop` is read from it on every call.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Adds lost records to the summary for their reason. Does nothing without an onDrop hook.\n * @param reason Cause of the loss.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n add(reason: LossReason, records: readonly LogRecord[], batchIds: readonly string[] = []): void {\n // A hook that logs can fill a buffer again, and reporting that loss would start a loop.\n if (!this.config.onDrop || this.reporting) {\n return;\n }\n\n // A failed load with an empty buffer loses nothing, and a corrupt entry has no id to report.\n if (records.length === 0 && batchIds.length === 0) {\n return;\n }\n\n let summary = this.pending.get(reason);\n if (!summary) {\n summary = { reason, records: 0, batchIds: [], journeyIds: [], actions: [] };\n this.pending.set(reason, summary);\n }\n\n summary.records += records.length;\n for (const id of batchIds) {\n addCapped(summary.batchIds, id);\n }\n\n for (const record of records) {\n // A record from storage can be corrupt: null, or missing its attributes.\n const journey = attributeOf(record, ATTR_JOURNEY_ID);\n if (typeof journey === \"string\") {\n addCapped(summary.journeyIds, journey);\n }\n\n const body: unknown = isActionRecord(record) ? record.body : undefined;\n if (typeof body === \"string\") {\n addCapped(summary.actions, body);\n }\n }\n\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => {\n this.flush();\n });\n }\n }\n\n /** Hands every waiting summary to the hook. A hook that throws doesn't stop the others. */\n private flush(): void {\n this.scheduled = false;\n const summaries = [...this.pending.values()];\n this.pending.clear();\n\n const onDrop = this.config.onDrop;\n if (!onDrop) {\n return;\n }\n\n this.reporting = true;\n for (const summary of summaries) {\n this.diagnostics.guard(\"handler.threw\", \"The onDrop hook threw an error.\", () => {\n // The capture modules skip any request or console line the hook makes. A captured line\n // would become a record, and that record could evict one more stored batch.\n runAsLibraryRequest(() => {\n runAsLibraryConsole(() => {\n onDrop(summary);\n });\n });\n });\n }\n this.reporting = false;\n }\n}\n","// src/core/hold-buffer.ts\n//\n// Holds records while the runtime can't deliver them. An action is an audit fact, so actions\n// have their own cap and a storm of other records can't push one out.\n\nimport { BUS_MAX_BOOT_BUFFER_ACTIONS, BUS_MAX_BOOT_BUFFER_RECORDS } from \"../constants\";\nimport { isActionRecord } from \"../models/batch\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** Holds records in arrival order. A full buffer drops its oldest record of the same kind. */\nexport class HoldBuffer {\n /** Held records in arrival order. */\n private held: LogRecord[] = [];\n\n /** Number of held actions. Counting them spots a full buffer without a scan on every push. */\n private actions = 0;\n\n /**\n * @param onDrop Receives the record that a full buffer drops.\n */\n constructor(private readonly onDrop: (record: LogRecord) => void) {}\n\n /** Held records in arrival order. */\n get records(): readonly LogRecord[] {\n return this.held;\n }\n\n /** Number of held records. */\n get length(): number {\n return this.held.length;\n }\n\n /**\n * Adds a record. A full buffer drops its oldest record of the same kind.\n * @param record Record to hold.\n */\n push(record: LogRecord): void {\n const action = isActionRecord(record);\n const count = action ? this.actions : this.held.length - this.actions;\n const cap = action ? BUS_MAX_BOOT_BUFFER_ACTIONS : BUS_MAX_BOOT_BUFFER_RECORDS;\n\n if (count < cap) {\n this.actions += action ? 1 : 0;\n } else {\n // Scan only at the cap. Scanning on every push would be quadratic in a log storm.\n const oldest = this.held.findIndex((one) => isActionRecord(one) === action);\n const [dropped] = this.held.splice(oldest, 1);\n this.onDrop(dropped);\n }\n\n this.held.push(record);\n }\n\n /**\n * Removes the held records.\n * @returns The records in arrival order.\n */\n take(): LogRecord[] {\n const records = this.held;\n this.held = [];\n this.actions = 0;\n return records;\n }\n}\n","// src/core/measure.ts\n//\n// Times one operation with named phases. Every phase and the total go into duration histograms.\n// With a span, the operation is that span, with one child span per phase.\n\nimport { METRIC_DEFAULT_BOUNDARIES } from \"../constants\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport { type ClientSpan, newSpanId } from \"../utils/tracing\";\nimport type { SpanData } from \"./spans\";\n\n/** Total duration of each measure, in milliseconds. */\nconst TOTAL_DURATION: InstrumentDef = {\n name: \"ui.measure.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Duration of each phase, in milliseconds. */\nconst PHASE_DURATION: InstrumentDef = {\n name: \"ui.measure.phase.duration\",\n kind: \"histogram\",\n unit: \"ms\",\n boundaries: METRIC_DEFAULT_BOUNDARIES,\n};\n\n/** Where the values of one measure go. */\nexport interface MeasureSinks {\n /** Adds a value to a histogram. */\n metric(def: InstrumentDef, value: number, attributes: MetricAttributes): void;\n /** Records one span. */\n span(span: SpanData): void;\n}\n\n/**\n * Starts the clock for one operation.\n * @param name Operation name. A JavaScript caller can pass any type.\n * @param attributes Copy of the app's attribute set.\n * @param span The operation's span, or undefined when spans are off or the trace was dropped.\n * @param sinks Where the values go.\n * @returns The operation's handle.\n */\nexport function createMeasure(\n name: unknown,\n attributes: MetricAttributes,\n span: ClientSpan | undefined,\n sinks: MeasureSinks,\n): Measure {\n // The record builder needs text.\n const label = String(name);\n const startMs = Date.now();\n const startedAt = performance.now();\n let open: { name: string; at: number } | undefined;\n let ended = false;\n\n // The histograms use the monotonic clock, but a span needs epoch times.\n const epoch = (at: number): number => startMs + at - startedAt;\n\n const closePhase = (now: number, error: boolean): void => {\n if (!open) {\n return;\n }\n\n sinks.metric(PHASE_DURATION, now - open.at, {\n ...attributes,\n \"measure.name\": label,\n \"measure.phase\": open.name,\n });\n if (span) {\n sinks.span({\n name: open.name,\n kind: \"internal\",\n traceId: span.traceId,\n spanId: newSpanId(),\n parentSpanId: span.spanId,\n startMs: epoch(open.at),\n endMs: epoch(now),\n error,\n attributes: { \"measure.name\": label },\n });\n }\n open = undefined;\n };\n\n return {\n phase: (next: unknown) => {\n if (ended) {\n return;\n }\n\n const now = performance.now();\n closePhase(now, false);\n open = { name: String(next), at: now };\n },\n end: (outcome = \"ok\") => {\n if (ended) {\n return;\n }\n\n ended = true;\n const now = performance.now();\n const error = outcome === \"error\";\n closePhase(now, error);\n const fields = { ...attributes, \"measure.outcome\": outcome };\n sinks.metric(TOTAL_DURATION, now - startedAt, { ...fields, \"measure.name\": label });\n if (span) {\n sinks.span({\n ...span,\n name: label,\n kind: \"internal\",\n startMs,\n endMs: epoch(now),\n error,\n attributes: fields,\n });\n }\n },\n };\n}\n","// src/core/record.ts\n//\n// Builds structured log records from ambient context, journey data, trace context and\n// resource attributes. Never throws to the caller.\n// The builder caches the resource block, so call invalidateResource after its inputs change.\n\nimport {\n ATTR_APP_NAMESPACE,\n ATTR_ATTRIBUTES_BYTES,\n ATTR_ATTRIBUTES_DROPPED,\n ATTR_BREADCRUMBS,\n ATTR_ERROR_DATA,\n ATTR_JOURNEY_ID,\n ATTR_JOURNEY_NAME,\n ATTR_JOURNEY_PARENT_ID,\n ATTR_LOG_SEQ,\n ATTR_LOG_TYPE,\n ATTR_PAGE_URL,\n ATTR_SANITIZE_FAILED,\n LEVEL_BYPASS_TYPES,\n LEVEL_ORDER,\n METRIC_KEYS,\n RESOURCE_BROWSER_USER_AGENT,\n RESOURCE_CONTEXT_ID,\n RESOURCE_DEPLOYMENT_ENVIRONMENT,\n RESOURCE_HOST_PLATFORM,\n RESOURCE_OPENFIN_NAME,\n RESOURCE_OPENFIN_UUID,\n RESOURCE_SERVICE_NAME,\n RESOURCE_SERVICE_VERSION,\n RESOURCE_SESSION_ID,\n RESOURCE_TAB_ID,\n RESOURCE_TELEMETRY_SDK_LANGUAGE,\n RESOURCE_TELEMETRY_SDK_NAME,\n RESOURCE_TELEMETRY_SDK_VERSION,\n SEVERITY_NUMBER,\n SPAN_KEYS,\n TELEMETRY_SDK_LANGUAGE,\n TELEMETRY_SDK_NAME,\n TELEMETRY_SDK_VERSION,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport {\n isLogLevel,\n isLogRecord,\n type LogLevel,\n type LogRecord,\n type LogType,\n nowUnixNano,\n} from \"../models/log-record\";\nimport { isObject } from \"../utils/guards\";\nimport type { Identity } from \"../utils/identity\";\nimport { currentUrl, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { type SanitizeLimits, sanitizeWithSize, truncate } from \"../utils/sanitize\";\nimport type { Sequence } from \"../utils/sequence\";\nimport type { TraceContext, TraceEngine } from \"../utils/tracing\";\nimport type { ContextStore } from \"./context\";\nimport type { DebugBuffer } from \"./debug-buffer\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport type { Journey, JourneyEngine } from \"./journey\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport { levelFor, shouldSampleInput } from \"./sampling\";\n\n/** Prefix of the error fields, which an oversized error record keeps. */\nconst ERROR_ATTR_PREFIX = \"error.\";\n\n/** Index keys that an oversized record keeps as redact left them. */\nconst REDACTABLE_INDEX_KEYS = [ATTR_PAGE_URL, ATTR_JOURNEY_ID, ATTR_JOURNEY_NAME] as const;\n\n/** Injected dependencies required by RecordBuilder. */\nexport interface RecordBuilderDeps {\n /** Active configuration object reference. */\n config: ResolvedConfig;\n /** Per-record size caps. */\n limits: RecordLimits;\n /** Diagnostics reporter instance. */\n diagnostics: Diagnostics;\n /** Ambient context store. */\n context: ContextStore;\n /** Active journey engine. */\n journey: JourneyEngine;\n /** Distributed tracing engine. */\n tracing: TraceEngine;\n /** Monotonic sequence counter. */\n sequence: Sequence;\n /** Context, session and tab identity. */\n identity: Identity;\n /** Detected host platform metadata. */\n platform: PlatformMetadata;\n /** Slot for the sampling rules from the ingest server. */\n remote: RemoteSlot;\n /** Keeps the records that minLevel or sampling drops, for the next error. */\n debug?: DebugBuffer;\n}\n\n/** Per-record size limits. The builder applies them after sanitize and after redact. */\nexport interface RecordLimits extends SanitizeLimits {\n /** Max record body length, in characters. */\n maxBodyChars: number;\n /** Max total attribute bytes per record. */\n maxRecordBytes: number;\n}\n\n/**\n * Reason a record was not built. \"malformed\" means a processor or the redact hook broke the\n * record shape or set an unknown severityText.\n */\nexport type DropReason = \"level\" | \"sampling\" | \"processor\" | \"redact\" | \"malformed\";\n\n/** Consumer hook that changes or drops a record. */\ntype RecordHook = (record: LogRecord) => LogRecord | null;\n\n/** Stage of a consumer hook. */\ntype HookStage = \"processor\" | \"redact\";\n\n/** Message subject and drop code for each hook stage. */\nconst HOOK_STAGES = {\n processor: { label: \"A processor\", code: \"record.dropped_by_processor\" },\n redact: { label: \"The redact hook\", code: \"record.dropped_by_redact\" },\n} as const;\n\n/** Outcome of one build call. */\nexport interface BuildResult {\n /** Completed record, or null when the builder drops it. */\n record: LogRecord | null;\n /** Reason for the drop. Absent when a record was built. */\n dropped?: DropReason;\n}\n\n/** Metadata captured before a deferred logger call reads its payload. */\nexport interface RecordSnapshot {\n timeUnixNano: string;\n trace: TraceContext;\n journey: Journey | null;\n context: Record<string, unknown>;\n url: string;\n}\n\n/** Input parameters for constructing a single log record. */\nexport interface BuildInput {\n /** Severity level of the log entry. */\n level: LogLevel;\n /** Telemetry type classification. */\n type: LogType;\n /** Primary log message body. */\n body: string;\n /** Originating application namespace. */\n namespace: string;\n /** Pre-merged scoped context from logger instance. */\n scoped?: Record<string, unknown>;\n /** Call-site payload attributes. */\n payload?: Record<string, unknown>;\n /**\n * Fields the library builds with a fixed size bound, for example a point's buckets.\n * The record limits don't trim them, and they override a payload key of the same name.\n */\n fixed?: Record<string, unknown>;\n /** True for a counter or histogram point. Sampling keeps it. */\n aggregated?: boolean;\n /** A span's trace IDs. Without them the builder reads the active trace. */\n trace?: TraceContext;\n /** The call's metadata, captured before the deferred build. */\n snapshot?: RecordSnapshot;\n}\n\n/** Keys of the fields the library builds for a metric point or a span. */\nconst FIXED_KEYS: readonly string[] = [\n \"metric.name\",\n \"metric.unit\",\n \"metric.type\",\n \"metric.value\",\n ...Object.values(METRIC_KEYS),\n ...Object.values(SPAN_KEYS),\n];\n\n/**\n * Reads the fields that the library built in another context. The sender's hooks can't change\n * them, and the limits can't trim them.\n * @param attributes A forwarded record's attributes.\n * @returns Those fields that the record has.\n */\nfunction fixedOf(attributes: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n FIXED_KEYS.filter((key) => key in attributes).map((key) => [key, attributes[key]]),\n );\n}\n\n/**\n * Casts a sanitized plain object value to an attribute record.\n * @param value Sanitized object value.\n * @returns Attribute record.\n */\nfunction asAttributes(value: unknown): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\n/** Builds validated and sanitized LogRecord instances from logger inputs. */\nexport class RecordBuilder {\n /** Cached resource attributes block. */\n private resourceCache: Record<string, unknown> | null = null;\n\n /**\n * @param deps Injected builder dependencies.\n */\n constructor(private readonly deps: RecordBuilderDeps) {}\n\n /** Clears the cached resource attributes, so the next build computes them again. */\n invalidateResource(): void {\n this.resourceCache = null;\n }\n\n /**\n * Checks whether logging is on and the level is at or above the namespace's minimum level.\n * The minimum level doesn't apply to an action or a metric.\n * @param level Target log severity level.\n * @param namespace Logger namespace. `minLevels` can set its level.\n * @param type Record type. Without it, the minimum level applies.\n * @returns True if the library builds a record of this level and type.\n */\n isEnabled(level: LogLevel, namespace: string, type?: LogType): boolean {\n const { config } = this.deps;\n if (!config.enabled) {\n return false;\n }\n\n if (type !== undefined && LEVEL_BYPASS_TYPES.includes(type)) {\n return true;\n }\n\n // A remote rule can lower the level during an incident.\n const minLevel =\n this.deps.remote.sampling?.minLevelFor(namespace) ?? levelFor(namespace, config);\n\n return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];\n }\n\n /**\n * Keeps a record that minLevel or sampling dropped, when the debug buffer is on. The privacy\n * hooks run now, and an error record from this context sends the kept record later.\n * @param input The dropped record's input.\n */\n private keepForDebug(input: BuildInput): void {\n const { config, debug } = this.deps;\n if (!debug || !config.enabled || !config.debugBuffer.enabled) {\n return;\n }\n\n const { record } = this.build(input, true);\n if (record) {\n debug.push(record);\n }\n }\n\n /**\n * Builds a structured LogRecord from the input, sanitizing attributes and applying size limits.\n * @param input Logger call input parameters.\n * @param forConsole True to skip delivery sampling and level checks. Privacy hooks still run.\n * @returns The record, or null with the reason for the drop.\n */\n build(input: BuildInput, forConsole = false): BuildResult {\n const { config, diagnostics, tracing, journey, sequence, limits, remote } = this.deps;\n\n if (!forConsole && !this.isEnabled(input.level, input.namespace, input.type)) {\n diagnostics.count(\"record.dropped_by_level\");\n this.keepForDebug(input);\n return { record: null, dropped: \"level\" };\n }\n\n const traceCtx = input.trace ?? input.snapshot?.trace ?? tracing.resolve();\n const activeJourney = input.snapshot ? input.snapshot.journey : journey.current();\n\n // Sample delivery records before the attribute walk. A record for the console or a\n // breadcrumb skips this check: the privacy hooks still process it, but it is never sent.\n const sampled = shouldSampleInput(\n {\n level: input.level,\n type: input.type,\n namespace: input.namespace,\n journeyId: activeJourney?.id ?? \"\",\n traceId: traceCtx.traceId,\n aggregated: input.aggregated,\n },\n config,\n remote.sampling?.current() ?? null,\n );\n if (!forConsole && !sampled) {\n diagnostics.count(\"record.dropped_by_sampling\");\n this.keepForDebug(input);\n return { record: null, dropped: \"sampling\" };\n }\n\n const seq = sequence.next();\n // The query and fragment can contain tokens and user input. The path is what groups records.\n const url = input.snapshot?.url ?? currentUrl(diagnostics);\n const pageUrl = config.metadata.pageUrl\n ? recordedUrl(url, config.capture.fullUrls, config.capture.urlTransform, diagnostics)\n : \"\";\n\n let attributes: Record<string, unknown>;\n let bytes = 0;\n try {\n const fromContext = sanitizeWithSize(\n input.snapshot?.context ?? this.deps.context.getAll(),\n limits,\n diagnostics,\n );\n const fromProvider = sanitizeWithSize(this.provided(), limits, diagnostics);\n const fromScope = sanitizeWithSize(input.scoped ?? {}, limits, diagnostics);\n const fromPayload = sanitizeWithSize(input.payload ?? {}, limits, diagnostics);\n bytes = fromContext.bytes + fromProvider.bytes + fromScope.bytes + fromPayload.bytes;\n\n // Merge in increasing precedence: the provider overrides the context, scope overrides\n // the provider, and payload overrides scope.\n attributes = {\n ...asAttributes(fromContext.value),\n ...asAttributes(fromProvider.value),\n ...asAttributes(fromScope.value),\n ...asAttributes(fromPayload.value),\n };\n } catch (error) {\n diagnostics.report(\n \"record.sanitize_failed\",\n \"The library could not sanitize the attributes.\",\n undefined,\n error,\n );\n attributes = { [ATTR_SANITIZE_FAILED]: true };\n }\n\n // A trimmed bucket list would make the serializer drop the point.\n Object.assign(attributes, input.fixed);\n\n // Set reserved attributes after the payload merge. If they went first, a payload key\n // named journey.id would replace the ID that correlates the records.\n attributes[ATTR_LOG_TYPE] = input.type;\n attributes[ATTR_LOG_SEQ] = seq;\n attributes[ATTR_APP_NAMESPACE] = input.namespace;\n attributes[ATTR_PAGE_URL] = pageUrl;\n if (activeJourney) {\n attributes[ATTR_JOURNEY_ID] = activeJourney.id;\n attributes[ATTR_JOURNEY_NAME] = activeJourney.name;\n if (activeJourney.parentId !== undefined) {\n attributes[ATTR_JOURNEY_PARENT_ID] = activeJourney.parentId;\n }\n }\n\n const body = truncate(input.body, limits.maxBodyChars);\n if (body !== input.body) {\n diagnostics.count(\"record.truncated\");\n }\n\n let record: LogRecord = {\n timeUnixNano: input.snapshot?.timeUnixNano ?? nowUnixNano(),\n traceId: traceCtx.traceId,\n spanId: traceCtx.spanId,\n traceFlags: traceCtx.traceFlags,\n severityNumber: SEVERITY_NUMBER[input.level],\n severityText: input.level,\n body,\n attributes,\n resource: this.resource(),\n };\n\n // The processors run first. redact is the last privacy gate.\n const stages = config.processors.map((hook): [RecordHook, HookStage] => [hook, \"processor\"]);\n if (config.redact) {\n stages.push([config.redact, \"redact\"]);\n }\n\n if (stages.length > 0) {\n const outcome = this.applyHooks(record, stages, input.fixed);\n if (typeof outcome === \"string\") {\n return { record: null, dropped: outcome };\n }\n\n ({ record, bytes } = outcome);\n }\n\n // Drop the caller attributes when they exceed maxRecordBytes, but keep the index keys:\n // a search can't find a record without journey.id and trace_id. Keep the error fields,\n // then the breadcrumbs if they fit, because they say why the record exists.\n if (bytes > limits.maxRecordBytes) {\n diagnostics.report(\n \"record.truncated\",\n \"The attributes are larger than the size limit. The library dropped the caller attributes.\",\n { bytes, body: record.body },\n );\n\n const kept: Record<string, unknown> = {\n [ATTR_LOG_TYPE]: input.type,\n [ATTR_LOG_SEQ]: seq,\n [ATTR_APP_NAMESPACE]: input.namespace,\n [ATTR_ATTRIBUTES_DROPPED]: true,\n [ATTR_ATTRIBUTES_BYTES]: bytes,\n };\n\n // Read these keys after redact, because the hook can remove a token from page.url.\n for (const key of REDACTABLE_INDEX_KEYS) {\n if (key in record.attributes) {\n kept[key] = record.attributes[key];\n }\n }\n\n for (const [key, value] of Object.entries(record.attributes)) {\n if (key.startsWith(ERROR_ATTR_PREFIX)) {\n kept[key] = value;\n }\n }\n\n // error.data can be large, so drop it first, before the other error fields.\n let keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n if (keptBytes > limits.maxRecordBytes && ATTR_ERROR_DATA in kept) {\n Reflect.deleteProperty(kept, ATTR_ERROR_DATA);\n keptBytes = sanitizeWithSize(kept, limits, diagnostics).bytes;\n }\n\n const breadcrumbs = record.attributes[ATTR_BREADCRUMBS];\n if (breadcrumbs !== undefined) {\n const crumbBytes = sanitizeWithSize(breadcrumbs, limits, diagnostics).bytes;\n if (keptBytes + crumbBytes <= limits.maxRecordBytes) {\n kept[ATTR_BREADCRUMBS] = breadcrumbs;\n }\n }\n\n // A point without its metric fields is lost.\n Object.assign(kept, input.fixed);\n record.attributes = kept;\n }\n\n return { record };\n }\n\n /**\n * Runs the redact hook on a record from another context. A child context without redact\n * forwards raw records, so the sender is the last privacy gate.\n * @param record Forwarded record.\n * @returns The record to deliver, or null when the hook drops it.\n */\n redactForwarded(record: LogRecord): LogRecord | null {\n const { redact } = this.deps.config;\n if (!redact) {\n return record;\n }\n\n const stages: [RecordHook, HookStage][] = [[redact, \"redact\"]];\n const outcome = this.applyHooks(record, stages, fixedOf(record.attributes));\n return typeof outcome === \"string\" ? null : outcome.record;\n }\n\n /**\n * Runs the hooks in order, then sanitizes and measures the attributes again.\n * @param record Built record.\n * @param stages Hooks and their stages.\n * @param fixed Fields the library builds. The hooks can't change them.\n * @returns The record and the size of its attributes, or the reason for the drop.\n */\n private applyHooks(\n record: LogRecord,\n stages: readonly [RecordHook, HookStage][],\n fixed: Record<string, unknown> | undefined,\n ): { record: LogRecord; bytes: number } | DropReason {\n let current = record;\n\n for (const [hook, stage] of stages) {\n const outcome = this.runHook(hook, stage, current);\n if (typeof outcome === \"string\") {\n return outcome;\n }\n current = outcome;\n }\n\n // A hook can change the attributes in place or replace them. A cycle, a hostile getter or\n // a BigInt from a hook would throw at serialization, and the transport would lose the batch.\n const { diagnostics, limits } = this.deps;\n const remeasured = sanitizeWithSize(current.attributes, limits, diagnostics);\n const attributes = asAttributes(remeasured.value);\n // The limits must not trim the fields the library builds.\n Object.assign(attributes, fixed);\n\n return { record: { ...current, attributes }, bytes: remeasured.bytes };\n }\n\n /**\n * Runs one consumer hook on a record. A processor and the redact hook have the same contract.\n * @param hook Processor or redact hook.\n * @param stage Stage of the hook.\n * @param record Record before the hook.\n * @returns The record after the hook, or the reason for the drop.\n */\n private runHook(hook: RecordHook, stage: HookStage, record: LogRecord): LogRecord | DropReason {\n const { diagnostics } = this.deps;\n const { label, code } = HOOK_STAGES[stage];\n\n // A plain JavaScript hook can edit the record in place and return nothing.\n let changed: unknown;\n try {\n changed = hook(record);\n } catch (error) {\n // Drop the record. A record the hook didn't clean must not leave the page.\n diagnostics.report(\n code,\n `${label} threw an error. The library dropped the record.`,\n undefined,\n error,\n );\n return stage;\n }\n\n if (changed === null) {\n diagnostics.count(code);\n return stage;\n }\n\n const candidate: unknown = changed ?? record;\n\n if (!isLogRecord(candidate)) {\n // The hook changed the record in place, so we have no intact copy.\n if (candidate === record) {\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} changed the record to a shape that is not a record. The library dropped it.`,\n );\n return \"malformed\";\n }\n\n // A plain JavaScript hook can return a string or a Promise. The record didn't pass the hook.\n diagnostics.report(\n code,\n `${label} returned a value that is not a record. The library dropped the record.`,\n );\n return stage;\n }\n\n if (!isLogLevel(candidate.severityText)) {\n // An unknown level has no severity number, so the serializer can't map it.\n diagnostics.report(\n \"record.dropped_malformed\",\n `${label} set a severityText that is not a log level. The library dropped the record.`,\n );\n return \"malformed\";\n }\n\n // The hook can change severityText, so keep the number in step with the text.\n return { ...candidate, severityNumber: SEVERITY_NUMBER[candidate.severityText] };\n }\n\n /**\n * Calls the config's contextProvider. A provider that throws or returns something that isn't\n * an object adds nothing, and the record is still built. undefined means no attributes.\n * @returns The attributes from the provider, or an empty object.\n */\n private provided(): unknown {\n const provider = this.deps.config.contextProvider;\n if (!provider) {\n return {};\n }\n\n const { diagnostics } = this.deps;\n const value = diagnostics.guard(\n \"handler.threw\",\n \"The contextProvider threw an error. The record has no attributes from it.\",\n () => {\n const given: unknown = provider();\n if (given === undefined) {\n return {};\n }\n\n // A promise is an object, but its fields aren't attributes.\n return isObject(given) && typeof given.then !== \"function\" ? given : null;\n },\n );\n\n if (value === null) {\n diagnostics.report(\n \"config.invalid\",\n \"contextProvider must return an object of attributes. The library ignores the value.\",\n );\n }\n\n return value ?? {};\n }\n\n /**\n * Computes or returns cached resource metadata for this runtime context.\n * @returns Resource attributes record.\n */\n private resource(): Record<string, unknown> {\n if (this.resourceCache) {\n return this.resourceCache;\n }\n const { config, identity, platform } = this.deps;\n\n this.resourceCache = {\n [RESOURCE_SERVICE_NAME]: config.serviceName,\n [RESOURCE_SERVICE_VERSION]: config.serviceVersion,\n [RESOURCE_DEPLOYMENT_ENVIRONMENT]: config.environment,\n [RESOURCE_TELEMETRY_SDK_NAME]: TELEMETRY_SDK_NAME,\n [RESOURCE_TELEMETRY_SDK_VERSION]: TELEMETRY_SDK_VERSION,\n [RESOURCE_TELEMETRY_SDK_LANGUAGE]: TELEMETRY_SDK_LANGUAGE,\n [RESOURCE_HOST_PLATFORM]: platform.platform,\n [RESOURCE_SESSION_ID]: identity.sessionId,\n [RESOURCE_TAB_ID]: identity.tabId,\n [RESOURCE_CONTEXT_ID]: identity.contextId,\n ...(config.metadata.userAgent ? { [RESOURCE_BROWSER_USER_AGENT]: platform.userAgent } : {}),\n // Omits undefined OpenFin properties from resource attributes.\n ...(!config.metadata.openfin || platform.openfinUuid === undefined\n ? {}\n : { [RESOURCE_OPENFIN_UUID]: platform.openfinUuid }),\n ...(!config.metadata.openfin || platform.openfinName === undefined\n ? {}\n : { [RESOURCE_OPENFIN_NAME]: platform.openfinName }),\n };\n return this.resourceCache;\n }\n}\n","// src/core/spans.ts\n//\n// Builds the span data for a root span and the span fields for a span record. The runtime\n// builds every span as a record of type \"span\", and the traces serializer reads the span fields.\n\nimport { SPAN_KEYS } from \"../constants\";\nimport type { EndedTrace, RotateReason } from \"../utils/tracing\";\n\n/** Microseconds in one millisecond. */\nconst US_PER_MS = 1000;\n\n/** Root span name for each reason a trace can start. */\nconst ROOT_NAMES: Record<RotateReason, string> = {\n start: \"ui.start\",\n interaction: \"ui.interaction\",\n navigation: \"ui.navigation\",\n explicit: \"ui.trace\",\n maxAge: \"ui.trace\",\n};\n\n/** One span recorded by the runtime. */\nexport interface SpanData {\n /** Span name. */\n name: string;\n /** \"internal\" for a root span, \"client\" for a request. */\n kind: \"internal\" | \"client\";\n /** Trace ID. */\n traceId: string;\n /** Span ID. */\n spanId: string;\n /** The parent's span ID, or \"\" for a root span. */\n parentSpanId: string;\n /** Start time in epoch milliseconds. */\n startMs: number;\n /** End time in epoch milliseconds. */\n endMs: number;\n /** True for a failed operation. */\n error: boolean;\n /** The span's attributes. */\n attributes: Record<string, unknown>;\n /** Server span linked through a response traceparent entry. */\n link?: { traceId: string; spanId: string };\n}\n\n/**\n * Converts epoch milliseconds to nanoseconds as a decimal string, keeping microseconds.\n * @param ms Epoch time in milliseconds. May have a fraction.\n * @returns Epoch time in nanoseconds.\n */\nfunction unixNano(ms: number): string {\n return `${String(Math.round(ms * US_PER_MS))}000`;\n}\n\n/**\n * Builds the root span for an ambient trace that has ended.\n * @param ended The trace.\n * @returns The span data.\n */\nexport function rootSpan(ended: EndedTrace): SpanData {\n return {\n name: ROOT_NAMES[ended.reason],\n kind: \"internal\",\n traceId: ended.traceId,\n spanId: ended.spanId,\n parentSpanId: \"\",\n startMs: ended.startedAt,\n endMs: ended.endedAt,\n error: false,\n attributes: {},\n };\n}\n\n/**\n * Builds the span fields for a span record. The record limits don't trim them.\n * @param span The span data.\n * @returns The fields.\n */\nexport function spanFields(span: SpanData): Record<string, unknown> {\n return {\n [SPAN_KEYS.kind]: span.kind,\n [SPAN_KEYS.parentId]: span.parentSpanId,\n [SPAN_KEYS.start]: unixNano(span.startMs),\n [SPAN_KEYS.end]: unixNano(span.endMs),\n [SPAN_KEYS.status]: span.error ? \"error\" : \"unset\",\n ...(span.link\n ? {\n [SPAN_KEYS.linkTraceId]: span.link.traceId,\n [SPAN_KEYS.linkSpanId]: span.link.spanId,\n }\n : {}),\n };\n}\n","// src/core/runtime.ts\n//\n// Coordinates the subsystems. Manages their lifecycles, the configuration and record routing.\n\nimport type { Bus } from \"../bus/bus\";\nimport type { Receive, WorkerLike } from \"../bus/links\";\nimport type { Capture, CaptureContext, CaptureOnce } from \"../capture/types\";\nimport {\n ATTR_BREADCRUMBS,\n ATTR_DEBUG_BUFFER,\n ATTR_PAGE_URL,\n CAPTURE_NAMESPACE,\n REMOTE_CAPTURE_FLAGS,\n DIAGNOSTICS_NAMESPACE,\n GAP_REPORT_THROTTLE_MS,\n METRIC_NAMESPACE,\n RUNTIME_GLOBAL_KEY,\n RUNTIME_STOPPED_KEY,\n STORAGE_NAMESPACE,\n TELEMETRY_SDK_VERSION,\n TRACE_FLAGS_SAMPLED,\n TRACE_NAMESPACE,\n INSTRUMENT_OPTIONS_FAULT,\n} from \"../constants\";\nimport type { LogBatch } from \"../models/batch\";\nimport type { BusMessage, BusRole } from \"../models/bus\";\nimport type { FrameOptions, SourceOptions } from \"../models/bus\";\nimport type {\n CaptureOptions,\n IdentityStrategy,\n ObservabilityConfig,\n ResolvedConfig,\n StorageStrategy,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n} from \"../models/config\";\nimport type { LossReporter } from \"../models/drop\";\nimport type { InstrumentDef, Measure, MetricAttributes } from \"../models/metric\";\nimport type { CapturePlugin, PluginContext } from \"../models/plugin\";\nimport { isLogRecord, type LogRecord } from \"../models/log-record\";\nimport type { DeliveryStats } from \"../models/stats\";\nimport type { DebugBundle, ObservabilityHealth } from \"../models/health\";\nimport type { PruneResult, StorageAdapter, StoragePersistence } from \"../models/storage\";\nimport { ConsoleSink } from \"../utils/console\";\nimport { isObject } from \"../utils/guards\";\nimport {\n BROWSER_STORES,\n type Identity,\n type IdentityStores,\n memoryStores,\n newId,\n persistTabId,\n resolveIdentity,\n SessionTouch,\n} from \"../utils/identity\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { detectPlatform, type PlatformMetadata, recordedUrl } from \"../utils/platform\";\nimport { sanitize, truncate } from \"../utils/sanitize\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { Sequence } from \"../utils/sequence\";\nimport { TraceEngine } from \"../utils/tracing\";\nimport { type Breadcrumb, BreadcrumbBuffer } from \"./breadcrumbs\";\nimport { applyResolvedConfig, resolveConfig } from \"./config\";\nimport { ContextStore } from \"./context\";\nimport { DebugBuffer } from \"./debug-buffer\";\nimport { cancelDeferred, drainDeferred } from \"./deferred\";\nimport {\n type DiagnosticCode,\n type DiagnosticEvent,\n type DiagnosticHandler,\n Diagnostics,\n} from \"./diagnostics\";\nimport { DropReporter } from \"./drops\";\nimport { HoldBuffer } from \"./hold-buffer\";\nimport { JourneyEngine, JOURNEY_OPTIONS, type JourneyOptions } from \"./journey\";\nimport { OneLogger } from \"./logger\";\nimport { createMeasure } from \"./measure\";\nimport { makeCounter, makeHistogram, Meter, type RecordMetric } from \"./meter\";\nimport { profilerCore, type ProfilerSink } from \"./profiler\";\nimport { RecordBuilder } from \"./record\";\nimport type { RemoteSlot } from \"./remote-sampling\";\nimport { sampleKey, shouldSample } from \"./sampling\";\nimport type { Sender } from \"./sender\";\nimport { rootSpan, type SpanData, spanFields } from \"./spans\";\n\n/** Constructor for a capture module. */\ntype CaptureClass = new (ctx: CaptureContext) => Capture;\n\n/** The import for each capture module. Each one is its own chunk. */\nconst CAPTURE_LOADERS = {\n errors: async (): Promise<CaptureClass> => (await import(\"../capture/errors\")).ErrorCapture,\n network: async (): Promise<CaptureClass> => (await import(\"../capture/network\")).NetworkCapture,\n interactions: async (): Promise<CaptureClass> =>\n (await import(\"../capture/interactions\")).InteractionCapture,\n webVitals: async (): Promise<CaptureClass> =>\n (await import(\"../capture/web-vitals\")).WebVitalsCapture,\n longFrames: async (): Promise<CaptureClass> =>\n (await import(\"../capture/long-frames\")).LongFrameCapture,\n console: async (): Promise<CaptureClass> => (await import(\"../capture/console\")).ConsoleCapture,\n uncleanExit: async (): Promise<CaptureClass> =>\n (await import(\"../capture/unclean-exit\")).UncleanExitCapture,\n userTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/user-timing\")).UserTimingCapture,\n reports: async (): Promise<CaptureClass> => (await import(\"../capture/reports\")).ReportCapture,\n resourceTiming: async (): Promise<CaptureClass> =>\n (await import(\"../capture/resource-timing\")).ResourceTimingCapture,\n lifecycle: async (): Promise<CaptureClass> =>\n (await import(\"../capture/lifecycle\")).LifecycleCapture,\n framePhases: async (): Promise<CaptureClass> =>\n (await import(\"../capture/profiler-frames\")).FramePhasesCapture,\n framePacing: async (): Promise<CaptureClass> =>\n (await import(\"../capture/profiler-frames\")).FramePacingCapture,\n replay: async (): Promise<CaptureClass> => (await import(\"../capture/replay\")).ReplayCapture,\n};\n\n/** Name of a capture module. */\ntype CaptureName = keyof typeof CAPTURE_LOADERS;\n\n/** The parts of the session replay capture the runtime calls. */\ninterface ReplayControl extends Capture {\n /** Loads the recorder and starts it. */\n start(): Promise<void>;\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void;\n /** Drops the buffer and, if the recorder was running, starts a fresh recording. */\n reset(): void;\n}\n\n/** Constructor for the WebSocket capture plugin. */\ntype WebSocketClass = new (diagnostics: Diagnostics, config: ResolvedConfig) => CapturePlugin;\n\n/** An id per plugin object, so a new plugin object changes the capture key. */\nconst pluginIds = new WeakMap<object, number>();\n\n/** The last id pluginId() handed out. */\nlet lastPluginId = 0;\n\n/**\n * Returns a plugin object's id. The capture key can't hold the plugin itself, because a\n * plugin can contain a cycle and JSON.stringify would throw.\n * @param plugin The app's plugin.\n * @returns The object's id.\n */\nfunction pluginId(plugin: object): number {\n let id = pluginIds.get(plugin);\n\n if (id === undefined) {\n id = ++lastPluginId;\n pluginIds.set(plugin, id);\n }\n\n return id;\n}\n\n/** Global symbol key for the singleton runtime. All federated bundles share it. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** Global symbol key for the runtime that shutdown() stopped. */\nconst STOPPED_KEY = Symbol.for(RUNTIME_STOPPED_KEY);\n\n/** Config sections the delivery stack reads once, when it loads. */\nconst SENDER_SECTIONS = [\"batching\", \"retention\"] as const;\n\n/** Config sections a later configure() can't change. */\ntype StartupSection = (typeof SENDER_SECTIONS)[number] | \"limits\";\n\n/** Delivery settings a rotation resets when the update leaves them out. */\nconst DELIVERY_RESET = {\n endpoint: null,\n metricsEndpoint: \"\",\n tracesEndpoint: \"\",\n headers: undefined,\n credentials: \"omit\",\n transport: undefined,\n transportOnExit: undefined,\n transportWorker: undefined,\n} as const;\n\n/** Delivery settings configure() can't change while isolation is on. */\nconst ROUTING_KEYS = Object.keys(DELIVERY_RESET) as (keyof typeof DELIVERY_RESET)[];\n\n/** Diagnostic codes for a normal event rather than a fault. Their records are logged at INFO. */\nconst NOTICE_CODES: ReadonlySet<DiagnosticCode> = new Set([\n \"bus.role_resolved\",\n \"config.reconfigured\",\n \"security.rotated\",\n \"journey.adopted\",\n \"journey.expired\",\n]);\n\n/**\n * Builds a text key for the capture section. A later configure() reinstalls the capture\n * modules only when the key changes, because a reinstall unpatches and repatches every host\n * function.\n * @param capture Capture section.\n * @returns The key. A function or a RegExp becomes fixed text.\n */\nfunction captureKey(capture: CaptureOptions): string {\n return JSON.stringify({\n ...capture,\n urlTransform: capture.urlTransform ? pluginId(capture.urlTransform) : undefined,\n webVitalsLoader: capture.webVitalsLoader !== undefined,\n ignoreUrls: capture.ignoreUrls.map(String),\n propagateTraceHeaderTo: capture.propagateTraceHeaderTo.map(String),\n userTimingInclude: capture.userTimingInclude.map(String),\n plugins: capture.plugins.map(pluginId),\n });\n}\n\n/**\n * Trims the URL fields of a diagnostic detail, because their query can hold a key.\n * onDiagnostic stays local and keeps them.\n * @param detail A diagnostic event's detail.\n * @returns The detail to put in a record.\n */\nfunction recordDetail(detail: unknown): unknown {\n if (!isObject(detail)) {\n return detail;\n }\n\n const copy = { ...detail };\n for (const key of [\"url\", \"endpoint\"]) {\n const value = copy[key];\n if (typeof value === \"string\") {\n copy[key] = recordedUrl(value, false);\n }\n }\n\n return copy;\n}\n\n/**\n * Removes the delivery settings from a configuration. A console-only runtime must not send\n * or join a bus, because the other version's runtime does both.\n * @param input Consumer configuration options.\n * @returns The options with no endpoint, no transport and bus mode \"off\".\n */\nfunction consoleOnly(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n return {\n ...input,\n endpoint: null,\n metricsEndpoint: \"\",\n tracesEndpoint: \"\",\n transport: undefined,\n transportOnExit: undefined,\n transportWorker: undefined,\n bus: { ...input.bus, mode: \"off\" },\n };\n}\n\n/**\n * Checks whether a configuration names a destination.\n * @param input Consumer configuration options.\n * @returns True if it has an endpoint, a signal endpoint or a transport.\n */\nfunction sends(input: Partial<ObservabilityConfig>): boolean {\n return (\n Boolean(input.endpoint) ||\n Boolean(input.metricsEndpoint) ||\n Boolean(input.tracesEndpoint) ||\n input.transport !== undefined ||\n input.transportWorker !== undefined\n );\n}\n\n/**\n * Checks whether a runtime on a global key comes from this version of the library.\n * @param runtime Runtime on the global key. A runtime older than 0.9.0 has no sdkVersion.\n * @returns True if this copy can call the runtime's methods.\n */\nfunction ownVersion(runtime: ObservabilityRuntime): boolean {\n return runtime.sdkVersion === TELEMETRY_SDK_VERSION;\n}\n\n/** Manages subsystem lifecycles, bus coordination and record delivery. */\nexport class ObservabilityRuntime {\n /** True while the security context is changing. */\n private rotating = false;\n /**\n * True while this runtime has the profiler core attached. Tracking it keeps configure() from\n * restarting the sampling every time, and keeps a runtime with the profiler off from ever\n * creating the core and its global symbol.\n */\n private profilerOn = false;\n /** True while the old context's last records are being collected. */\n private closingContext = false;\n /** Version of another SDK copy that owns the page runtime, or null. */\n private mismatchVersion: string | null = null;\n /** True if the configured context id differs from the owner's context id. */\n private contextMismatch = false;\n /** The context change in progress. Shutdown waits for this promise. */\n private rotation?: Promise<void>;\n /** Memory store kept for later context changes. */\n private memoryStorage?: StorageAdapter;\n /** State of the persistent storage request. getHealth() reports it. */\n private storagePersistence: StoragePersistence = \"off\";\n /** True while a diagnostic record goes out. Diagnostics raised meanwhile produce no record. */\n private recordingDiagnostic = false;\n /** Logger for the records that diagnostics.records produces. */\n private readonly diagnosticLogger = new OneLogger(() => this, DIAGNOSTICS_NAMESPACE);\n /** Records that minLevel or sampling dropped. An error in this context sends them first. */\n private readonly debugBuffer = new DebugBuffer(() => this.config.debugBuffer);\n /** True if the app supplied a context id at startup. */\n private explicitSecurityContext: boolean;\n /** True once this forwarder has taken a context id from its owner. */\n private ownerAdopted = false;\n\n /**\n * Checks whether a security context change is in progress.\n * @returns True until the current change completes.\n */\n isRotating(): boolean {\n return this.rotating;\n }\n\n /**\n * Locks or unlocks configuration when the app asks. Any other code on this origin can call\n * this too, so the lock is not access control.\n * @param locked True to refuse changes through configure().\n */\n setConfigurationLocked(locked: boolean): void {\n if (typeof locked === \"boolean\") this.config.lockConfiguration = locked;\n }\n /**\n * This copy's runtime when another version of the library owns the page runtime.\n * It stays off the global key.\n */\n private static local: ObservabilityRuntime | null = null;\n\n /**\n * This runtime's library version. Another copy reads it from the global key, because two\n * versions sharing one runtime would call methods the other version doesn't have.\n */\n readonly sdkVersion: string = TELEMETRY_SDK_VERSION;\n\n /** Diagnostics reporter for internal faults. */\n readonly diagnostics: Diagnostics;\n\n /** Active configuration instance. A reconfigure changes it in place. */\n readonly config: ResolvedConfig;\n\n /** Detected host platform metadata. */\n readonly platform: PlatformMetadata;\n\n /** Identity context containing session, tab, and context identifiers. */\n readonly identity: Identity;\n\n /** Stores for identity and journey keys, set at startup. */\n private readonly stores: IdentityStores;\n\n /** The identity strategy the stores were built with. */\n private readonly identityBuiltAs: IdentityStrategy;\n\n /** Throttled writer of the session's last-seen timestamp. */\n private readonly sessionTouch: SessionTouch;\n\n /** Store for ambient application context attributes. */\n readonly context = new ContextStore();\n\n /** Ring buffer holding contextual user breadcrumbs. */\n readonly breadcrumbs: BreadcrumbBuffer;\n\n /** Distributed tracing context engine. */\n readonly tracing: TraceEngine;\n\n /** Monotonic sequence counter for records emitted in this context. */\n readonly sequence = new Sequence();\n\n /** Journey tracking engine managing workflow correlation. */\n readonly journey: JourneyEngine;\n\n /** Record builder assembling structured log records. */\n readonly builder: RecordBuilder;\n\n /** Slot for the remote sampling rules. The sender or the bus fills it. */\n private readonly remote: RemoteSlot = {\n sampling: null,\n changed: () => {\n this.refreshCaptures();\n },\n };\n\n /** Number of delivery identity changes. A context's first id doesn't count as a change. */\n private identityEpoch = 0;\n\n /** Session replay's hook. It gets every ERROR and FATAL record. */\n private errorHook: ((record: LogRecord) => void) | undefined;\n\n /**\n * True after startReplay(), false after stopReplay(), undefined until either is called. The\n * app's last choice survives a reinstall of the capture modules.\n */\n private replayConsent: boolean | undefined;\n\n /** The installed session replay capture. */\n private replay: ReplayControl | undefined;\n\n /** Timer that restores the local capture switches once the remote TTL ends. */\n private remoteCaptureTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Settings of the current capture load or install. */\n private installedCaptureKey = \"\";\n\n /** The replay settings the running replay capture was built with. */\n private replayBuiltKey = \"\";\n\n /** Console sink for local developer output. */\n readonly console: ConsoleSink;\n\n /** Collects lost records into onDrop summaries. */\n private readonly drops: DropReporter;\n\n /** Sums the values of the counter and histogram instruments. */\n private readonly meter: Meter;\n\n /**\n * Cross-realm communication bus. Null until its chunk loads. In bus.mode \"off\", it loads\n * only when a child frame or a worker needs it.\n */\n private bus: Bus | null = null;\n\n /** Promise for the bus load and construction. Undefined until first needed. */\n private busBuilt?: Promise<Bus | null>;\n\n /** Promise for the bus load and start. Undefined until first needed. */\n private busLoad?: Promise<Bus | null>;\n\n /** The adapter's storage strategy, set when the build starts. */\n private storageBuiltAs?: StorageStrategy;\n\n /**\n * Delivery stack. Set in the sender role with an endpoint or a custom transport, once the\n * chunk has loaded.\n */\n private sender?: Sender;\n\n /** The delivery stack load. Undefined when nothing loads, so records have no destination. */\n private senderLoad?: Promise<void>;\n\n /** Records that arrive while the delivery stack loads. */\n private readonly pendingRecords = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Active auto-capture instrumentation modules. */\n private readonly captures: Capture[] = [];\n\n /** Number of capture installs. An install replaced by a later one stops after its load. */\n private captureGeneration = 0;\n\n /** Capture work that rebuilding the capture modules must not repeat. */\n private readonly captureOnce: CaptureOnce = {\n webVitals: false,\n navigationTiming: false,\n longFrames: false,\n uncleanExit: false,\n userTiming: false,\n };\n\n /** Holds records created before the bus role is resolved. */\n private readonly bootBuffer = new HoldBuffer((record) => {\n this.dropHeld(record);\n });\n\n /** Records staged for forwarding on the next microtask. */\n private forwardBuffer: LogRecord[] = [];\n\n /** True if a microtask drain of the forward buffer is pending. */\n private forwardScheduled = false;\n\n /** True once startup has decided the bus role. A sender load waits for it. */\n private roleResolved = false;\n\n /** Resolves when startup releases the boot records. Set by init(), awaited by flush(). */\n private started: Promise<void> = Promise.resolve();\n\n /** True if asynchronous initialization is complete. */\n private ready = false;\n\n /** True if shutdown stopped the runtime. */\n private destroyed = false;\n\n /** When the last storage gap warning was reported, in epoch milliseconds. */\n private lastGapAt = 0;\n\n /** Record limits for the builder and the console. The app's first configure() sets them. */\n private readonly limits: ResolvedConfig[\"limits\"];\n\n /** Lifetime rules for the journey engine. The app's first configure() sets the age. */\n private readonly journeyOptions: JourneyOptions;\n\n /** False in a runtime started by an early log call. The first configure() then sets limits. */\n private tunablesLocked = true;\n\n /**\n * True for a console-only runtime, which sends nothing, joins no bus and installs no capture.\n * That happens next to another version of the library on the page, or on a server.\n */\n private readonly degraded: boolean;\n\n /** True once a destination on a server has been reported. It is reported only once. */\n private serverReported = false;\n\n /**\n * Ends a forwarder's root span when its document unloads. The exit flush only ends it in the\n * sender, so without this the client spans of a frame or a view have no parent.\n */\n private readonly onPageHide = (): void => {\n drainDeferred(this);\n if (this.role() !== \"forwarder\") {\n return;\n }\n\n this.tracing.end();\n this.sendForwarded();\n };\n\n /**\n * @param input Initial consumer configuration options.\n * @param mismatch True for a console-only runtime next to another version.\n */\n private constructor(input: Partial<ObservabilityConfig>, mismatch = false) {\n this.diagnostics = new Diagnostics(input.onDiagnostic);\n\n this.platform = detectPlatform(this.diagnostics);\n // A server has no page to capture and no storage, so it only writes to the console.\n this.degraded = mismatch || this.onServer();\n this.config = resolveConfig(this.allowed(input), this.diagnostics);\n this.explicitSecurityContext = Boolean(input.securityContext?.id);\n this.config.securityContext.id ||= newId(this.diagnostics);\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n this.identityBuiltAs = this.config.identity;\n this.stores =\n this.identityBuiltAs === \"memory\" || this.onServer() ? memoryStores() : BROWSER_STORES;\n this.identity = resolveIdentity(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionIdleMs,\n );\n this.sessionTouch = new SessionTouch(\n this.diagnostics,\n this.stores,\n this.config.correlation.sessionTouchMs,\n this.config.correlation.sessionIdleMs,\n );\n this.breadcrumbs = new BreadcrumbBuffer(this.config.capturePolicy.breadcrumbs);\n // Sample a span by its trace, so the whole trace stays or goes.\n const keeps = (traceId: string): boolean =>\n sampleKey(traceId, this.config.sampling.defaultRate);\n this.tracing = new TraceEngine(\n this.diagnostics,\n this.config.correlation.traceMaxAgeMs || Infinity,\n this.config.otelLoader,\n {\n enabled: () => this.config.tracesEndpoint !== \"\",\n keeps,\n onEnd: (ended) => {\n if (keeps(ended.traceId)) {\n this.recordSpan(rootSpan(ended));\n }\n },\n },\n );\n // Don't await. Without OTel, records use the ambient trace and nothing is lost.\n void this.tracing.loadOtel();\n // The startup values stick. A later configure() can't change the limits or the journey age.\n this.limits = { ...this.config.limits };\n this.console = new ConsoleSink(this.config.console, this.diagnostics, this.limits);\n this.drops = new DropReporter(this.config, this.diagnostics);\n this.journeyOptions = { ...JOURNEY_OPTIONS, maxAgeMs: this.config.journey.maxAgeMs };\n\n this.journey = new JourneyEngine(\n this.journeyOptions,\n this.diagnostics,\n this.identity.contextId,\n (journey) => {\n this.bus?.broadcastJourney(journey);\n },\n this.stores,\n );\n\n this.builder = new RecordBuilder({\n remote: this.remote,\n config: this.config,\n limits: this.limits,\n diagnostics: this.diagnostics,\n context: this.context,\n journey: this.journey,\n tracing: this.tracing,\n sequence: this.sequence,\n identity: this.identity,\n platform: this.platform,\n debug: this.debugBuffer,\n });\n\n this.meter = new Meter(\n () => this.config.batching.metricFlushIntervalMs,\n (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n this.diagnostics,\n this.config.metrics,\n );\n // The record builder exists now, so a diagnostic can become a record.\n this.diagnostics.setHandler(this.diagnosticHandler());\n this.syncProfiler();\n }\n\n /**\n * Returns the diagnostics handler. With diagnostics.records, it also sends every event as\n * a record.\n * @returns The handler, or undefined with no onDiagnostic and no diagnostic records.\n */\n private diagnosticHandler(): DiagnosticHandler | undefined {\n if (this.config.diagnostics.records === false) {\n return this.config.onDiagnostic;\n }\n\n return (event) => {\n this.recordDiagnostic(event);\n this.config.onDiagnostic?.(event);\n };\n }\n\n /**\n * Sends a diagnostic event as a record when diagnostics.records selects its code.\n * A diagnostic raised during that send produces no record, which stops a loop.\n * @param event Diagnostic event.\n */\n private recordDiagnostic(event: DiagnosticEvent): void {\n const { records } = this.config.diagnostics;\n const selected = records === true || (records !== false && records.includes(event.code));\n if (!selected || this.recordingDiagnostic) {\n return;\n }\n\n this.recordingDiagnostic = true;\n try {\n const write = NOTICE_CODES.has(event.code)\n ? this.diagnosticLogger.info\n : this.diagnosticLogger.warn;\n write(event.message, {\n \"diagnostic.code\": event.code,\n \"diagnostic.count\": event.count,\n \"diagnostic.detail\": recordDetail(event.detail),\n });\n } finally {\n this.recordingDiagnostic = false;\n }\n }\n\n /**\n * Adds a breadcrumb from app code. The data is copied now, so a later change to the app's\n * object doesn't change the trail.\n * @param message Description of the event. A JavaScript caller can pass a non-string, which\n * is converted.\n * @param data Optional metadata.\n */\n addBreadcrumb(message: unknown, data?: Record<string, unknown>): void {\n if (this.rotating || this.destroyed) return;\n // A message whose toString() throws, or a data getter that throws, must not throw into\n // the app's call.\n this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not add the breadcrumb.\",\n () => {\n const crumb: Breadcrumb = {\n t: Date.now(),\n category: \"custom\",\n message: truncate(String(message), this.limits.maxBodyChars),\n };\n\n if (data !== undefined) {\n const clean = sanitize(data, this.limits, this.diagnostics);\n crumb.data = isObject(clean) ? clean : { value: clean };\n }\n\n this.breadcrumbs.push(crumb);\n },\n );\n }\n\n /**\n * Adds a value to a counter or a histogram. The meter sends one point per interval.\n * @param def The instrument's definition.\n * @param value Value to add.\n * @param attributes The value's attribute set.\n */\n recordMetric(def: InstrumentDef, value: number, attributes?: MetricAttributes): void {\n // Guard against a value after shutdown, whose interval timer would outlive the runtime.\n if (!this.destroyed && !this.rotating) {\n this.meter.record(def, value, attributes);\n }\n }\n\n /**\n * Starts a timed operation. Its values are dropped if the runtime has shut down or a rotation\n * is running when it ends. With `securityContext.isolation`, a new delivery identity before\n * the end drops them too.\n * @param name Operation name.\n * @param attributes Attribute set for every histogram point.\n * @returns The operation's handle.\n */\n startMeasure(name: string, attributes?: MetricAttributes): Measure {\n const epoch = this.identityEpoch;\n const current = (): boolean =>\n !this.destroyed &&\n !this.rotating &&\n (!this.config.securityContext.isolation || this.identityEpoch === epoch);\n const copied = this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the attributes of the measure.\",\n () => ({ ...attributes }),\n );\n\n // The name's toString() can throw. If it does, the measure gets an empty name.\n const label = this.diagnostics.guard(\n \"record.sanitize_failed\",\n \"The library could not read the name of the measure.\",\n () => \"\".concat(name),\n );\n\n return createMeasure(label ?? \"\", copied ?? {}, this.tracing.request().span, {\n metric: (def, value, points) => {\n if (current()) {\n this.recordMetric(def, value, points);\n }\n },\n span: (span) => {\n if (current()) {\n this.recordSpan(span);\n }\n },\n });\n }\n\n /**\n * Builds and emits the record for one span. The console doesn't print it and minLevel\n * doesn't drop it. The trace engine already sampled the trace before the span existed.\n * @param span The span data.\n */\n private recordSpan(span: SpanData): void {\n if (this.config.tracesEndpoint === \"\") {\n return;\n }\n\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"span\",\n body: span.name,\n namespace: TRACE_NAMESPACE,\n payload: span.attributes,\n fixed: spanFields(span),\n trace: { traceId: span.traceId, spanId: span.spanId, traceFlags: TRACE_FLAGS_SAMPLED },\n });\n this.emit(record);\n }\n\n /**\n * Builds and emits the record for one aggregated point. The console doesn't print it.\n * @param name Metric name.\n * @param attributes The call's attributes. The record limits apply to them.\n * @param fields The point's metric fields. The record limits don't truncate them.\n */\n private emitPoint(\n name: string,\n attributes: MetricAttributes,\n fields: Record<string, unknown>,\n ): void {\n const { record } = this.builder.build({\n level: \"INFO\",\n type: \"metric\",\n body: name,\n namespace: METRIC_NAMESPACE,\n payload: attributes,\n fixed: fields,\n aggregated: true,\n });\n this.emit(record);\n }\n\n /**\n * Turns the profiler on or off to match profiler.enabled. Before switching off it sends the\n * points that are waiting, because the switch would otherwise drop them.\n */\n private syncProfiler(): void {\n const { enabled } = this.config.profiler;\n if (enabled === this.profilerOn) {\n return;\n }\n\n this.profilerOn = enabled;\n const core = profilerCore();\n if (!enabled) {\n core.collect(false);\n core.detach();\n return;\n }\n\n // Profiler points take the same path as meter points, so hooks and transports apply.\n const sink: ProfilerSink = {\n capacity: this.config.profiler.maxProbes,\n intervalMs: () => this.config.profiler.flushIntervalMs,\n emit: (name, attributes, fields) => {\n this.emitPoint(name, attributes, fields);\n },\n diagnostics: this.diagnostics,\n // Same rule as emit(): the first collect of a rotation still goes to the old sender.\n ready: () => !this.rotating || this.closingContext,\n outlier: (name, ms) => {\n this.breadcrumbs.push({\n t: Date.now(),\n category: \"profile\",\n message: `${name} ${String(Math.round(ms))} ms`,\n });\n },\n };\n core.attach(sink);\n }\n\n /**\n * Gives or withdraws consent for session replay, and starts or stops the recorder if the\n * capture is installed.\n * @param consent True starts the recorder, false stops it.\n */\n setReplay(consent: boolean): void {\n this.replayConsent = consent;\n\n if (consent) {\n void this.replay?.start();\n } else {\n this.replay?.stop();\n }\n }\n\n /**\n * Sends the open interval of the meter and the profiler. The profiler doesn't calibrate here,\n * which keeps flush and the exit path short and synchronous.\n */\n private collectPoints(): void {\n this.meter.collect();\n if (this.profilerOn) {\n profilerCore().collect(false);\n }\n }\n\n /**\n * Starts a new identity epoch. With isolation on, the profiler also drops its data and open\n * spans, so a span from the old identity can't add to the new one.\n */\n private advanceIdentity(): void {\n this.identityEpoch++;\n if (this.profilerOn && this.config.securityContext.isolation) {\n profilerCore().reset();\n }\n }\n\n /**\n * Checks the source policy before a direct child link opens.\n * @param source Child window.\n * @param origin The child window's origin.\n * @returns True if the bus allows this source.\n */\n readonly busCanAccept = (source: Window, origin: string): boolean =>\n this.bus?.isRegistered(source, origin) ?? false;\n\n /**\n * Receives direct messages from same-origin child frames.\n * @param message Inbound bus message.\n * @param reply Direct response callback.\n * @param source The child frame's window.\n */\n readonly busAccept = (message: BusMessage, reply: Receive, source?: Window): void => {\n if (this.destroyed) {\n return;\n }\n\n // Messages wait for the bus in arrival order, because a promise runs its callbacks in order.\n void this.ensureBus().then((bus) => {\n if (!bus || this.destroyed) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The bus could not accept a direct message from a child frame.\",\n () => {\n bus.acceptDirect(message, reply, source);\n },\n );\n });\n };\n\n /**\n * Returns the runtime on this realm's global key. Another copy of the library can own it.\n * @returns Pinned runtime instance or null.\n */\n private static pinned(): ObservabilityRuntime | null {\n return (\n ((globalThis as Record<symbol, unknown>)[RUNTIME_KEY] as ObservabilityRuntime | undefined) ??\n null\n );\n }\n\n /**\n * Returns this copy's local runtime, or the pinned runtime if there is none. A pinned\n * runtime from another version returns null, and a log call then starts the local runtime.\n * @returns Active runtime instance or null.\n */\n static current(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local) {\n return local.destroyed ? null : local;\n }\n\n const pinned = ObservabilityRuntime.pinned();\n return pinned && ownVersion(pinned) ? pinned : null;\n }\n\n /**\n * Returns the runtime that shutdown() stopped, until the next configure().\n * A stopped runtime from another version returns null.\n * @returns Stopped runtime instance or null.\n */\n static stopped(): ObservabilityRuntime | null {\n const local = ObservabilityRuntime.local;\n if (local?.destroyed) {\n return local;\n }\n\n const stopped = (globalThis as Record<symbol, unknown>)[STOPPED_KEY] as\n ObservabilityRuntime | undefined;\n return stopped && ownVersion(stopped) ? stopped : null;\n }\n\n /**\n * Checks whether shutdown() stopped this runtime.\n * @returns True once destroy() starts.\n */\n isDestroyed(): boolean {\n return this.destroyed;\n }\n\n /**\n * Initializes a new runtime instance or updates the existing singleton.\n * @param input Consumer configuration options.\n * @param implicit True for the default runtime that an early log call starts.\n * @returns Active runtime instance.\n */\n static configure(input: Partial<ObservabilityConfig>, implicit = false): ObservabilityRuntime {\n const local = ObservabilityRuntime.local;\n if (local && !local.destroyed) {\n // The local runtime stays console-only. React StrictMode calls configure() twice.\n local.reconfigure(input);\n return local;\n }\n ObservabilityRuntime.local = null;\n\n const pinned = ObservabilityRuntime.pinned();\n if (pinned) {\n // A runtime older than 0.9.0 has no sdkVersion, which also counts as another version.\n if (!ownVersion(pinned)) {\n return ObservabilityRuntime.startDegraded(input, pinned.sdkVersion);\n }\n\n if (!pinned.destroyed) {\n pinned.reconfigure(input);\n return pinned;\n }\n }\n\n const runtime = new ObservabilityRuntime(input);\n // The app's first configure() sets the limits of a default runtime.\n runtime.tunablesLocked = !implicit;\n (globalThis as Record<symbol, unknown>)[RUNTIME_KEY] = runtime;\n Reflect.deleteProperty(globalThis, STOPPED_KEY);\n void runtime.init();\n return runtime;\n }\n\n /**\n * Starts a console-only runtime next to another version's runtime. It sends nothing, joins\n * no bus and installs no capture. The other version keeps the page runtime.\n * @param input Consumer configuration options.\n * @param found The pinned runtime's sdkVersion. A runtime older than 0.9.0 has none.\n * @returns The local runtime.\n */\n private static startDegraded(\n input: Partial<ObservabilityConfig>,\n found: unknown,\n ): ObservabilityRuntime {\n const runtime = new ObservabilityRuntime(input, true);\n ObservabilityRuntime.local = runtime;\n\n const foundText = typeof found === \"string\" ? found : \"before 0.9.0\";\n runtime.mismatchVersion = foundText;\n runtime.diagnostics.report(\n \"runtime.version_mismatch\",\n `Another copy of the library, version ${foundText}, owns the page runtime. This copy, version ${TELEMETRY_SDK_VERSION}, runs in console-only mode and installs no capture. Load one version of the library on the page.`,\n { found: foundText, own: TELEMETRY_SDK_VERSION },\n );\n\n void runtime.init();\n return runtime;\n }\n\n /**\n * Updates runtime configuration and refreshes affected subsystems.\n * @param input Partial configuration to merge.\n */\n private reconfigure(input: Partial<ObservabilityConfig>): void {\n if (this.rotating) {\n this.diagnostics.report(\n \"config.locked\",\n \"Configuration cannot change during security-context rotation.\",\n );\n return;\n }\n if (this.config.lockConfiguration) {\n const next = resolveConfig(input, this.diagnostics, this.config);\n if (!sameConfig(this.config, next))\n this.diagnostics.report(\n \"config.locked\",\n \"Runtime configuration is locked. Use setConfigurationLocked(false) to unlock it explicitly.\",\n );\n return;\n }\n drainDeferred(this);\n const accepted = this.keepDestination(this.keepRouting(this.allowed(input)));\n // The first configure() after an implicit start is the app's startup, so its id is explicit.\n if (!this.tunablesLocked && accepted.securityContext?.id) {\n this.explicitSecurityContext = true;\n }\n for (const key of [\"correlation\", \"persistence\"] as const) {\n // The sender reads the namespace when it loads. Until then, the first configure() can set it.\n if (key === \"persistence\" && !this.tunablesLocked && this.senderLoad === undefined) {\n continue;\n }\n if (\n accepted[key] &&\n !sameConfig({ ...this.config[key], ...accepted[key] }, this.config[key])\n ) {\n this.diagnostics.report(\"config.invalid\", `${key} cannot change after startup.`);\n Object.assign(accepted, { [key]: this.config[key] });\n }\n }\n const next = resolveConfig(accepted, this.diagnostics, this.config);\n this.keepStartupTunables(next);\n const { redact, processors } = this.config;\n applyResolvedConfig(this.config, next);\n // A kept record only saw the hooks from its own log call. New hooks must not miss it.\n if (this.config.redact !== redact || this.config.processors !== processors) {\n this.debugBuffer.clear();\n }\n this.breadcrumbs.resize(this.config.capturePolicy.breadcrumbs);\n this.diagnostics.setHandler(this.diagnosticHandler());\n this.diagnostics.setPolicy(\n this.config.diagnostics.throttleMs,\n this.config.diagnostics.consoleFallback,\n );\n\n this.builder.invalidateResource();\n this.console.update(this.config.console);\n this.keepBuiltStorage();\n this.keepBuiltIdentity();\n // The handler and the resource are up to date now, and points and diagnostics use both.\n this.syncProfiler();\n\n // Reinstall only on a change, because a reinstall unpatches and repatches every host\n // function. A stale capture load stops at its generation check, so a reinstall is safe\n // at any time.\n this.refreshCaptures();\n\n if (this.roleResolved) {\n void this.syncSender();\n }\n\n this.diagnostics.report(\"config.reconfigured\", \"A later configure() call updated the runtime.\");\n }\n\n /**\n * Checks whether the runtime is on a server, for example Node during server-side rendering.\n * @returns True on Node.\n */\n private onServer(): boolean {\n return this.platform.platform === \"node\";\n }\n\n /**\n * Removes the delivery settings from a console-only runtime's input. On a server, it\n * reports a destination once.\n * @param input Consumer configuration options.\n * @returns The options the runtime accepts.\n */\n private allowed(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.degraded) {\n return input;\n }\n\n if (this.onServer() && !this.serverReported && sends(input)) {\n this.serverReported = true;\n this.diagnostics.report(\n \"config.invalid\",\n \"The library runs console-only on Node. It sends no record and installs no capture. It ignores endpoint, metricsEndpoint, tracesEndpoint, transport and transportWorker.\",\n );\n }\n\n return consoleOnly(input);\n }\n\n /**\n * Removes delivery and identity changes while isolation is on. The other settings still apply.\n * @param input Consumer configuration options.\n * @returns The options without the refused delivery or identity changes.\n */\n private keepRouting(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (!this.tunablesLocked || this.degraded || !this.config.securityContext.isolation) {\n return input;\n }\n\n // Compare resolved values. An unset endpoint keeps the current endpoint, so it isn't a\n // change. A separate reporter keeps the real resolve's diagnostics from being counted twice.\n const probe = resolveConfig(input, new Diagnostics(), this.config);\n const refused: string[] = ROUTING_KEYS.filter(\n (key) => !sameConfig(probe[key], this.config[key]),\n );\n if (probe.securityContext.id !== this.config.securityContext.id) {\n refused.push(\"securityContext.id\");\n }\n if (refused.length === 0) {\n return input;\n }\n\n const kept: Partial<ObservabilityConfig> = { ...input };\n for (const key of ROUTING_KEYS) {\n if (refused.includes(key)) {\n Reflect.deleteProperty(kept, key);\n }\n }\n if (refused.includes(\"securityContext.id\")) {\n const context = { ...input.securityContext };\n Reflect.deleteProperty(context, \"id\");\n kept.securityContext = context;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `Isolation refuses changes to ${refused.join(\", \")}. Use rotateSecurityContext() for these changes. To permit them, set securityContext.isolation: false in a separate configure() call. The other settings apply.`,\n );\n return kept;\n }\n\n /**\n * Restores the startup tunables in the next config. Each tunable is read once by some part\n * of the runtime, so a later change would have no effect and is refused.\n * @param next The resolved config from a later configure() call.\n */\n private keepStartupTunables(next: ResolvedConfig): void {\n if (this.senderLoad !== undefined) {\n this.keepSections(next, SENDER_SECTIONS);\n }\n\n // An early log call starts a runtime with defaults. The app's first configure() sets that\n // runtime's limits and journey age.\n if (!this.tunablesLocked) {\n this.tunablesLocked = true;\n Object.assign(this.limits, next.limits);\n this.journeyOptions.maxAgeMs = next.journey.maxAgeMs;\n return;\n }\n\n this.keepSections(next, [\"limits\"]);\n\n const { maxAgeMs } = this.config.journey;\n if (next.journey.maxAgeMs !== maxAgeMs) {\n this.diagnostics.report(\n \"config.invalid\",\n `journey.maxAgeMs cannot change after startup. It stays ${String(maxAgeMs)}.`,\n { requested: next.journey.maxAgeMs },\n );\n next.journey.maxAgeMs = maxAgeMs;\n }\n\n const { maxProbes } = this.config.profiler;\n if (next.profiler.maxProbes !== maxProbes) {\n this.diagnostics.report(\n \"config.invalid\",\n `profiler.maxProbes cannot change after startup. It stays ${String(maxProbes)}.`,\n { requested: next.profiler.maxProbes },\n );\n next.profiler.maxProbes = maxProbes;\n }\n }\n\n /**\n * Refuses a change to config sections by restoring the current values in the next config.\n * @param next The resolved config from a later configure() call.\n * @param sections Sections that can't change.\n */\n private keepSections(next: ResolvedConfig, sections: readonly StartupSection[]): void {\n for (const section of sections) {\n if (sameConfig(next[section], this.config[section])) {\n continue;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `${section} cannot change after startup. The current values stay.`,\n { requested: next[section] },\n );\n Object.assign(next, { [section]: this.config[section] });\n }\n }\n\n /**\n * Restores the built adapter's storage strategy. Every other key is read live, but the\n * adapter is built only once. A new adapter would strand the batches in the old one, and\n * that loss is worse than a refused change.\n */\n private keepBuiltStorage(): void {\n const built = this.storageBuiltAs;\n\n if (built === undefined || this.config.storage === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `storage cannot change after startup. It stays ${built}.`,\n { requested: this.config.storage },\n );\n this.config.storage = built;\n }\n\n /**\n * Refuses a change that leaves the built delivery stack with no destination.\n * Without one, the retry engine removes every stored batch as if it were delivered.\n * @param input Partial configuration to merge.\n * @returns Input without the refused changes.\n */\n private keepDestination(input: Partial<ObservabilityConfig>): Partial<ObservabilityConfig> {\n if (this.senderLoad === undefined) {\n return input;\n }\n\n let accepted = input;\n // The stack picks its transport once. A rotation can pick another one.\n for (const key of [\"transport\", \"transportWorker\"] as const) {\n const addsOrRemoves =\n key in input && (input[key] === undefined) !== (this.config[key] === undefined);\n if (addsOrRemoves) {\n this.diagnostics.report(\n \"config.invalid\",\n `You cannot add or remove ${key} after the delivery stack loads. The current transport stays.`,\n );\n accepted = { ...accepted };\n Reflect.deleteProperty(accepted, key);\n }\n }\n\n const removesEndpoint = accepted.endpoint === null || accepted.endpoint === \"\";\n\n if (removesEndpoint && this.config.transport === undefined) {\n this.diagnostics.report(\n \"config.invalid\",\n \"You cannot remove the endpoint after the delivery stack loads. The current endpoint stays.\",\n );\n // An undefined endpoint keeps the current endpoint, and keeps it in ignoreUrls.\n accepted = { ...accepted, endpoint: undefined };\n }\n\n return accepted;\n }\n\n /**\n * Restores the identity strategy from startup. The ids have existed since startup, and a\n * later change can't move them to another store.\n */\n private keepBuiltIdentity(): void {\n const built = this.identityBuiltAs;\n\n if (this.config.identity === built) {\n return;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `identity cannot change after startup. It stays ${built}.`,\n { requested: this.config.identity },\n );\n this.config.identity = built;\n }\n\n /** Initializes asynchronous subsystems and flushes the boot buffer. */\n private async init(): Promise<void> {\n // A console-only runtime never forwards, and Node has no addEventListener.\n if (!this.degraded) {\n addEventListener(\"pagehide\", this.onPageHide);\n }\n\n // Start the capture imports now so they download in parallel with the bus and the sender.\n const captures = this.installCaptures();\n\n // Set before the first await, so a flush() right after configure() waits for it.\n this.started = this.boot();\n await this.started;\n await captures;\n }\n\n /**\n * Resolves the bus role, loads the delivery stack and releases the boot records.\n * Never rejects.\n */\n private async boot(): Promise<void> {\n try {\n const journeyReady = this.journey.bootstrap();\n\n if (this.config.bus.mode !== \"off\") {\n await this.ensureBus();\n }\n\n this.roleResolved = true;\n await this.syncSender();\n await journeyReady;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"Startup failed. The runtime continues with reduced function.\",\n undefined,\n error,\n );\n } finally {\n // Release the boot records before the captures load, so the exit flush can find them.\n this.ready = true;\n this.releaseBootBuffer();\n }\n }\n\n /**\n * Starts the bus load once.\n * @returns Promise that resolves to the started bus, or null if it didn't load.\n */\n private ensureBus(): Promise<Bus | null> {\n this.busLoad ??= this.startBus();\n return this.busLoad;\n }\n\n /**\n * Loads and constructs the bus once. Does not call start().\n * @returns Promise that resolves to the constructed bus, or null if it didn't load.\n */\n private constructBus(): Promise<Bus | null> {\n this.busBuilt ??= this.buildBus();\n return this.busBuilt;\n }\n\n /**\n * Starts the constructed bus. Never rejects.\n * @returns Promise that resolves to the started bus, or null if it didn't load or start.\n */\n private async startBus(): Promise<Bus | null> {\n const bus = await this.constructBus();\n\n if (!bus) {\n return null;\n }\n\n try {\n await bus.start();\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not start. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /** Imports and constructs the bus. Never rejects. */\n private async buildBus(): Promise<Bus | null> {\n try {\n const { Bus } = await import(\"../bus/bus\");\n\n // A shutdown can happen during the load, and a bus on a destroyed runtime leaks its links.\n if (this.destroyed) {\n return null;\n }\n\n const bus = new Bus(\n this.config,\n this.diagnostics,\n this.platform,\n this.identity.contextId,\n this.identity.tabId,\n {\n onSecurityContext: (id) => {\n if (this.explicitSecurityContext && this.config.securityContext.id !== id) {\n this.contextMismatch = true;\n this.diagnostics.report(\n \"security.context_mismatch\",\n \"The configured security context differs from the upstream owner.\",\n );\n return false;\n }\n this.contextMismatch = false;\n if (this.config.securityContext.id !== id) {\n // The first owner id keeps the startup records and the app's context, because\n // those records had no other identity. A later change retires them, even before\n // ready.\n if (this.ownerAdopted) {\n drainDeferred(this);\n this.drops.add(\"security_context\", [\n ...this.bootBuffer.take(),\n ...this.pendingRecords.take(),\n ...this.forwardBuffer,\n ]);\n this.forwardBuffer = [];\n this.context.clear();\n this.breadcrumbs.clear();\n // collect() removes the open measurements, and emit() refuses them during this\n // reset.\n const rotating = this.rotating;\n this.rotating = true;\n this.collectPoints();\n // The profiler holds on to its data while emit() refuses records. Don't let the\n // old owner's data reach the new owner.\n if (this.profilerOn) {\n profilerCore().reset();\n }\n // A same-origin owner stores its new session before it sends the new id, so use\n // that session. Otherwise every frame starts a different session.\n const shared = this.sessionTouch.stored();\n this.resetSession(\n shared !== undefined && shared !== this.identity.sessionId\n ? shared\n : newId(this.diagnostics),\n );\n this.rotating = rotating;\n this.advanceIdentity();\n // The old owner's rules must not apply to the new identity.\n this.remote.sampling = null;\n this.refreshCaptures();\n }\n this.config.securityContext.id = id;\n }\n this.ownerAdopted = true;\n return true;\n },\n onRecords: (records) => {\n this.ingestForwarded(records);\n },\n onJourney: (journey) => {\n this.journey.applyRemote(journey);\n },\n onJourneyRequest: () => this.journey.current(),\n onTabConflict: () => {\n this.regenerateTabId();\n },\n remote: this.remote,\n },\n );\n\n this.bus = bus;\n\n return bus;\n } catch (error) {\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The bus did not load. This context sends its own records.\",\n undefined,\n error,\n );\n\n return null;\n }\n }\n\n /**\n * Reads the bus role. Without a bus, this context is the sender.\n * @returns Active bus role.\n */\n private role(): BusRole {\n return this.bus?.getRole() ?? \"sender\";\n }\n\n /**\n * Loads the delivery stack if this context is the sender and has a destination, that is an\n * endpoint or a custom transport.\n * @returns Promise that resolves when the load completes, or immediately when nothing loads.\n */\n private syncSender(): Promise<void> {\n if (!this.hasDestination() || this.role() !== \"sender\") {\n return Promise.resolve();\n }\n\n return this.loadSender();\n }\n\n /**\n * Checks whether the config names a destination for the records.\n * @returns True if it has an endpoint or a custom transport.\n */\n private hasDestination(): boolean {\n return Boolean(this.config.endpoint) || this.config.transport !== undefined;\n }\n\n /**\n * Starts the delivery stack load once.\n * @returns Promise that resolves when the load completes or fails.\n */\n private loadSender(): Promise<void> {\n this.senderLoad ??= this.buildSender();\n return this.senderLoad;\n }\n\n /**\n * Imports and builds the delivery stack, then moves the held records into it.\n * Never rejects.\n */\n private async buildSender(): Promise<void> {\n this.storageBuiltAs = this.config.storage;\n\n try {\n const { Sender } = await import(\"./sender\");\n const sender = this.destroyed\n ? null\n : await Sender.create({\n storage: this.memoryStorage,\n onStorage: (storage) => {\n if (storage.name === \"memory\") this.memoryStorage = storage;\n },\n onPersistence: (state) => {\n this.storagePersistence = state;\n },\n config: this.config,\n diagnostics: this.diagnostics,\n onGap: this.reportGap,\n onLoss: this.reportLoss,\n remote: this.remote,\n beforeExit: () => {\n drainDeferred(this);\n this.collectPoints();\n this.tracing.end();\n },\n });\n\n // Guard against a shutdown during the load. The stack must not outlive the runtime.\n if (!sender || this.destroyed) {\n await sender?.destroy();\n return;\n }\n\n this.sender = sender;\n } catch (error) {\n // Clear the load so a later configure() can try again.\n this.senderLoad = undefined;\n this.diagnostics.report(\n \"pipeline.crashed\",\n \"The delivery stack did not load. The library does not send records.\",\n { held: this.pendingRecords.length },\n error,\n );\n this.drops.add(\"load_failed\", this.pendingRecords.records);\n }\n\n for (const record of this.pendingRecords.take()) {\n this.sender?.push(record);\n }\n }\n\n /** Refreshes temporary switches and restores local settings when their TTL ends. */\n private refreshCaptures(): void {\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n if (this.destroyed) {\n return;\n }\n\n const wire = this.remote.sampling?.wire();\n if (wire) {\n this.remoteCaptureTimer = setTimeout(() => {\n this.refreshCaptures();\n }, wire.ttlMs);\n unrefTimer(this.remoteCaptureTimer);\n }\n\n if (this.captureState(this.effectiveCapture()) !== this.installedCaptureKey) {\n void this.installCaptures();\n }\n }\n\n /**\n * Serializes the current capture settings and profiler observers into one string. When the\n * string changes, the captures are reinstalled.\n * @param settings Current capture settings.\n * @returns The string.\n */\n private captureState(settings: CaptureOptions): string {\n const { enabled, framePhases, framePacing } = this.config.profiler;\n\n return `${captureKey(settings)}${String(enabled && framePhases)}${String(enabled && framePacing)}${this.replayState(settings)}`;\n }\n\n /**\n * Serializes what the replay recorder reads when it starts. The replay capture has its own\n * key because a restart drops the buffer, so an unrelated capture change must not cause one.\n * The other replay values are read on use and apply without a restart.\n * @param settings Current capture settings.\n * @returns The string. Empty while replay is off, so a replay change then installs nothing.\n */\n private replayState(settings: CaptureOptions): string {\n const { replay } = this.config;\n\n if (!replay.enabled) {\n return \"\";\n }\n\n // Functions and recordOptions go in by identity: a function doesn't stringify, and the\n // app's recordOptions can have a cycle or a throwing getter. The endpoint and onSegment are\n // in, so a buffer never goes to a destination it wasn't recorded for. fullUrls and\n // ignoreUrls are in because the kept capture reads them from its install-time settings,\n // and a buffer recorded with full URLs must not survive the app turning them off.\n // replay.headers stays out, so a refreshed token doesn't drop the buffer.\n return JSON.stringify([\n replay.loader && pluginId(replay.loader),\n replay.onSegment && pluginId(replay.onSegment),\n pluginId(replay.recordOptions),\n replay.endpoint,\n replay.requireConsent,\n replay.mode,\n replay.maskText,\n replay.maskInputs,\n replay.maskSelectors,\n replay.blockSelectors,\n replay.recordCanvas,\n replay.bufferMs,\n replay.plugins.map(pluginId),\n settings.fullUrls,\n settings.ignoreUrls.map(String),\n ]);\n }\n\n /** Returns local capture settings with the permitted remote switches. */\n private effectiveCapture(): CaptureOptions {\n const settings = { ...this.config.capture };\n const remote = this.remote.sampling?.current()?.capture;\n for (const key of REMOTE_CAPTURE_FLAGS) {\n const value = remote?.[key];\n if (settings.remoteToggles.includes(key) && value !== undefined) {\n if (value && typeof settings[key] === \"object\") {\n continue;\n }\n settings[key] = value;\n }\n }\n\n return settings;\n }\n\n /** Loads, builds and installs the enabled capture modules. Never rejects. */\n private async installCaptures(): Promise<void> {\n // A console-only runtime next to another version patches nothing. The other version does.\n if (this.degraded) {\n return;\n }\n\n const generation = ++this.captureGeneration;\n const settings = this.effectiveCapture();\n this.installedCaptureKey = this.captureState(settings);\n const replayKey = this.replayState(settings);\n\n // The recorder reads the live config whenever it starts, and newSession() or startReplay()\n // can restart it at any time. So once any install has asked for different settings, the\n // running recorder may no longer match the key it was built with, and it is never kept.\n if (replayKey !== this.replayBuiltKey) {\n this.replayBuiltKey = \"\";\n }\n\n // A running recorder whose start settings didn't change stays as it is. Reinstalling it\n // would drop the buffer, and with it the \"before\" of the next error.\n const kept = replayKey !== \"\" && replayKey === this.replayBuiltKey ? this.replay : undefined;\n const names: CaptureName[] = [];\n const { profiler } = this.config;\n\n if (settings.errors || settings.rejections || settings.resourceErrors) {\n names.push(\"errors\");\n }\n if (settings.fetch || settings.xhr) {\n names.push(\"network\");\n }\n if (settings.interactions || settings.navigation) {\n names.push(\"interactions\");\n }\n if (settings.webVitals) {\n names.push(\"webVitals\");\n }\n if (settings.longFrames) {\n names.push(\"longFrames\");\n }\n // An empty list wraps nothing, so don't load the chunk for it.\n const consoleOn = Array.isArray(settings.console)\n ? settings.console.length > 0\n : settings.console;\n\n if (consoleOn) {\n names.push(\"console\");\n }\n if (settings.uncleanExit) {\n names.push(\"uncleanExit\");\n }\n if (settings.userTiming) {\n names.push(\"userTiming\");\n }\n\n if (settings.reports) {\n names.push(\"reports\");\n }\n if (settings.resourceTiming) {\n names.push(\"resourceTiming\");\n }\n if (settings.lifecycle) {\n names.push(\"lifecycle\");\n }\n // The profiler's observers share one chunk, and it only loads with the profiler on.\n if (profiler.enabled && profiler.framePhases) {\n names.push(\"framePhases\");\n }\n if (profiler.enabled && profiler.framePacing) {\n names.push(\"framePacing\");\n }\n if (this.config.replay.enabled && !kept) {\n names.push(\"replay\");\n }\n\n const [classes, WebSocketCapture] = await Promise.all([\n Promise.all(names.map((name) => this.loadCapture(name))),\n settings.webSocket ? this.loadWebSocket() : undefined,\n ]);\n\n // Guard against a later install or a shutdown during the load. A stale capture would\n // leak its listeners.\n if (generation !== this.captureGeneration || this.destroyed) {\n return;\n }\n\n // Swap the old set for the new one in one synchronous step, leaving no gap without capture.\n this.uninstallCaptures(kept);\n\n const ctx: CaptureContext = {\n isActive: () => !this.destroyed && !this.rotating,\n config: Object.assign(Object.create(this.config) as ResolvedConfig, { capture: settings }),\n diagnostics: this.diagnostics,\n breadcrumbs: this.breadcrumbs,\n tracing: this.tracing,\n logger: new OneLogger(() => this, CAPTURE_NAMESPACE),\n once: this.captureOnce,\n recordMetric: (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n },\n recordSpan: (span) => {\n this.recordSpan(span);\n },\n sessionId: () => this.identity.sessionId,\n onError: (hook) => {\n this.errorHook = hook;\n },\n setContext: (key, value) => {\n if (value === undefined) {\n this.context.remove(key);\n } else {\n this.context.set(key, value);\n }\n },\n replayConsent: () => this.replayConsent,\n };\n\n classes.forEach((CaptureModule, index) => {\n if (CaptureModule) {\n const capture = new CaptureModule(ctx);\n this.captures.push(capture);\n\n // Find the replay capture by its loader, not by its name. A plugin could use that name.\n if (names[index] === \"replay\") {\n this.replay = capture as ReplayControl;\n this.replayBuiltKey = replayKey;\n }\n }\n });\n\n const plugins = WebSocketCapture\n ? [...settings.plugins, new WebSocketCapture(this.diagnostics, ctx.config)]\n : settings.plugins;\n\n for (const plugin of plugins) {\n this.captures.push(this.pluginCapture(plugin));\n }\n\n for (const capture of this.captures) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not install the ${capture.name} capture.`,\n () => {\n capture.install();\n },\n );\n }\n }\n\n /**\n * Uninstalls the active capture modules.\n * @param kept A replay capture that stays installed, if there is one.\n */\n private uninstallCaptures(kept?: ReplayControl): void {\n for (const capture of this.captures) {\n if (capture !== kept) {\n this.diagnostics.guard(\n \"capture.install_failed\",\n `The library could not uninstall the ${capture.name} capture.`,\n () => {\n capture.uninstall();\n },\n );\n }\n }\n this.captures.length = 0;\n this.replay = kept;\n\n if (kept) {\n this.captures.push(kept);\n }\n }\n\n /**\n * Imports the WebSocket capture plugin. A failed import is reported and skipped.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadWebSocket(): Promise<WebSocketClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the webSocket capture.\",\n async () => (await import(\"../capture/web-socket\")).WebSocketCapture,\n );\n }\n\n /**\n * Wraps a plugin as a capture module. The plugin only gets public tools.\n * @param plugin The app's plugin, or a built-in one.\n * @returns The capture module.\n */\n private pluginCapture(plugin: CapturePlugin): Capture {\n const { name } = plugin;\n const record: RecordMetric = (def, value, attributes) => {\n this.recordMetric(def, value, attributes);\n };\n const fault = (error: unknown): void => {\n this.diagnostics.report(\"config.invalid\", INSTRUMENT_OPTIONS_FAULT, undefined, error);\n };\n const ctx: PluginContext = {\n logger: new OneLogger(() => this, `${CAPTURE_NAMESPACE}.${name}`),\n counter: (metric, options = {}) => makeCounter(metric, options, record, fault),\n histogram: (metric, options = {}) => makeHistogram(metric, options, record, fault),\n addBreadcrumb: (message, data) => {\n this.addBreadcrumb(message, data);\n },\n ownRequest: runAsLibraryRequest,\n };\n\n return {\n name,\n install: () => {\n plugin.install(ctx);\n },\n uninstall: () => {\n plugin.uninstall();\n },\n };\n }\n\n /**\n * Imports one capture module. A failed import is reported and skips only that module.\n * @param name Capture module name.\n * @returns Promise that resolves to the class, or undefined if the import failed.\n */\n private loadCapture(name: CaptureName): Promise<CaptureClass | undefined> {\n return this.diagnostics.guardAsync(\n \"capture.install_failed\",\n `The library could not load the ${name} capture.`,\n CAPTURE_LOADERS[name],\n );\n }\n\n /**\n * Attaches a Web Worker or MessagePort to the bus for record forwarding.\n * @param worker Target Worker or MessagePort instance.\n */\n registerWorker(worker: WorkerLike, options: SourceOptions = {}): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n if (this.destroyed) {\n return () => undefined;\n }\n\n // Attach on construction, because the worker's handshake can time out while the bus starts.\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) {\n return;\n }\n\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not register the worker.\",\n () => {\n detach = bus.attachWorker(worker, options);\n },\n );\n\n // In bus.mode \"off\" startup didn't start the bus, so start it now.\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /**\n * Registers a frame after the bus loads. Early removal cancels the registration.\n * @param frame Child frame or window.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\n registerFrame(frame: HTMLIFrameElement | Window, options: FrameOptions): () => void {\n let cancelled = false;\n let detach: (() => void) | undefined;\n void this.constructBus().then((bus) => {\n if (!bus || this.destroyed || cancelled) return;\n detach = this.diagnostics.guard(\"bus.send_failed\", \"The frame could not be registered.\", () =>\n bus.registerFrame(frame, options),\n );\n void this.ensureBus();\n });\n return () => {\n cancelled = true;\n detach?.();\n };\n }\n\n /** Flushes pending telemetry, unregisters listeners, and unpins the runtime instance. */\n async destroy(): Promise<void> {\n if (this.destroyed) {\n return;\n }\n\n // The open interval's points and the root span go out with the final flush.\n drainDeferred(this);\n this.collectPoints();\n // After shutdown() probes stop reading the clock until the next configure().\n if (this.profilerOn) {\n this.profilerOn = false;\n profilerCore().detach();\n }\n this.tracing.end();\n this.destroyed = true;\n cancelDeferred(this);\n clearTimeout(this.remoteCaptureTimer);\n this.remoteCaptureTimer = undefined;\n\n if (!this.degraded) {\n removeEventListener(\"pagehide\", this.onPageHide);\n }\n\n this.uninstallCaptures();\n\n // Sender.destroy awaits a normal flush, then runs the exit flush. The records already\n // hold their journey, so the journey and the bus can stop first.\n const closing = this.sender?.destroy();\n this.journey.destroy();\n // A record in the forward buffer waits for its microtask, so the bus takes it before it stops.\n this.sendForwarded();\n this.bus?.destroy();\n // The delivery stack didn't load before shutdown(), so the held records are lost.\n this.drops.add(\"load_failed\", this.pendingRecords.take());\n await closing;\n // A load in progress destroys its own stack, and shutdown() resolves only after that.\n await this.senderLoad;\n await this.rotation?.catch(() => undefined);\n await this.memoryStorage?.close();\n\n // A local runtime must not remove the other version's runtime from the global key.\n if (ObservabilityRuntime.pinned() === this) {\n Reflect.deleteProperty(globalThis, RUNTIME_KEY);\n // Calls after shutdown() go to this runtime and do nothing.\n // A new default runtime would drop the app's settings.\n (globalThis as Record<symbol, unknown>)[STOPPED_KEY] = this;\n }\n }\n\n /**\n * Routes a completed log record to the pipeline or forward buffer.\n * @param record Log record to emit, or null when the build dropped it.\n */\n emit(record: LogRecord | null): void {\n if (!record || this.destroyed || (this.rotating && !this.closingContext)) {\n return;\n }\n\n this.sessionTouch.touch(this.identity.sessionId);\n\n // An error first sends the records that minLevel or sampling dropped before it.\n const error = record.severityText === \"ERROR\" || record.severityText === \"FATAL\";\n const records = error ? [...this.debugBuffer.drain(), record] : [record];\n\n // Session replay uploads its buffer on an error. The hook has its own guard.\n if (error) {\n this.errorHook?.(record);\n }\n\n for (const one of records) {\n if (this.ready) {\n this.route(one);\n } else {\n this.bootBuffer.push(one);\n }\n }\n }\n\n /**\n * Sends a record to the forward buffer or to the local pipeline, depending on the bus role.\n * @param record Log record to route.\n */\n private route(record: LogRecord): void {\n if (this.role() === \"forwarder\") {\n this.forward(record);\n return;\n }\n\n this.deliver(record);\n }\n\n /**\n * Hands a record to the delivery stack. Holds the record while the stack loads.\n * Drops the record when nothing loads, for example in console-only mode.\n * @param record Log record to deliver.\n */\n private deliver(record: LogRecord): void {\n if (this.sender) {\n this.sender.push(record);\n return;\n }\n\n // Console-only mode has no destination. Count the drop, otherwise no counter shows the loss.\n if (!this.senderLoad) {\n this.diagnostics.count(\"record.dropped_no_destination\");\n // After a failed load, the config has a destination but no delivery stack.\n if (this.hasDestination()) {\n this.drops.add(\"load_failed\", [record]);\n }\n return;\n }\n\n this.pendingRecords.push(record);\n }\n\n /**\n * Counts a record dropped by a full hold buffer and passes it to the onDrop report.\n * @param record Dropped record.\n */\n private dropHeld(record: LogRecord): void {\n this.diagnostics.count(\"record.dropped_boot_buffer_full\");\n this.drops.add(\"buffer_full\", [record]);\n }\n\n /**\n * Batches records for asynchronous transmission to the upstream sender.\n * @param record Log record to forward.\n */\n private forward(record: LogRecord): void {\n this.forwardBuffer.push(record);\n if (this.forwardScheduled) {\n return;\n }\n this.forwardScheduled = true;\n\n queueMicrotask(() => {\n this.forwardScheduled = false;\n this.sendForwarded();\n });\n }\n\n /** Hands the forward buffer's records to the bus. */\n private sendForwarded(): void {\n const records = this.forwardBuffer;\n this.forwardBuffer = [];\n if (records.length > 0) {\n this.bus?.sendRecords(records);\n }\n }\n\n /**\n * Validates, samples and queues records from child frames or workers. A forwarded record\n * arrives already built, so this is the first point in this context where sampling can run.\n * Local records are sampled by RecordBuilder.\n * @param records Inbound payload from bus.\n */\n private ingestForwarded(records: unknown): void {\n if (this.destroyed) return;\n if (!Array.isArray(records)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n return;\n }\n const accepted: LogRecord[] = [];\n for (const record of records) {\n if (!isLogRecord(record)) {\n this.diagnostics.count(\"record.dropped_malformed\");\n continue;\n }\n // A debug buffer record explains an error. Sampling by its key would drop it again.\n if (\n record.attributes[ATTR_DEBUG_BUFFER] !== true &&\n !shouldSample(record, this.config, this.remote.sampling?.current() ?? null)\n ) {\n this.diagnostics.count(\"record.dropped_by_sampling\");\n continue;\n }\n\n // A child context without redact forwards raw records, so the sender is the last gate.\n const redacted = this.builder.redactForwarded(record);\n if (redacted) {\n accepted.push(redacted);\n }\n }\n\n // Records that arrive while the context changes belong to neither identity. Report the\n // loss after sampling and redact, so onDrop never gets action names or journey ids that\n // redact masks.\n if (this.rotating) {\n this.drops.add(\"security_context\", accepted);\n return;\n }\n\n for (const record of accepted) {\n this.deliver(record);\n }\n }\n\n /** Flushes the startup records, adding the active journey to records that have none. */\n private releaseBootBuffer(): void {\n const buffered = this.bootBuffer.take();\n // The hooks have already seen every record, so a key added now would bypass redact.\n const { processors, redact } = this.config;\n const journey = processors.length === 0 && redact === undefined ? this.journey.current() : null;\n\n for (const record of buffered) {\n if (journey && !record.attributes[\"journey.id\"]) {\n record.attributes[\"journey.id\"] = journey.id;\n record.attributes[\"journey.name\"] = journey.name;\n }\n this.route(record);\n }\n }\n\n /**\n * Passes lost records to the onDrop report.\n * @param reason Why they were lost.\n * @param records Lost records.\n * @param batchIds Ids of the lost batches.\n */\n private readonly reportLoss: LossReporter = (reason, records, batchIds) => {\n this.drops.add(reason, records, batchIds);\n };\n\n /**\n * Passes the evicted batches to the onDrop report and emits a warning record. The warning\n * records are throttled.\n * @param result Storage prune summary metrics.\n * @param dropped The evicted batches.\n */\n private readonly reportGap = (result: PruneResult, dropped: readonly LogBatch[]): void => {\n this.drops.add(\n result.reason,\n dropped.flatMap((batch) => batch.records),\n dropped.map((batch) => batch.id),\n );\n\n const now = Date.now();\n if (now - this.lastGapAt < GAP_REPORT_THROTTLE_MS) {\n return;\n }\n this.lastGapAt = now;\n\n new OneLogger(() => this, STORAGE_NAMESPACE).warn(\n \"stored records were dropped before delivery\",\n {\n \"gap.batches\": result.batches,\n \"gap.records\": result.records,\n \"gap.reason\": result.reason,\n },\n );\n };\n\n /** Creates and stores a new tab ID after a tab ID collision. */\n private regenerateTabId(): void {\n const fresh = newId(this.diagnostics);\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"Another context uses this tab id. A duplicated tab is the usual cause. The library makes a new tab id.\",\n { was: this.identity.tabId, now: fresh },\n );\n\n (this.identity as { tabId: string }).tabId = fresh;\n persistTabId(fresh, this.diagnostics, this.stores);\n this.builder.invalidateResource();\n }\n\n /**\n * Starts a new session in this context. Sends the open metric points, starts a new trace,\n * ends the active journey and clears the breadcrumbs. Other tabs pick up the new id at\n * their next startup.\n */\n newSession(): void {\n if (this.destroyed) {\n return;\n }\n\n drainDeferred(this);\n this.resetSession(newId(this.diagnostics));\n }\n\n /**\n * Closes the old session's work and starts the given session.\n * @param sessionId Id of the session to start.\n */\n private resetSession(sessionId: string): void {\n // Close the old session's work first, so its points and root span keep the old id.\n this.collectPoints();\n this.tracing.rotate(\"explicit\");\n this.journey.end();\n // On a shared machine, the next user must not see the previous user's trail.\n this.breadcrumbs.clear();\n this.debugBuffer.clear();\n // The replay buffer still shows the previous user's page. Drop it and start a new recording.\n this.replay?.reset();\n\n (this.identity as { sessionId: string }).sessionId = sessionId;\n this.sessionTouch.restart(sessionId);\n this.builder.invalidateResource();\n }\n\n /**\n * Changes the delivery context in one operation. A second call while this one is running is\n * rejected.\n * @param update New identity, delivery settings and context attributes.\n * @param options What to do with the old context's records, and the flush deadline.\n * @returns Promise that resolves when the change completes. Invalid settings reject it.\n */\n rotateSecurityContext(\n update: SecurityContextUpdate,\n options: SecurityContextRotationOptions = {},\n ): Promise<void> {\n // Check the promise, not the flag. \"carry\" clears the flag before it stores old batches again.\n if (this.rotation)\n return Promise.reject(new Error(\"A security-context rotation is already running.\"));\n const pending = options.pending ?? \"discard\";\n const timeoutMs = options.timeoutMs ?? 5000;\n if (\n !isObject(update) ||\n !isObject(update.delivery) ||\n ![\"discard\", \"flush\", \"retain\", \"carry\"].includes(pending) ||\n !Number.isFinite(timeoutMs) ||\n timeoutMs < 0 ||\n (update.id !== undefined && (typeof update.id !== \"string\" || update.id.length === 0))\n ) {\n return Promise.reject(new Error(\"Invalid security-context rotation options.\"));\n }\n if (this.destroyed) return Promise.reject(new Error(\"The runtime has stopped.\"));\n drainDeferred(this);\n this.rotating = true;\n this.rotation = this.rotateContext(update, pending, timeoutMs).finally(() => {\n this.rotating = false;\n this.rotation = undefined;\n });\n return this.rotation;\n }\n\n /**\n * Checks the new settings, stops the old delivery and starts the new context.\n * @param update New identity, delivery settings and attributes.\n * @param pending What to do with the old records.\n * @param timeoutMs Maximum wait for an old-context flush, in milliseconds.\n * @returns Promise that resolves when the context change completes.\n */\n private async rotateContext(\n update: SecurityContextUpdate,\n pending: \"discard\" | \"flush\" | \"retain\" | \"carry\",\n timeoutMs: number,\n ): Promise<void> {\n await this.started;\n if (this.role() === \"forwarder\")\n throw new Error(\n \"Rotate the security context on the upstream owner, or use bus.mode: sender for an independent identity.\",\n );\n await this.senderLoad;\n const previous = this.config.securityContext.id;\n const nextId = update.id ?? newId(this.diagnostics);\n if (nextId === previous)\n throw new Error(\"A rotation requires a different security-context id.\");\n // Check the new settings before the old sender stops, so invalid settings keep the old sender.\n const delivery = { ...DELIVERY_RESET, ...update.delivery };\n const before = this.diagnostics.snapshot()[\"config.invalid\"] ?? 0;\n // The base has no old delivery values, so an invalid new value can't fall back to an old one.\n const next = resolveConfig(\n this.allowed({ ...delivery, securityContext: { id: nextId } }),\n this.diagnostics,\n { ...this.config, ...DELIVERY_RESET },\n );\n if ((this.diagnostics.snapshot()[\"config.invalid\"] ?? 0) !== before)\n throw new Error(\"Invalid delivery settings for the next security context.\");\n // Copy the context now, so a throwing getter rejects before the old sender stops.\n const context = update.context ? Object.fromEntries(Object.entries(update.context)) : undefined;\n\n // The base above has no endpoints, so remove the old endpoints from the ignore list here.\n // If they stayed, network capture would ignore calls to the old destination.\n const oldUrls = new Set<unknown>([\n this.config.endpoint,\n this.config.metricsEndpoint,\n this.config.tracesEndpoint,\n ]);\n const newUrls = new Set<unknown>([next.endpoint, next.metricsEndpoint, next.tracesEndpoint]);\n next.capture.ignoreUrls = next.capture.ignoreUrls.filter(\n (url) => !oldUrls.has(url) || newUrls.has(url),\n );\n\n this.closingContext = true;\n try {\n this.collectPoints();\n this.tracing.end();\n this.journey.end();\n } finally {\n this.closingContext = false;\n }\n const held = [...this.bootBuffer.take(), ...this.pendingRecords.take(), ...this.forwardBuffer];\n this.forwardBuffer = [];\n const old = this.sender;\n this.sender = undefined;\n this.senderLoad = undefined;\n const retired = (await old?.retire(pending, timeoutMs, previous)) ?? {\n buffered: [],\n stored: [],\n };\n if (this.destroyed) return;\n const live = [...held, ...retired.buffered];\n const stored = retired.stored.flatMap((batch) => batch.records);\n if (pending !== \"retain\" && pending !== \"carry\") {\n this.drops.add(\"security_context\", [...live, ...stored]);\n }\n // Keep a lock change the app made during the rotation.\n next.lockConfiguration = this.config.lockConfiguration;\n // Replace all delivery settings together. Don't keep old credentials or signal endpoints.\n applyResolvedConfig(this.config, next);\n this.advanceIdentity();\n this.remote.sampling = null;\n this.refreshCaptures();\n this.context.clear();\n if (context) this.context.setMany(context);\n this.breadcrumbs.clear();\n this.newSession();\n this.builder.invalidateResource();\n await this.syncSender();\n this.bus?.rotateContext();\n // New calls go to the new sender from here, so a long carry drops no logger call and the\n // report below can produce a record.\n this.rotating = false;\n if (pending === \"carry\") {\n await this.carry(live, retired.stored);\n }\n this.diagnostics.report(\"security.rotated\", \"The runtime rotated its security context.\", {\n pending,\n });\n }\n\n /**\n * Moves the old context's records into the new context.\n * @param live Records that were in memory. They go through the live buffer.\n * @param stored Batches that were stored. The new sender stores them again.\n * @returns Promise that resolves once the stored batches are stored again.\n */\n private async carry(live: LogRecord[], stored: LogBatch[]): Promise<void> {\n for (const record of live) {\n this.route(record);\n }\n\n // The live buffer doesn't take the stored backlog, which would exceed the buffer budget.\n // Without a new sender, the stored batches stay parked under the old id and nothing is lost.\n if (this.sender) {\n await this.sender.adopt(stored, this.config.securityContext.id);\n }\n }\n\n /**\n * Collects this runtime's state for a support ticket. The app decides where to send it.\n * @param health Health snapshot from the facade, with the logger cache counts.\n * @returns Promise that resolves to the JSON-safe bundle.\n */\n async debugBundle(health: ObservabilityHealth): Promise<DebugBundle> {\n const { configSummary } = await import(\"./debug-bundle\");\n // Build the breadcrumbs as a record so the privacy hooks run, as they do for an error record.\n const { record } = this.builder.build(\n {\n level: \"INFO\",\n type: \"system\",\n body: \"debug bundle\",\n namespace: DIAGNOSTICS_NAMESPACE,\n payload: { [ATTR_BREADCRUMBS]: this.breadcrumbs.snapshot() },\n },\n true,\n );\n const attributes = record?.attributes ?? {};\n const crumbs = attributes[ATTR_BREADCRUMBS];\n const pageUrl = attributes[ATTR_PAGE_URL];\n\n return {\n createdAt: new Date().toISOString(),\n sdkVersion: this.sdkVersion,\n health,\n diagnostics: this.diagnostics.snapshot(),\n resource: record?.resource ?? {},\n pageUrl: typeof pageUrl === \"string\" ? pageUrl : \"\",\n breadcrumbs: Array.isArray(crumbs) ? crumbs : [],\n debugBuffer: this.debugBuffer.snapshot(),\n config: configSummary(this.config, this.limits, this.diagnostics),\n };\n }\n\n /**\n * Reads this runtime's state. Doesn't wait for startup or for the sender to load.\n * @returns State, delivery counts and policies. The facade adds the logger cache counts.\n */\n async health(): Promise<Omit<ObservabilityHealth, \"loggerCache\">> {\n const delivery = this.sender?.stats() ?? { pending: 0, inFlight: 0, lastSendAt: null };\n const issues: ObservabilityHealth[\"issues\"] = [];\n if (this.mismatchVersion) issues.push(\"runtime.version_mismatch\");\n if (this.contextMismatch) issues.push(\"security.context_mismatch\");\n if (this.ready && this.hasDestination() && this.role() === \"sender\" && !this.sender)\n issues.push(\"sender.unavailable\");\n const {\n sourcePolicy,\n validation,\n maxMessageBytes,\n maxRecordsPerMessage,\n maxMessagesPerSecond,\n maxTrackedSources,\n } = this.config.bus;\n return {\n ...delivery,\n pending:\n delivery.pending +\n this.bootBuffer.length +\n this.pendingRecords.length +\n this.forwardBuffer.length,\n stored: (await this.sender?.queueDepth()) ?? 0,\n sdkVersion: this.sdkVersion,\n owningSdkVersion: this.mismatchVersion,\n status: this.destroyed\n ? \"stopped\"\n : this.rotating\n ? \"rotating\"\n : issues.length\n ? \"degraded\"\n : !this.ready\n ? \"starting\"\n : \"ready\",\n mode:\n this.role() === \"forwarder\"\n ? \"forwarder\"\n : this.hasDestination()\n ? \"sender\"\n : \"console-only\",\n senderReady: this.sender !== undefined && !this.destroyed && !this.rotating,\n configurationLocked: this.config.lockConfiguration,\n issues,\n securityContext: { ...this.config.securityContext },\n storagePersistence: this.storagePersistence,\n bus: {\n sourcePolicy,\n validation,\n maxMessageBytes,\n maxRecordsPerMessage,\n maxMessagesPerSecond,\n maxTrackedSources,\n },\n };\n }\n\n /**\n * Reads this context's delivery state.\n * @returns Promise that resolves to the counts and the time of the last accepted send.\n */\n async stats(): Promise<DeliveryStats> {\n // queueDepth() waits for a loading delivery stack. By then the held records are in the\n // pipeline.\n const stored = await this.queueDepth();\n const delivery = this.sender?.stats() ?? { pending: 0, inFlight: 0, lastSendAt: null };\n const held = this.bootBuffer.length + this.pendingRecords.length + this.forwardBuffer.length;\n\n return { ...delivery, pending: delivery.pending + held, stored };\n }\n\n /**\n * Removes the stored records for one context, or for all contexts in the application\n * namespace.\n * @param scope Which part of storage to clear.\n * @returns Promise that resolves when removal completes.\n */\n async clearPersisted(scope: \"context\" | \"namespace\"): Promise<void> {\n await this.senderLoad;\n if (this.sender) {\n await this.sender.clearPersisted(scope, this.config.securityContext.id);\n return;\n }\n const [\n { createStorage, storageName },\n { ContextStorage },\n { storageLimits },\n { clearEmergencyContext },\n ] = await Promise.all([\n import(\"../storage/factory\"),\n import(\"../storage/context-storage\"),\n import(\"../models/storage\"),\n import(\"../storage/emergency-queue\"),\n ]);\n const namespace = this.config.persistence.namespace;\n const backing =\n this.memoryStorage ??\n (await createStorage(\n this.config.storage,\n storageName(namespace),\n storageLimits(this.config.retention),\n this.diagnostics,\n undefined,\n namespace,\n ));\n const store = new ContextStorage(backing, this.config.securityContext, namespace);\n try {\n if (scope === \"namespace\") await store.clearNamespace();\n else await store.clear();\n clearEmergencyContext(\n this.config.securityContext.id,\n this.diagnostics,\n namespace,\n scope === \"namespace\",\n );\n } finally {\n if (backing !== this.memoryStorage) await store.close();\n }\n }\n\n /**\n * Counts the batches held in storage after a failed or deferred delivery.\n * @returns Promise that resolves to the number of stored batches. A forwarder stores\n * nothing and reports 0.\n */\n async queueDepth(): Promise<number> {\n await this.senderLoad;\n return (await this.sender?.queueDepth()) ?? 0;\n }\n\n /**\n * Flushes all pending records in the pipeline or forward buffer.\n * @returns Promise that resolves once the queued records are sent or handed off.\n */\n async flush(): Promise<void> {\n drainDeferred(this);\n this.collectPoints();\n\n // A record logged during startup waits in the boot buffer, and flush() would miss it\n // without this wait. After startup, don't wait, so the forward buffer handover stays\n // synchronous.\n if (!this.ready) {\n await this.started;\n }\n\n if (this.role() === \"forwarder\") {\n this.sendForwarded();\n return;\n }\n\n await this.senderLoad;\n await this.sender?.flush();\n }\n}\n\n/**\n * Compares resolved settings without JSON conversion. Functions are compared by identity.\n * The seen map keeps a cycle from causing repeated comparisons.\n * @param a First value.\n * @param b Second value.\n * @param seen Object pairs already compared.\n * @returns True if the values are equal.\n */\nfunction sameConfig(a: unknown, b: unknown, seen = new WeakMap<object, object>()): boolean {\n if (Object.is(a, b)) return true;\n if (a instanceof RegExp && b instanceof RegExp) return String(a) === String(b);\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) return false;\n if (seen.has(a)) return seen.get(a) === b;\n seen.set(a, b);\n const ak = Object.keys(a);\n const bk = Object.keys(b);\n return (\n ak.length === bk.length &&\n ak.every(\n (key) => Object.hasOwn(b, key) && sameConfig(Reflect.get(a, key), Reflect.get(b, key), seen),\n )\n );\n}\n","import {\n TELEMETRY_SDK_VERSION,\n TRANSPORT_WORKER_PROTOCOL,\n TRANSPORT_WORKER_REFUSAL,\n TRANSPORT_WORKER_TYPE,\n} from \"../constants\";\nimport { Diagnostics, type DiagnosticHandler } from \"../core/diagnostics\";\nimport { isObject } from \"../utils/guards\";\n\nlet active: (() => void) | undefined;\n\n/** Installs the worker service synchronously before its delivery module loads. */\nexport function serveTransportWorker(\n options: { onDiagnostic?: DiagnosticHandler } = {},\n): () => void {\n if (active) {\n return active;\n }\n const diagnostics = new Diagnostics(options.onDiagnostic);\n if (typeof document !== \"undefined\" || typeof addEventListener !== \"function\") {\n diagnostics.report(\"config.invalid\", \"Call serveTransportWorker() in a dedicated worker.\");\n return () => undefined;\n }\n\n let stopped = false;\n let port: MessagePort | undefined;\n let detach: (() => void) | undefined;\n const onMessage = (event: MessageEvent<unknown>): void => {\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport worker could not read its connection.\",\n () => {\n const message = event.data;\n if (\n !isObject(message) ||\n message.p !== TRANSPORT_WORKER_PROTOCOL ||\n message.t !== TRANSPORT_WORKER_TYPE.connect\n ) {\n return;\n }\n if (event.ports.length === 0) {\n return;\n }\n const incoming = event.ports[0];\n if (port || message.v !== TELEMETRY_SDK_VERSION) {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n return;\n }\n\n port = incoming;\n void import(\"./worker-server\")\n .then((module) => {\n if (!stopped) {\n detach = module.serveWorkerPort(incoming, diagnostics);\n }\n })\n .catch((error: unknown) => {\n diagnostics.report(\n \"transport.http_error\",\n \"The transport worker delivery module could not load.\",\n undefined,\n error,\n );\n diagnostics.guard(\n \"transport.http_error\",\n \"The failed transport port could not be closed.\",\n () => {\n incoming.postMessage(TRANSPORT_WORKER_REFUSAL);\n incoming.close();\n },\n );\n });\n },\n );\n };\n\n const stop = (): void => {\n if (stopped) {\n return;\n }\n stopped = true;\n active = undefined;\n removeEventListener(\"message\", onMessage);\n detach?.();\n diagnostics.guard(\n \"transport.http_error\",\n \"The transport service could not close its port.\",\n () => {\n port?.postMessage(TRANSPORT_WORKER_REFUSAL);\n },\n );\n diagnostics.guard(\"transport.http_error\", \"The transport port could not close.\", () => {\n port?.close();\n });\n };\n addEventListener(\"message\", onMessage);\n active = stop;\n return stop;\n}\n","// src/transport/memory-transport.ts\n//\n// A transport for tests that keeps every batch in memory, so a test can check the records the\n// library sends without a network or a fetch mock.\n\nimport { HTTP_SUCCESS_END, HTTP_SUCCESS_MIN } from \"../constants\";\nimport type { Transport, TransportRequest, TransportResponse } from \"../models/config\";\nimport type { LogRecord } from \"../models/log-record\";\n\n/** A transport for tests that keeps every batch in memory. */\nexport interface MemoryTransport {\n /** Pass this function as `transport` to `configure()`. */\n transport: Transport;\n /**\n * Returns the records of every accepted batch, in send order.\n * @returns The accepted records.\n */\n records(): LogRecord[];\n /**\n * Returns every request, accepted or refused, in send order.\n * @returns The requests.\n */\n batches(): TransportRequest[];\n /** Forgets every batch. The answer set with respondWith stays. */\n clear(): void;\n /**\n * Sets the answer for all later batches. The default answer is 200.\n * @param status Status code to answer with, for example 413, 429 or 500.\n * @param retryAfterMs Delay to answer with, for 429 and 503.\n */\n respondWith(status: number, retryAfterMs?: number): void;\n}\n\n/**\n * Creates a transport that keeps every batch in memory. Use it in tests, with `configure()`.\n * @returns The memory transport.\n */\nexport function createMemoryTransport(): MemoryTransport {\n const sent: TransportRequest[] = [];\n const accepted: TransportRequest[] = [];\n let answer: TransportResponse = { status: HTTP_SUCCESS_MIN };\n\n return {\n transport: (request) => {\n sent.push(request);\n\n if (answer.status >= HTTP_SUCCESS_MIN && answer.status < HTTP_SUCCESS_END) {\n accepted.push(request);\n }\n\n return Promise.resolve({ ...answer });\n },\n records: () => accepted.flatMap((request) => [...request.records]),\n batches: () => [...sent],\n clear: () => {\n sent.length = 0;\n accepted.length = 0;\n },\n respondWith: (status, retryAfterMs) => {\n answer = retryAfterMs === undefined ? { status } : { status, retryAfterMs };\n },\n };\n}\n","// src/index.ts\n//\n// The library's public entry point. Exports the facade API, the logging primitives and\n// the types.\n\nimport type { WorkerLike } from \"./bus/links\";\nimport type { Journey } from \"./core/journey\";\nimport { INSTRUMENT_OPTIONS_FAULT } from \"./constants\";\nimport { OneLogger, type OneLoggerOptions } from \"./core/logger\";\nimport { makeCounter, makeHistogram } from \"./core/meter\";\nimport { profilerCore } from \"./core/profiler\";\nimport { ObservabilityRuntime } from \"./core/runtime\";\nimport type { ObservabilityConfig } from \"./models/config\";\nexport type {\n ReplayLoader,\n ReplayPluginLoader,\n ReplayPluginTools,\n ReplaySegment,\n} from \"./models/replay\";\nimport type { SecurityContextUpdate, SecurityContextRotationOptions } from \"./models/config\";\nimport type { DebugBundle, ObservabilityHealth } from \"./models/health\";\nimport type { FrameOptions, SourceOptions } from \"./models/bus\";\nexport type { FrameOptions, SourceOptions, BusPermission } from \"./models/bus\";\nimport type { MetricType } from \"./models/log-record\";\nimport type { DeliveryStats } from \"./models/stats\";\nimport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n Profiler,\n} from \"./models/metric\";\n\nexport { OneLogger };\nexport { serveTransportWorker } from \"./transport/worker-entry\";\nexport { createMemoryTransport, type MemoryTransport } from \"./transport/memory-transport\";\nexport type { Journey, ObservabilityConfig, OneLoggerOptions };\nexport type {\n DeliveryPolicy,\n BufferingPolicy,\n MetricsPolicy,\n CorrelationPolicy,\n DiagnosticsPolicy,\n PersistencePolicy,\n MetadataPolicy,\n CapturePolicy,\n DebugBufferPolicy,\n ProfilerPolicy,\n ReplayPolicy,\n BusOptions,\n CaptureOptions,\n InteractionOptions,\n ResourceTimingOptions,\n RemoteCaptureFlag,\n LoggerCacheOptions,\n SecurityContextOptions,\n SecurityContextUpdate,\n SecurityContextRotationOptions,\n DeliveryOptions,\n ConsoleOptions,\n ConsoleStyles,\n ExitTransport,\n Transport,\n TransportRequest,\n TransportResponse,\n} from \"./models/config\";\nexport type { DebugBundle, ObservabilityHealth } from \"./models/health\";\nexport type { WorkerLike } from \"./bus/links\";\nexport type { DiagnosticCode, DiagnosticEvent } from \"./core/diagnostics\";\nexport type { DropSummary, LossReason } from \"./models/drop\";\nexport type { LogLevel, LogRecord, LogType, MetricType } from \"./models/log-record\";\nexport type {\n Counter,\n Histogram,\n HistogramOptions,\n InstrumentOptions,\n Measure,\n MetricAttributes,\n Probe,\n ProbeOptions,\n Profiler,\n} from \"./models/metric\";\nexport type { CapturePlugin, PluginContext } from \"./models/plugin\";\nexport type { LogSerializer, SerializedBatch } from \"./models/serializer\";\nexport type { DeliveryStats } from \"./models/stats\";\nexport type { StorageAdapter } from \"./models/storage\";\n\n/**\n * Cached loggers, keyed by namespace. A scoped logger never goes in this map.\n * A logger looks up the runtime on every write, so the cache stays valid across\n * configure() and shutdown().\n */\nconst loggers = new Map<string, OneLogger>();\n\n/**\n * Returns the active runtime. After shutdown() that is the stopped runtime, which does\n * nothing. Before the first configure(), it starts a runtime with default settings.\n * @returns Runtime instance.\n */\nfunction requireRuntime(): ObservabilityRuntime {\n const runtime = ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped();\n if (runtime) {\n return runtime;\n }\n\n // Start a default runtime, so a log call before configure() doesn't throw.\n return ObservabilityRuntime.configure({}, true);\n}\n\n/**\n * Removes stored logs. Records and requests that are still pending can write to storage again\n * afterwards.\n * @param scope Whose stored records to remove: the context's or the namespace's.\n * @returns Promise that resolves once the logs are removed.\n */\nexport function clearPersistedLogs(scope: \"context\" | \"namespace\" = \"context\"): Promise<void> {\n if (![\"context\", \"namespace\"].includes(scope))\n return Promise.reject(new Error(\"Invalid persistence scope.\"));\n return requireRuntime().clearPersisted(scope);\n}\n\n/**\n * Initializes or reconfigures the observability runtime.\n * With `payloadMode: \"defer\"`, logger records are built in idle time. With the debug buffer on,\n * they are still built at the call.\n * @param config Consumer configuration options.\n */\nexport function configure(config: Partial<ObservabilityConfig>): void {\n ObservabilityRuntime.configure(config);\n trimLoggerCache();\n}\n\n/**\n * Locks or unlocks the configuration. The lock isn't access control against other code on\n * this origin.\n * @param locked True to refuse changes through configure().\n */\nexport function setConfigurationLocked(locked: boolean): void {\n requireRuntime().setConfigurationLocked(locked);\n}\n\n/**\n * Stops delivery for the old context and starts it for the new one.\n * @param update New identity, delivery settings and context attributes.\n * @param options What to do with old records, and the flush deadline.\n * @returns Promise that resolves once the change is complete.\n */\nexport function rotateSecurityContext(\n update: SecurityContextUpdate,\n options?: SecurityContextRotationOptions,\n): Promise<void> {\n return requireRuntime().rotateSecurityContext(update, options);\n}\n\n/**\n * Reads this SDK copy's runtime state, delivery counts and policies.\n * @returns Promise that resolves to the current state.\n */\nexport async function getHealth(): Promise<ObservabilityHealth> {\n const runtime = requireRuntime();\n trimLoggerCache();\n return {\n ...(await runtime.health()),\n loggerCache: { ...runtime.config.loggerCache, size: loggers.size },\n };\n}\n\n/**\n * Collects the library's state for a support ticket. The bundle holds the health, the\n * diagnostic counters, the resource, the breadcrumbs, the debug buffer and a config summary.\n * The summary has no headers and no URL query, and a plugin or custom serializer shows up by\n * name only. The breadcrumbs go through the privacy hooks. A debug buffer record keeps its\n * context attributes. Where the bundle gets sent is up to the app.\n * @returns Promise that resolves to a JSON-safe bundle.\n */\nexport async function collectDebugBundle(): Promise<DebugBundle> {\n const health = await getHealth();\n return requireRuntime().debugBundle(health);\n}\n\n/**\n * Removes the least recently used loggers until the cache is within its limit.\n * @returns Cache limit, or null for no limit.\n */\nfunction trimLoggerCache(): number | null {\n const limit = (ObservabilityRuntime.current() ?? ObservabilityRuntime.stopped())?.config\n .loggerCache.maxEntries;\n const max = limit === undefined ? 256 : limit;\n if (max !== null) {\n // A Map keeps insertion order, so the first keys are the least recently used loggers.\n for (const key of loggers.keys()) {\n if (loggers.size <= max) {\n break;\n }\n loggers.delete(key);\n }\n }\n return max;\n}\n\n/**\n * Returns the cached logger for a namespace, or a new scoped logger.\n * @param namespace Application subsystem or module namespace.\n * @param options Context attributes for this logger only.\n * @returns Logger for the namespace. You get a new logger if you pass options or the cache\n * is disabled.\n */\nexport function getLogger(namespace: string, options?: OneLoggerOptions): OneLogger {\n const max = trimLoggerCache();\n if (options || max === 0) return new OneLogger(requireRuntime, namespace, options);\n\n let logger = loggers.get(namespace);\n\n logger ??= new OneLogger(requireRuntime, namespace);\n\n // Move a cached logger to the end, so the first entry is always the least recently used.\n loggers.delete(namespace);\n loggers.set(namespace, logger);\n trimLoggerCache();\n\n return logger;\n}\n\n/**\n * Returns the default root logger.\n * @returns The OneLogger for the \"app\" namespace.\n */\nfunction root(): OneLogger {\n return getLogger(\"app\");\n}\n\n/**\n * Logs a trace-level debug record.\n * @param message Detail message.\n * @param payload Optional context attributes.\n */\nexport function trace(message: string, payload?: Record<string, unknown>): void {\n root().trace(message, payload);\n}\n\n/**\n * Logs a debug-level record.\n * @param message Detail message.\n * @param payload Optional context attributes.\n */\nexport function debug(message: string, payload?: Record<string, unknown>): void {\n root().debug(message, payload);\n}\n\n/**\n * Logs an informational record.\n * @param message Informational message.\n * @param payload Optional context attributes.\n */\nexport function info(message: string, payload?: Record<string, unknown>): void {\n root().info(message, payload);\n}\n\n/**\n * Logs a warning record.\n * @param message Warning message.\n * @param payload Optional context attributes.\n */\nexport function warn(message: string, payload?: Record<string, unknown>): void {\n root().warn(message, payload);\n}\n\n/**\n * Logs an error record, with the error that caused it and the breadcrumbs.\n * @param message Error summary.\n * @param err The caught error or reason.\n * @param payload Optional context attributes.\n */\nexport function error(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().error(message, err, payload);\n}\n\n/**\n * Logs a fatal record, with the error that caused it and the breadcrumbs.\n * @param message Fatal error summary.\n * @param err The caught error or reason.\n * @param payload Optional context attributes.\n */\nexport function fatal(message: string, err?: unknown, payload?: Record<string, unknown>): void {\n root().fatal(message, err, payload);\n}\n\n/**\n * Logs a single user action.\n * @param name Action identifier.\n * @param payload Optional action attributes.\n */\nexport function logAction(name: string, payload?: Record<string, unknown>): void {\n root().logAction(name, payload);\n}\n\n/**\n * Logs an application lifecycle or domain event.\n * @param name Event identifier.\n * @param payload Optional event attributes.\n */\nexport function logEvent(name: string, payload?: Record<string, unknown>): void {\n root().logEvent(name, payload);\n}\n\n/**\n * Logs a numeric metric measurement.\n * @param name Metric identifier.\n * @param value Measured value.\n * @param unit Unit of measurement.\n * @param type Metric type.\n * @param attributes Optional metric attributes.\n */\nexport function logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attributes?: Record<string, unknown>,\n): void {\n root().logMetric(name, value, unit, type, attributes);\n}\n\n/**\n * Reports instrument options the library couldn't read. Without a runtime there is nowhere to\n * report to, so it does nothing.\n * @param error What reading the options threw.\n */\nfunction optionsFault(error: unknown): void {\n ObservabilityRuntime.current()?.diagnostics.report(\n \"config.invalid\",\n INSTRUMENT_OPTIONS_FAULT,\n undefined,\n error,\n );\n}\n\n/**\n * Returns a counter. Values are summed in memory, and every interval the library sends one\n * point per attribute set. A handle stays valid across configure() and shutdown().\n * @param name Metric name.\n * @param options Unit of the values.\n * @returns The counter.\n */\nexport function counter(name: string, options: InstrumentOptions = {}): Counter {\n return makeCounter(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Returns a histogram. Values are counted into buckets in memory, and every interval the\n * library sends one point per attribute set. A handle stays valid across configure() and\n * shutdown().\n * @param name Metric name.\n * @param options Unit of the values and the bucket boundaries.\n * @returns The histogram.\n */\nexport function histogram(name: string, options: HistogramOptions = {}): Histogram {\n return makeHistogram(\n name,\n options,\n (def, value, attributes) => {\n requireRuntime().recordMetric(def, value, attributes);\n },\n optionsFault,\n );\n}\n\n/**\n * Times an operation with named phases. Every phase and the total go into duration histograms.\n * With `tracesEndpoint` set, the operation is also a span with one child span per phase.\n * @param name Operation name. Every name creates one series.\n * @param attributes Attribute set for every histogram point. Keep it small.\n * @returns The operation's handle.\n */\nexport function startMeasure(name: string, attributes?: MetricAttributes): Measure {\n return requireRuntime().startMeasure(name, attributes);\n}\n\n/**\n * Starts the session replay recorder. With `replay.requireConsent` set, nothing is recorded\n * until you call this, so call it once the user agrees. Does nothing while `replay.enabled`\n * is false.\n */\nexport function startReplay(): void {\n requireRuntime().setReplay(true);\n}\n\n/**\n * Stops the session replay recorder and drops any replay events that haven't been sent. With\n * `replay.requireConsent` set, the recorder stays off until the next `startReplay()`.\n */\nexport function stopReplay(): void {\n requireRuntime().setReplay(false);\n}\n\n/**\n * Times spans of app code with probes. A probe is a named handle with `begin()`, `end()`,\n * `endAfterPaint()` and `record()`, and `time()` times a single function call. Once per\n * interval the library sends one `ui.profile.duration` histogram for every probe that has data.\n *\n * The profiler is off by default. Set `profiler.enabled` to true to turn it on. While it is\n * off, probes don't read the clock. After `shutdown()` a probe does nothing until a later\n * `configure()` turns the profiler back on. Probes stay valid across `configure()` and\n * `shutdown()`, and you can create them before `configure()`. No call ever throws.\n * @example\n * const render = profiler.probe(\"grid.render\");\n * const token = render.begin();\n * drawGrid();\n * render.end(token);\n */\nexport const profiler: Profiler = {\n // Probe calls report to whichever runtime is current. Once shutdown() resolves, the stopped\n // runtime gets nothing.\n probe: (name, options) =>\n profilerCore().probe(name, options, ObservabilityRuntime.current()?.diagnostics),\n time: (name, fn) => profilerCore().time(name, fn, ObservabilityRuntime.current()?.diagnostics),\n};\n\n/**\n * Times a synchronous function and logs a duration metric.\n * @param label Metric name prefix.\n * @param fn Synchronous function to time.\n * @param attributes Optional context attributes.\n * @returns Whatever the timed function returns.\n */\nexport function timeSync<T>(label: string, fn: () => T, attributes?: Record<string, unknown>): T {\n return root().timeSync(label, fn, attributes);\n}\n\n/**\n * Times an asynchronous function and logs a duration metric.\n * @param label Metric name prefix.\n * @param fn Asynchronous function to time.\n * @param attributes Optional context attributes.\n * @returns Promise that resolves to the timed function's result.\n */\nexport function timeAsync<T>(\n label: string,\n fn: () => Promise<T>,\n attributes?: Record<string, unknown>,\n): Promise<T> {\n return root().timeAsync(label, fn, attributes);\n}\n\n/**\n * Adds a breadcrumb to the trail. The next error record carries the trail.\n * @param message Description of the event.\n * @param data Optional metadata. It is copied right away.\n */\nexport function addBreadcrumb(message: string, data?: Record<string, unknown>): void {\n requireRuntime().addBreadcrumb(message, data);\n}\n\n/**\n * Sets a key-value pair on the ambient context. Every later record includes it.\n * @param key Attribute key.\n * @param value Attribute value.\n */\nexport function setContext(key: string, value: unknown): void {\n requireRuntime().context.set(key, value);\n}\n\n/**\n * Merges several key-value pairs into the ambient context.\n * @param values Key-value map of attributes to add.\n */\nexport function setContextMap(values: Record<string, unknown>): void {\n requireRuntime().context.setMany(values);\n}\n\n/**\n * Removes an attribute from the ambient context.\n * @param key Attribute key to delete.\n */\nexport function removeContext(key: string): void {\n requireRuntime().context.remove(key);\n}\n\n/**\n * Starts a new journey correlation context.\n * @param name Journey workflow identifier.\n * @param options `parent` links the active journey as the parent. `id` sets the journey id, a\n * string of 1 to 64 letters, digits, \"_\", \".\", \":\" or \"-\". Without it, the library generates one.\n * @returns The started Journey.\n */\nexport function startJourney(name: string, options?: { parent?: boolean; id?: string }): Journey {\n return requireRuntime().journey.start(name, options);\n}\n\n/** Ends the active journey correlation context. */\nexport function endJourney(): void {\n requireRuntime().journey.end();\n}\n\n/**\n * Returns the active journey, or null if none is in progress.\n * @returns The active Journey, or null.\n */\nexport function currentJourney(): Journey | null {\n return requireRuntime().journey.current();\n}\n\n/**\n * Serializes the active journey's metadata into a URL token that another context can adopt.\n * @returns The token, or undefined if no journey is active.\n */\nexport function getJourneyToken(): string | undefined {\n return requireRuntime().journey.getToken();\n}\n\n/**\n * Adopts a serialized journey token in this application realm.\n * @param token Serialized journey token.\n * @returns True if the token is valid and the runtime adopted it.\n */\nexport function adoptJourney(token: string): boolean {\n return requireRuntime().journey.adopt(token, \"manual\", true);\n}\n\n/**\n * Connects a Web Worker or MessagePort to the document bus, so its records get routed.\n * @param worker The Worker or MessagePort to connect.\n * @param options The worker's permissions. Defaults to \"records\".\n * @returns Function that removes this registration.\n */\nexport function registerWorker(worker: WorkerLike, options?: SourceOptions): () => void {\n return requireRuntime().registerWorker(worker, options);\n}\n\n/**\n * Registers one frame or window at an exact origin.\n * @param frame Child frame or window to register.\n * @param options Expected origin and source permissions.\n * @returns Function that removes this registration.\n */\nexport function registerFrame(\n frame: HTMLIFrameElement | Window,\n options: FrameOptions,\n): () => void {\n return requireRuntime().registerFrame(frame, options);\n}\n\n/** Rotates the trace context to begin a new distributed trace. */\nexport function startTrace(): void {\n requireRuntime().tracing.rotate(\"explicit\");\n}\n\n/**\n * Returns the W3C traceparent headers to put on an outgoing HTTP request.\n * @returns Map of trace header names to values.\n */\nexport function getTraceHeaders(): Record<string, string> {\n return requireRuntime().tracing.headers();\n}\n\n/**\n * Builds any deferred calls and flushes the pending batches of every pipeline stream.\n * @returns Promise that resolves once the pipeline has processed the queued batches.\n */\nexport function flush(): Promise<void> {\n return requireRuntime().flush();\n}\n\n/**\n * Counts the batches waiting in storage for delivery.\n * @returns Promise that resolves to the number of stored batches. A forwarder doesn't store\n * batches, so it reports 0.\n */\nexport function getQueueDepth(): Promise<number> {\n return requireRuntime().queueDepth();\n}\n\n/**\n * Reads this context's delivery state.\n * @returns Promise that resolves to the records waiting, the records in requests, the batches\n * in storage and the time of the last accepted send. A forwarder reports only its own buffers.\n */\nexport function getStats(): Promise<DeliveryStats> {\n return requireRuntime().stats();\n}\n\n/**\n * Starts a new correlation in this tab. Ends the active journey and starts a new trace. Other\n * tabs pick up the new id at their next startup. For a logout or a tenant change, use\n * rotateSecurityContext().\n */\nexport function newSession(): void {\n requireRuntime().newSession();\n}\n\n/**\n * Returns a snapshot of the cumulative diagnostic event counts.\n * @returns Map of diagnostic codes to how often each one occurred.\n */\nexport function getDiagnosticCounters(): Record<string, number> {\n return requireRuntime().diagnostics.snapshot();\n}\n\n/**\n * Flushes pending records and stops every runtime subsystem. A request still open after the\n * final flush is cancelled, and its stored batch stays in storage.\n * @returns Promise that resolves once shutdown is complete.\n */\nexport async function shutdown(): Promise<void> {\n await ObservabilityRuntime.current()?.destroy();\n}\n"],"mappings":"A,ylBAYA,SAASwJ,EAAQ,EAA2B,CAC1C,OAAO,KAAK,OAAO,YAAY,IAAI,EAAIC,GAAazJ,EAAAA,CAAkB,EAAIA,EAAAA,CAC5E,CAUA,SAAS0J,EACP,EACA,EACA,EACA,EACA,EACM,CACNC,EAAO,UAAU,GAAGC,EAAM,WAAYC,EAAU,KAAM,YAAa,CACjE,SACA,GAAGC,CACL,CAAC,CACH,CAUA,SAASC,EACP,EACA,EACA,EACA,EACA,EACM,CAEN,IAAMF,EAAWL,EAAQC,CAAS,EAClCE,EAAO,MAAM,GAAGC,EAAM,SAAUI,EAAO,CACrC,qBAAsBH,EACtB,OAAQ,UACR,GAAGC,CACL,CAAC,EACDJ,EAAOC,EAAQC,EAAOC,EAAU,UAAWC,CAAU,CACvD,CAUA,SAAgB7J,EACd,EACA,EACA,EACA,EACG,CACH,IAAMwJ,EAAY,YAAY,IAAI,EAClC,GAAI,CACF,IAAMS,EAASC,EAAG,EAElB,OADAT,EAAOC,EAAQC,EAAOJ,EAAQC,CAAS,EAAG,UAAWK,CAAU,EACxDI,CACT,OAASF,EAAO,CAGd,MADAD,EAAKJ,EAAQC,EAAOH,EAAWO,EAAOF,CAAU,EAC1CE,CACR,CACF,CAUA,eAAsB9J,GACpB,EACA,EACA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