@utk09/ui-observability 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/CHANGELOG.md +111 -219
  2. package/README.md +24 -26
  3. package/dist/{batch-CXmPmTse.js → batch-120Kc9jr.js} +3 -3
  4. package/dist/{batch-CXmPmTse.js.map → batch-120Kc9jr.js.map} +1 -1
  5. package/dist/{batch-mmPigCpi.cjs → batch-C3uNp5kU.cjs} +2 -2
  6. package/dist/{batch-mmPigCpi.cjs.map → batch-C3uNp5kU.cjs.map} +1 -1
  7. package/dist/bus/bus.d.cts +31 -2
  8. package/dist/bus/bus.d.ts +31 -2
  9. package/dist/bus-Dj8IEVcC.cjs +2 -0
  10. package/dist/bus-Dj8IEVcC.cjs.map +1 -0
  11. package/dist/{bus-C39wspFV.js → bus-DyNafxZN.js} +127 -104
  12. package/dist/bus-DyNafxZN.js.map +1 -0
  13. package/dist/capture/errors.d.cts +10 -0
  14. package/dist/capture/errors.d.ts +10 -0
  15. package/dist/capture/interactions.d.cts +35 -3
  16. package/dist/capture/interactions.d.ts +35 -3
  17. package/dist/capture/observed-windows.d.cts +51 -0
  18. package/dist/capture/observed-windows.d.ts +51 -0
  19. package/dist/capture/replay.d.cts +1 -1
  20. package/dist/capture/replay.d.ts +1 -1
  21. package/dist/capture/types.d.cts +5 -0
  22. package/dist/capture/types.d.ts +5 -0
  23. package/dist/capture/web-vitals.d.cts +1 -0
  24. package/dist/capture/web-vitals.d.ts +1 -0
  25. package/dist/{compression-tVtXwVjX.js → compression-BWkDWY3v.js} +2 -2
  26. package/dist/{compression-tVtXwVjX.js.map → compression-BWkDWY3v.js.map} +1 -1
  27. package/dist/{compression-CvED_Jel.cjs → compression-CEVe7NPX.cjs} +2 -2
  28. package/dist/{compression-CvED_Jel.cjs.map → compression-CEVe7NPX.cjs.map} +1 -1
  29. package/dist/config-C0PtemvC.cjs +2 -0
  30. package/dist/config-C0PtemvC.cjs.map +1 -0
  31. package/dist/config-DK1Zf7jn.js +556 -0
  32. package/dist/config-DK1Zf7jn.js.map +1 -0
  33. package/dist/{console-BGgGnjSi.js → console-CAyCQOpm.js} +5 -5
  34. package/dist/{console-BGgGnjSi.js.map → console-CAyCQOpm.js.map} +1 -1
  35. package/dist/{console-CSZ5_Vx5.cjs → console-Dk6GH4yj.cjs} +2 -2
  36. package/dist/{console-CSZ5_Vx5.cjs.map → console-Dk6GH4yj.cjs.map} +1 -1
  37. package/dist/{constants-CUyd9cTZ.js → constants-CEHN6KuY.js} +46 -25
  38. package/dist/constants-CEHN6KuY.js.map +1 -0
  39. package/dist/constants-NtiQDWL_.cjs +2 -0
  40. package/dist/constants-NtiQDWL_.cjs.map +1 -0
  41. package/dist/constants.d.cts +23 -0
  42. package/dist/constants.d.ts +23 -0
  43. package/dist/core/config.d.cts +9 -3
  44. package/dist/core/config.d.ts +9 -3
  45. package/dist/core/diagnostics.d.cts +1 -1
  46. package/dist/core/diagnostics.d.ts +1 -1
  47. package/dist/core/pipeline.d.cts +11 -0
  48. package/dist/core/pipeline.d.ts +11 -0
  49. package/dist/core/record.d.cts +2 -2
  50. package/dist/core/record.d.ts +2 -2
  51. package/dist/core/rotation.d.cts +26 -2
  52. package/dist/core/rotation.d.ts +26 -2
  53. package/dist/core/runtime.d.cts +9 -0
  54. package/dist/core/runtime.d.ts +9 -0
  55. package/dist/core/sender.d.cts +3 -2
  56. package/dist/core/sender.d.ts +3 -2
  57. package/dist/{debug-bundle-BXIlwDKM.cjs → debug-bundle-DMzUfiQc.cjs} +2 -2
  58. package/dist/{debug-bundle-BXIlwDKM.cjs.map → debug-bundle-DMzUfiQc.cjs.map} +1 -1
  59. package/dist/{debug-bundle-CRpYV_ui.js → debug-bundle-w78W46zr.js} +4 -4
  60. package/dist/{debug-bundle-CRpYV_ui.js.map → debug-bundle-w78W46zr.js.map} +1 -1
  61. package/dist/doctor.cjs +1 -1
  62. package/dist/doctor.js +36 -36
  63. package/dist/doctor.js.map +1 -1
  64. package/dist/errors-07pmZ7VY.cjs +3 -0
  65. package/dist/errors-07pmZ7VY.cjs.map +1 -0
  66. package/dist/{errors-BE_EZV7Q.js → errors-C-LYbqyB.js} +27 -24
  67. package/dist/errors-C-LYbqyB.js.map +1 -0
  68. package/dist/{factory-CTi0Is3F.js → factory-BHYrcSaU.js} +39 -28
  69. package/dist/factory-BHYrcSaU.js.map +1 -0
  70. package/dist/factory-DsaNdcXp.cjs +2 -0
  71. package/dist/factory-DsaNdcXp.cjs.map +1 -0
  72. package/dist/{identity-DdhKgrpk.js → identity-Byh3gCdT.js} +35 -24
  73. package/dist/identity-Byh3gCdT.js.map +1 -0
  74. package/dist/identity-BzAzdQyv.cjs +2 -0
  75. package/dist/identity-BzAzdQyv.cjs.map +1 -0
  76. package/dist/index.cjs +1 -1
  77. package/dist/index.cjs.map +1 -1
  78. package/dist/index.d.cts +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +453 -417
  81. package/dist/index.js.map +1 -1
  82. package/dist/{indexeddb-storage-GHdl0t8A.js → indexeddb-storage-BYywz-v6.js} +17 -17
  83. package/dist/{indexeddb-storage-GHdl0t8A.js.map → indexeddb-storage-BYywz-v6.js.map} +1 -1
  84. package/dist/{indexeddb-storage-CL9uqBCy.cjs → indexeddb-storage-BfqGkLFe.cjs} +2 -2
  85. package/dist/{indexeddb-storage-CL9uqBCy.cjs.map → indexeddb-storage-BfqGkLFe.cjs.map} +1 -1
  86. package/dist/interactions-BXzEel4F.cjs +2 -0
  87. package/dist/interactions-BXzEel4F.cjs.map +1 -0
  88. package/dist/interactions-DdKPMWIN.js +207 -0
  89. package/dist/interactions-DdKPMWIN.js.map +1 -0
  90. package/dist/{journey-B4Adltjm.cjs → journey-BUmsrgaw.cjs} +2 -2
  91. package/dist/{journey-B4Adltjm.cjs.map → journey-BUmsrgaw.cjs.map} +1 -1
  92. package/dist/{journey-D2_sia57.js → journey-Nu655gEO.js} +14 -14
  93. package/dist/{journey-D2_sia57.js.map → journey-Nu655gEO.js.map} +1 -1
  94. package/dist/{library-console-CPW6bvZH.cjs → library-console-DdIlzzph.cjs} +2 -2
  95. package/dist/{library-console-CPW6bvZH.cjs.map → library-console-DdIlzzph.cjs.map} +1 -1
  96. package/dist/{library-console-Btrzt814.js → library-console-amePMnP8.js} +2 -2
  97. package/dist/{library-console-Btrzt814.js.map → library-console-amePMnP8.js.map} +1 -1
  98. package/dist/{library-request-BJ9PLRaD.js → library-request-Cv7C05jf.js} +2 -2
  99. package/dist/{library-request-BJ9PLRaD.js.map → library-request-Cv7C05jf.js.map} +1 -1
  100. package/dist/{library-request-D7OvTxZV.cjs → library-request-DO3Ec7KE.cjs} +2 -2
  101. package/dist/{library-request-D7OvTxZV.cjs.map → library-request-DO3Ec7KE.cjs.map} +1 -1
  102. package/dist/{lifecycle-IaAm1mOC.cjs → lifecycle-B5yfH5is.cjs} +2 -2
  103. package/dist/{lifecycle-IaAm1mOC.cjs.map → lifecycle-B5yfH5is.cjs.map} +1 -1
  104. package/dist/{lifecycle-22CUCrc9.js → lifecycle-CMHz2Zbs.js} +2 -2
  105. package/dist/{lifecycle-22CUCrc9.js.map → lifecycle-CMHz2Zbs.js.map} +1 -1
  106. package/dist/{log-record-BNiLfqtL.js → log-record-B_nSqxoe.js} +2 -2
  107. package/dist/{log-record-BNiLfqtL.js.map → log-record-B_nSqxoe.js.map} +1 -1
  108. package/dist/{log-record-CkivuiEl.cjs → log-record-Bdywwg0k.cjs} +2 -2
  109. package/dist/{log-record-CkivuiEl.cjs.map → log-record-Bdywwg0k.cjs.map} +1 -1
  110. package/dist/{long-frames-DNFaRnC3.js → long-frames-6NGl1-uN.js} +3 -3
  111. package/dist/{long-frames-DNFaRnC3.js.map → long-frames-6NGl1-uN.js.map} +1 -1
  112. package/dist/{long-frames-BUUbXd-B.cjs → long-frames-D9DfSWqv.cjs} +2 -2
  113. package/dist/{long-frames-BUUbXd-B.cjs.map → long-frames-D9DfSWqv.cjs.map} +1 -1
  114. package/dist/models/bus.d.cts +6 -1
  115. package/dist/models/bus.d.ts +6 -1
  116. package/dist/models/config.d.cts +27 -11
  117. package/dist/models/config.d.ts +27 -11
  118. package/dist/models/serializer.d.cts +3 -1
  119. package/dist/models/serializer.d.ts +3 -1
  120. package/dist/{network-CGMLQ-mA.cjs → network-BNHBI0Fc.cjs} +2 -2
  121. package/dist/{network-CGMLQ-mA.cjs.map → network-BNHBI0Fc.cjs.map} +1 -1
  122. package/dist/{network-on2zZT6H.js → network-Cc3tSB7e.js} +5 -5
  123. package/dist/{network-on2zZT6H.js.map → network-Cc3tSB7e.js.map} +1 -1
  124. package/dist/observed-windows-8JtCsIr1.js +64 -0
  125. package/dist/observed-windows-8JtCsIr1.js.map +1 -0
  126. package/dist/observed-windows-BlE25nrn.cjs +2 -0
  127. package/dist/observed-windows-BlE25nrn.cjs.map +1 -0
  128. package/dist/openfin-Bxelt0yg.js.map +1 -1
  129. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  130. package/dist/{otlp-DimfrRor.js → otlp-Btix3EBa.js} +7 -7
  131. package/dist/{otlp-DimfrRor.js.map → otlp-Btix3EBa.js.map} +1 -1
  132. package/dist/{otlp-BENHf3g9.cjs → otlp-CFSW-Dno.cjs} +2 -2
  133. package/dist/{otlp-BENHf3g9.cjs.map → otlp-CFSW-Dno.cjs.map} +1 -1
  134. package/dist/patch-DlcKzIi-.cjs +2 -0
  135. package/dist/patch-DlcKzIi-.cjs.map +1 -0
  136. package/dist/patch-Sr1wKg7W.js +9 -0
  137. package/dist/patch-Sr1wKg7W.js.map +1 -0
  138. package/dist/platform-BZjp9wp1.cjs +2 -0
  139. package/dist/platform-BZjp9wp1.cjs.map +1 -0
  140. package/dist/platform-Dba6R3Hp.js +75 -0
  141. package/dist/platform-Dba6R3Hp.js.map +1 -0
  142. package/dist/{profiler-BAZoh7A4.js → profiler-DNKcqu09.js} +60 -60
  143. package/dist/{profiler-BAZoh7A4.js.map → profiler-DNKcqu09.js.map} +1 -1
  144. package/dist/{profiler-D4tJpDRc.cjs → profiler-DpoPi1hH.cjs} +2 -2
  145. package/dist/{profiler-D4tJpDRc.cjs.map → profiler-DpoPi1hH.cjs.map} +1 -1
  146. package/dist/{profiler-frames-C4xr7KfH.cjs → profiler-frames-C9zJNd8_.cjs} +2 -2
  147. package/dist/{profiler-frames-C4xr7KfH.cjs.map → profiler-frames-C9zJNd8_.cjs.map} +1 -1
  148. package/dist/{profiler-frames-cJMx9wNM.js → profiler-frames-CGXZeZ_3.js} +16 -16
  149. package/dist/{profiler-frames-cJMx9wNM.js.map → profiler-frames-CGXZeZ_3.js.map} +1 -1
  150. package/dist/{remote-rules-Dz9MRAsB.js → remote-rules-DNK96vLa.js} +25 -25
  151. package/dist/{remote-rules-Dz9MRAsB.js.map → remote-rules-DNK96vLa.js.map} +1 -1
  152. package/dist/{remote-rules-_tY0zj5o.cjs → remote-rules-DuMFRlit.cjs} +2 -2
  153. package/dist/{remote-rules-_tY0zj5o.cjs.map → remote-rules-DuMFRlit.cjs.map} +1 -1
  154. package/dist/replay-Cab-lSit.cjs +2 -0
  155. package/dist/replay-Cab-lSit.cjs.map +1 -0
  156. package/dist/{replay-Ds-ANH34.js → replay-Dy6OiaOZ.js} +104 -77
  157. package/dist/replay-Dy6OiaOZ.js.map +1 -0
  158. package/dist/{reports-BDSe4dFH.cjs → reports-CGK9YQch.cjs} +2 -2
  159. package/dist/{reports-BDSe4dFH.cjs.map → reports-CGK9YQch.cjs.map} +1 -1
  160. package/dist/{reports-C-thq-bk.js → reports-CX57-S9s.js} +3 -3
  161. package/dist/{reports-C-thq-bk.js.map → reports-CX57-S9s.js.map} +1 -1
  162. package/dist/{resource-timing-eUl2dNgC.js → resource-timing-CWVDCbrY.js} +4 -4
  163. package/dist/{resource-timing-eUl2dNgC.js.map → resource-timing-CWVDCbrY.js.map} +1 -1
  164. package/dist/{resource-timing-C576gFIQ.cjs → resource-timing-DalulXiR.cjs} +2 -2
  165. package/dist/{resource-timing-C576gFIQ.cjs.map → resource-timing-DalulXiR.cjs.map} +1 -1
  166. package/dist/response-body-Cpz5__4g.cjs +3 -0
  167. package/dist/response-body-Cpz5__4g.cjs.map +1 -0
  168. package/dist/{response-body-eoSQpLiH.js → response-body-yi92Rpvo.js} +109 -109
  169. package/dist/response-body-yi92Rpvo.js.map +1 -0
  170. package/dist/{rotation-Cwct4ckk.js → rotation-ChBbNDE2.js} +27 -28
  171. package/dist/rotation-ChBbNDE2.js.map +1 -0
  172. package/dist/rotation-fTnNJcfH.cjs +2 -0
  173. package/dist/rotation-fTnNJcfH.cjs.map +1 -0
  174. package/dist/{sampling-BlrI8jor.js → sampling-DZTOD28D.js} +16 -16
  175. package/dist/{sampling-BlrI8jor.js.map → sampling-DZTOD28D.js.map} +1 -1
  176. package/dist/{sampling-mXt4dstx.cjs → sampling-wAVJIZXp.cjs} +2 -2
  177. package/dist/{sampling-mXt4dstx.cjs.map → sampling-wAVJIZXp.cjs.map} +1 -1
  178. package/dist/{sanitize-Ba0KqU06.js → sanitize-B2GKlSFp.js} +2 -2
  179. package/dist/{sanitize-Ba0KqU06.js.map → sanitize-B2GKlSFp.js.map} +1 -1
  180. package/dist/{sanitize-DQyiI_KY.cjs → sanitize-BZdhoghq.cjs} +2 -2
  181. package/dist/{sanitize-DQyiI_KY.cjs.map → sanitize-BZdhoghq.cjs.map} +1 -1
  182. package/dist/{sender-Dv8rAmpV.js → sender-BRSpc7R8.js} +192 -178
  183. package/dist/sender-BRSpc7R8.js.map +1 -0
  184. package/dist/sender-CFu98DAB.cjs +2 -0
  185. package/dist/sender-CFu98DAB.cjs.map +1 -0
  186. package/dist/storage/emergency-queue.d.cts +3 -1
  187. package/dist/storage/emergency-queue.d.ts +3 -1
  188. package/dist/storage/stored-context.d.cts +3 -2
  189. package/dist/storage/stored-context.d.ts +3 -2
  190. package/dist/stored-context-CPLlzgpm.cjs +2 -0
  191. package/dist/stored-context-CPLlzgpm.cjs.map +1 -0
  192. package/dist/{stored-context-B2EzVuYm.js → stored-context-df1dEnht.js} +12 -10
  193. package/dist/stored-context-df1dEnht.js.map +1 -0
  194. package/dist/{storm-DjKetLKZ.js → storm-U3_ek1nA.js} +2 -2
  195. package/dist/{storm-DjKetLKZ.js.map → storm-U3_ek1nA.js.map} +1 -1
  196. package/dist/{storm-C-zYSdDX.cjs → storm-qiE_AMC7.cjs} +2 -2
  197. package/dist/{storm-C-zYSdDX.cjs.map → storm-qiE_AMC7.cjs.map} +1 -1
  198. package/dist/transport/exit-flush.d.cts +23 -0
  199. package/dist/transport/exit-flush.d.ts +23 -0
  200. package/dist/transport/http-transport.d.cts +3 -2
  201. package/dist/transport/http-transport.d.ts +3 -2
  202. package/dist/transport/retry-engine.d.cts +11 -3
  203. package/dist/transport/retry-engine.d.ts +11 -3
  204. package/dist/types-BAerHgCq.js.map +1 -1
  205. package/dist/types-C7WNpnG1.cjs.map +1 -1
  206. package/dist/{unclean-exit-DQD1cT7c.js → unclean-exit-Bj6gYHeL.js} +2 -2
  207. package/dist/{unclean-exit-DQD1cT7c.js.map → unclean-exit-Bj6gYHeL.js.map} +1 -1
  208. package/dist/{unclean-exit-py99ApzT.cjs → unclean-exit-CuBh-ee5.cjs} +2 -2
  209. package/dist/{unclean-exit-py99ApzT.cjs.map → unclean-exit-CuBh-ee5.cjs.map} +1 -1
  210. package/dist/{user-timing-D6XTmpuM.cjs → user-timing-BWqzYF2Q.cjs} +2 -2
  211. package/dist/{user-timing-D6XTmpuM.cjs.map → user-timing-BWqzYF2Q.cjs.map} +1 -1
  212. package/dist/{user-timing-BePqb1uN.js → user-timing-Duz0d-OA.js} +2 -2
  213. package/dist/{user-timing-BePqb1uN.js.map → user-timing-Duz0d-OA.js.map} +1 -1
  214. package/dist/utils/identity.d.cts +5 -0
  215. package/dist/utils/identity.d.ts +5 -0
  216. package/dist/utils/lock.d.cts +3 -2
  217. package/dist/utils/lock.d.ts +3 -2
  218. package/dist/utils/openfin.d.cts +18 -6
  219. package/dist/utils/openfin.d.ts +18 -6
  220. package/dist/utils/patch.d.cts +1 -1
  221. package/dist/utils/patch.d.ts +1 -1
  222. package/dist/utils/platform.d.cts +6 -0
  223. package/dist/utils/platform.d.ts +6 -0
  224. package/dist/{web-socket-DSHgDiZ6.js → web-socket-CE_9Q22z.js} +5 -5
  225. package/dist/{web-socket-DSHgDiZ6.js.map → web-socket-CE_9Q22z.js.map} +1 -1
  226. package/dist/{web-socket-CoIUBM3C.cjs → web-socket-sm3rD-A_.cjs} +2 -2
  227. package/dist/{web-socket-CoIUBM3C.cjs.map → web-socket-sm3rD-A_.cjs.map} +1 -1
  228. package/dist/{web-vitals-4pWACwaR.js → web-vitals-CGwXGF-M.js} +4 -4
  229. package/dist/web-vitals-CGwXGF-M.js.map +1 -0
  230. package/dist/web-vitals-Df4Wsfx9.cjs +2 -0
  231. package/dist/web-vitals-Df4Wsfx9.cjs.map +1 -0
  232. package/dist/{worker-protocol-QbvqNazn.cjs → worker-protocol-D5VnCdWY.cjs} +2 -2
  233. package/dist/{worker-protocol-QbvqNazn.cjs.map → worker-protocol-D5VnCdWY.cjs.map} +1 -1
  234. package/dist/{worker-protocol-x074Rpet.js → worker-protocol-h4-tRWqy.js} +6 -6
  235. package/dist/{worker-protocol-x074Rpet.js.map → worker-protocol-h4-tRWqy.js.map} +1 -1
  236. package/dist/{worker-server-CFe4nvos.cjs → worker-server-CF1yatXq.cjs} +2 -2
  237. package/dist/{worker-server-CFe4nvos.cjs.map → worker-server-CF1yatXq.cjs.map} +1 -1
  238. package/dist/worker-server-FYfKHQhJ.js +94 -0
  239. package/dist/{worker-server-iUVSjH8L.js.map → worker-server-FYfKHQhJ.js.map} +1 -1
  240. package/dist/worker-transport-COgY4RX8.cjs +2 -0
  241. package/dist/worker-transport-COgY4RX8.cjs.map +1 -0
  242. package/dist/{worker-transport-Dy1KMA7t.js → worker-transport-jzX1IusG.js} +49 -45
  243. package/dist/worker-transport-jzX1IusG.js.map +1 -0
  244. package/llms.txt +14 -12
  245. package/package.json +13 -5
  246. package/dist/bus-C39wspFV.js.map +0 -1
  247. package/dist/bus-_EaOVPGq.cjs +0 -2
  248. package/dist/bus-_EaOVPGq.cjs.map +0 -1
  249. package/dist/config-DUs7uHHt.cjs +0 -2
  250. package/dist/config-DUs7uHHt.cjs.map +0 -1
  251. package/dist/config-SgQcCP1_.js +0 -560
  252. package/dist/config-SgQcCP1_.js.map +0 -1
  253. package/dist/constants-CUyd9cTZ.js.map +0 -1
  254. package/dist/constants-CqdJhTxH.cjs +0 -2
  255. package/dist/constants-CqdJhTxH.cjs.map +0 -1
  256. package/dist/errors-BE_EZV7Q.js.map +0 -1
  257. package/dist/errors-CNPbesMs.cjs +0 -3
  258. package/dist/errors-CNPbesMs.cjs.map +0 -1
  259. package/dist/factory-CTi0Is3F.js.map +0 -1
  260. package/dist/factory-hRrH32v5.cjs +0 -2
  261. package/dist/factory-hRrH32v5.cjs.map +0 -1
  262. package/dist/identity-DdhKgrpk.js.map +0 -1
  263. package/dist/identity-DlWRIuwy.cjs +0 -2
  264. package/dist/identity-DlWRIuwy.cjs.map +0 -1
  265. package/dist/interactions-CUkzK8sR.cjs +0 -2
  266. package/dist/interactions-CUkzK8sR.cjs.map +0 -1
  267. package/dist/interactions-DiFvCosX.js +0 -111
  268. package/dist/interactions-DiFvCosX.js.map +0 -1
  269. package/dist/patch-BX8KrPCT.cjs +0 -2
  270. package/dist/patch-BX8KrPCT.cjs.map +0 -1
  271. package/dist/patch-UdPz1ea8.js +0 -8
  272. package/dist/patch-UdPz1ea8.js.map +0 -1
  273. package/dist/platform-BaaFIPCU.js +0 -62
  274. package/dist/platform-BaaFIPCU.js.map +0 -1
  275. package/dist/platform-CfA3-7sJ.cjs +0 -2
  276. package/dist/platform-CfA3-7sJ.cjs.map +0 -1
  277. package/dist/replay-B3gFXIZd.cjs +0 -2
  278. package/dist/replay-B3gFXIZd.cjs.map +0 -1
  279. package/dist/replay-Ds-ANH34.js.map +0 -1
  280. package/dist/response-body-YdNl-HkR.cjs +0 -3
  281. package/dist/response-body-YdNl-HkR.cjs.map +0 -1
  282. package/dist/response-body-eoSQpLiH.js.map +0 -1
  283. package/dist/rotation-Cwct4ckk.js.map +0 -1
  284. package/dist/rotation-D4qUAHAu.cjs +0 -2
  285. package/dist/rotation-D4qUAHAu.cjs.map +0 -1
  286. package/dist/sender-BdRuNVhF.cjs +0 -2
  287. package/dist/sender-BdRuNVhF.cjs.map +0 -1
  288. package/dist/sender-Dv8rAmpV.js.map +0 -1
  289. package/dist/stored-context-B2EzVuYm.js.map +0 -1
  290. package/dist/stored-context-CXt7eHZL.cjs +0 -2
  291. package/dist/stored-context-CXt7eHZL.cjs.map +0 -1
  292. package/dist/web-vitals-4pWACwaR.js.map +0 -1
  293. package/dist/web-vitals-__X7t4pj.cjs +0 -2
  294. package/dist/web-vitals-__X7t4pj.cjs.map +0 -1
  295. package/dist/worker-server-iUVSjH8L.js +0 -94
  296. package/dist/worker-transport-CRAX-09c.cjs +0 -2
  297. package/dist/worker-transport-CRAX-09c.cjs.map +0 -1
  298. package/dist/worker-transport-Dy1KMA7t.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"bus-_EaOVPGq.cjs","names":["BUS_TYPE","isLogRecord","isLogLevel","SEVERITY_NUMBER","isObject","BUS_PROTOCOL","RUNTIME_GLOBAL_KEY","BUS_PROTOCOL","getFin","BUS_HANDSHAKE_TIMEOUT_MS","BUS_TYPE","newId","windowEnded","countInWindow","FLUSH_TIMEOUT_MAX_MS","BUS_FLUSH_GAP_MS","getFin","BUS_CHANNEL_NAME","parseJourney","parseRemoteRules","REMOTE_SAMPLING_POLL_MS","require_constants","require_journey","require_remote_rules","require_log_record","require_guards","require_identity","require_openfin","require_fixed_window","require_unref","require_defineProperty","FLUSH_STATUSES","validMessage","value","m","text","key","r","readFlushResult","accepted","stored","dropped","forwarded","pending","count","status","envelope","message","unwrap","data","wrapper","RUNTIME_KEY","OPAQUE_ORIGIN","UNTAGGED_HOST_PROTOCOL","untrustedText","origin","what","parentOrigin","ancestors","referrerOrigin","sameOriginParent","diagnostics","referrer","frameOrigin","real","createDirectLink","host","hostProtocol","canAccept","hasSourceCheck","protocol","found","target","open","receive","createParentLink","self","trusted","trustedOrigins","reported","onMessage","event","createChildrenLink","sources","send","authorize","source","mayPost","answer","createBroadcastLink","BC","channel","channelName","createOpenFinLink","iab","appUuid","scoped","topic","raw","uuid","name","createOwnerLink","scope","createWorkerLink","worker","HANDSHAKE_OPTIONS","OWNED","Bus","permissions","peer","element","frame","options","registration","openFin","ref","reply","known","child","config","platform","contextId","tabId","handlers","handshakeOptions","bus","direct","candidate","attempts","welcomed","attempt","encoder","size","maxMessageBytes","chunk","bytes","rejected","record","records","recordBytes","comma","maxRecordsPerMessage","upstream","id","settle","answered","resolve","expired","plain","link","index","object","now","rate","entry","encoded","permission","before","current","from","own","wait","timeoutMs","gap","waiting","ends","result","configured","me","push","registered","settled","finish","timer","payload","journey","rules","to","update","ask"],"sources":["../src/bus/validation.ts","../src/models/bus.ts","../src/bus/links.ts","../src/bus/bus.ts"],"sourcesContent":["// src/bus/validation.ts\n//\n// Checks the required fields and values of messages from another context.\n\nimport type { BusMessage } from \"../models/bus\";\nimport type { FlushResult } from \"../models/health\";\nimport { isLogLevel, isLogRecord } from \"../models/log-record\";\nimport { BUS_TYPE, SEVERITY_NUMBER } from \"../constants\";\nimport { isObject } from \"../utils/guards\";\n\n/** The statuses a flush result can have. */\nconst FLUSH_STATUSES: readonly unknown[] = [\"complete\", \"timeout\", \"inactive\"];\n\n/**\n * Checks the fields that each bus message type requires. unwrap() only checks the envelope.\n * @param value Message to check.\n * @returns True if the message has the required fields and values.\n */\nexport function validMessage(value: unknown): value is BusMessage {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const m = value as Record<string, unknown>;\n if (typeof m.from !== \"string\" || !m.from || typeof m.t !== \"string\") {\n return false;\n }\n const text = (key: string): boolean => typeof m[key] === \"string\";\n switch (m.t) {\n case BUS_TYPE.hello:\n case BUS_TYPE.tab:\n return text(\"tabId\");\n case BUS_TYPE.welcome:\n return (\n text(\"to\") &&\n text(\"tabId\") &&\n (m.routingContextId === undefined || text(\"routingContextId\"))\n );\n case BUS_TYPE.journeyRequest:\n case BUS_TYPE.samplingRequest:\n return true;\n case BUS_TYPE.securityContext:\n return text(\"id\") && m.id !== \"\";\n case BUS_TYPE.journey:\n return (m.to === undefined || text(\"to\")) && \"journey\" in m;\n case BUS_TYPE.sampling:\n return text(\"to\") && \"rules\" in m;\n case BUS_TYPE.flushRequest:\n return text(\"id\") && typeof m.timeoutMs === \"number\";\n case BUS_TYPE.flushResult:\n return text(\"id\") && \"result\" in m;\n case BUS_TYPE.records:\n return (\n Array.isArray(m.records) &&\n (m.routingContextId === undefined || text(\"routingContextId\")) &&\n m.records.every((r: unknown) => {\n if (!isLogRecord(r) || !isLogLevel(r.severityText)) {\n return false;\n }\n return (\n !Array.isArray(r.attributes) &&\n !Array.isArray(r.resource) &&\n /^\\d+$/.test(r.timeUnixNano) &&\n (r.observedTimeUnixNano === undefined || /^\\d+$/.test(r.observedTimeUnixNano)) &&\n typeof r.traceId === \"string\" &&\n /^(?:[a-f\\d]{32})?$/.test(r.traceId) &&\n typeof r.spanId === \"string\" &&\n /^(?:[a-f\\d]{16})?$/.test(r.spanId) &&\n Number.isInteger(r.traceFlags) &&\n r.traceFlags >= 0 &&\n r.traceFlags <= 255 &&\n r.severityNumber === SEVERITY_NUMBER[r.severityText]\n );\n })\n );\n default:\n return false;\n }\n}\n\n/**\n * Copies a flush result from another context and checks the copy. Each field is read once, so\n * a getter can't pass the check with one value and hand over another.\n * @param value The answer's result.\n * @returns The copy, or null when the status is unknown or a count isn't a safe integer of 0\n * or more.\n */\nexport function readFlushResult(value: unknown): FlushResult | null {\n if (!isObject(value)) {\n return null;\n }\n\n const { status, accepted, stored, dropped, forwarded, pending } = value;\n const counts = [accepted, stored, dropped, forwarded, pending];\n const whole = counts.every((count) => Number.isSafeInteger(count) && (count as number) >= 0);\n // \"complete\" means that no record waits, so a count of pending records contradicts it.\n if (!whole || !FLUSH_STATUSES.includes(status) || (status === \"complete\" && pending !== 0)) {\n return null;\n }\n\n return { status, accepted, stored, dropped, forwarded, pending } as FlushResult;\n}\n","// src/models/bus.ts\n//\n// Protocol types, message definitions, and envelope encoding for bus messages between realms.\n\nimport { BUS_PROTOCOL, type BUS_TYPE } from \"../constants\";\nimport type { LogRecord } from \"./log-record\";\n\n/** What one child window or worker may do. The handshake needs no permission of its own. */\nexport type BusPermission = \"records\" | \"journey:read\" | \"journey:write\" | \"sampling:read\";\nexport interface SourceOptions {\n /** This source's permissions. Without the list, the source can only send records. */\n permissions?: BusPermission[];\n}\n\n/** Origin and permissions for one child frame registration. */\nexport interface FrameOptions extends SourceOptions {\n /** Expected window origin, including its scheme and port. Must match exactly. */\n origin: string;\n}\n\n/** Delivery role: whether this context sends its own records or forwards them upstream. */\nexport type BusRole = \"sender\" | \"forwarder\";\n\n/**\n * Kind of transport channel, which the bus uses to route incoming and outgoing messages.\n * Without it, `receive` can't tell the channels apart and a same-origin iframe looks like a\n * duplicated tab.\n */\nexport type LinkKind =\n /** Synchronous call into a same-origin parent runtime. */\n | \"direct\"\n /** postMessage to a parent window. */\n | \"parent\"\n /** postMessage to child frames. */\n | \"children\"\n /** BroadcastChannel across same-origin tabs and windows. */\n | \"broadcast\"\n /** OpenFin InterApplicationBus across desktop views and applications. */\n | \"openfin\"\n /** Dedicated worker communication to its owning document. */\n | \"owner\"\n /** Document-side communication to a dedicated worker. */\n | \"worker\";\n\n/** Origin and transport metadata for an incoming bus message. */\nexport interface MessageSource {\n /** Source identity as the transport reports it. The source can't supply it in message.from. */\n peer?: object | string;\n /** Inbound transport channel kind. */\n link: LinkKind;\n /** `event.origin` for `parent` and `children`. Other links use `\"same-origin\"` or `\"openfin\"`. */\n origin: string;\n /** Replies to this source only. A link that can't address a single source omits it. */\n reply?: (message: BusMessage) => void;\n}\n\n/** Discriminated union of control and telemetry payload messages. */\nexport type BusMessage =\n /** Handshake discovery announcement from a starting forwarder. */\n | { t: typeof BUS_TYPE.hello; from: string; tabId: string }\n /**\n * Handshake response from an upstream owner, addressed through the `to` field. A welcome on\n * InterApplicationBus reaches every subscriber, so without an address every waiting view\n * would accept the welcome as its own.\n */\n | {\n t: typeof BUS_TYPE.welcome;\n from: string;\n to: string;\n tabId: string;\n routingContextId?: string;\n }\n /** Telemetry log records forwarded to an upstream sender. */\n | { t: typeof BUS_TYPE.records; from: string; records: LogRecord[]; routingContextId?: string }\n /** Delivery context update. Only the owner from the handshake may send it to its children. */\n | { t: typeof BUS_TYPE.securityContext; from: string; id: string }\n /**\n * Journey update, or the answer to a journey question. An answer carries the asking\n * context's address in `to`. The payload comes from another realm, so the receiver parses it.\n */\n | { t: typeof BUS_TYPE.journey; from: string; to?: string; journey: unknown }\n /** Query requesting active journey state from connected peers. */\n | { t: typeof BUS_TYPE.journeyRequest; from: string }\n /** Tab identifier claim broadcast to detect collisions across windows. */\n | { t: typeof BUS_TYPE.tab; from: string; tabId: string }\n /** A forwarder's request for the current remote sampling rules. */\n | { t: typeof BUS_TYPE.samplingRequest; from: string }\n /**\n * Remote sampling rules in the header's shape, with the remaining TTL. `to` holds the address\n * of the forwarder that asked. The receiver validates `rules` again. Null rules end the\n * forwarder's copy.\n */\n | { t: typeof BUS_TYPE.sampling; from: string; to: string; rules: unknown }\n /**\n * A forwarder's request to flush. `id` names the request, and `timeoutMs` is the time the\n * forwarder has left. The receiver clamps it to its own range.\n */\n | { t: typeof BUS_TYPE.flushRequest; from: string; id: string; timeoutMs: number }\n /**\n * The answer to a flush request, with the request's id. The result comes from another realm,\n * so the receiver checks each field before it uses one.\n */\n | { t: typeof BUS_TYPE.flushResult; from: string; id: string; result: unknown };\n\n/** Transport envelope wrapping bus messages with a protocol version tag. */\nexport interface BusEnvelope {\n /** Protocol version identifier. */\n p: typeof BUS_PROTOCOL;\n /** Encapsulated bus payload. */\n m: BusMessage;\n}\n\n/**\n * Wraps a bus message in a versioned protocol envelope.\n * @param message Message to encapsulate.\n * @returns Envelope ready for transport.\n */\nexport function envelope(message: BusMessage): BusEnvelope {\n return { p: BUS_PROTOCOL, m: message };\n}\n\n/**\n * Validates the protocol tag and unpacks a raw payload into a bus message. A document gets\n * `message` events from all embedded content on the page, including analytics tags, video\n * players and extensions. Without the tag check, the bus would parse a video player's message\n * as a log record.\n * @param data Raw payload received over a transport link.\n * @returns The validated message, or null if the payload is invalid or unrecognized.\n */\nexport function unwrap(data: unknown): BusMessage | null {\n if (typeof data !== \"object\" || data === null) {\n return null;\n }\n\n // Validates payload structure at runtime without assuming envelope fields exist.\n const wrapper = data as Record<string, unknown>;\n if (wrapper.p !== BUS_PROTOCOL || typeof wrapper.m !== \"object\" || wrapper.m === null) {\n return null;\n }\n\n const message = wrapper.m as Record<string, unknown>;\n if (typeof message.t !== \"string\") {\n return null;\n }\n\n return message as unknown as BusMessage;\n}\n","// src/bus/links.ts\n//\n// Communication link implementations for direct, frame, broadcast, OpenFin, and worker channels.\n\nimport { BUS_PROTOCOL, BUS_TYPE_DETAIL_MAX_CHARS, RUNTIME_GLOBAL_KEY } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport {\n type BusMessage,\n envelope,\n type LinkKind,\n type MessageSource,\n unwrap,\n} from \"../models/bus\";\nimport { getFin } from \"../utils/openfin\";\n\n/** Bidirectional communication channel for bus message transport. */\nexport interface Link {\n /** Channel transport kind. */\n readonly kind: LinkKind;\n\n /**\n * Sends a message over the channel without throwing.\n * @param message Bus message to transmit.\n */\n post(message: BusMessage): void;\n\n /** Releases listeners, subscriptions, or channels held open by the link. */\n close(): void;\n}\n\n/**\n * Callback invoked when a bus message arrives on a link.\n * @param message Received bus message.\n * @param source Origin and link metadata.\n */\nexport type Receive = (message: BusMessage, source: MessageSource) => void;\n\n/** Interface that a same-origin parent runtime exposes on a global symbol. */\nexport interface DirectHost {\n /**\n * The parent's bus protocol tag. A direct call has no envelope to carry it, so the child\n * compares it before it opens the link. A parent on 0.12 or older has no tag.\n */\n readonly protocol?: string;\n /**\n * Accepts a message directly from a child frame and replies synchronously.\n * @param message Child bus message.\n * @param reply Callback for synchronous response.\n */\n busAccept(message: BusMessage, reply: Receive, source?: Window): void;\n /**\n * Checks if the parent permits a direct link from the child window.\n * @param source Child window.\n * @param origin Origin of the child window.\n * @returns True if the parent permits this source.\n */\n busCanAccept?: (source: Window, origin: string) => boolean;\n}\n\n/** Message port or dedicated/shared worker interface. */\nexport interface WorkerLike {\n /**\n * Sends a message to the worker or port.\n * @param message Payload to send.\n */\n postMessage(message: unknown): void;\n\n /**\n * Subscribes to incoming message events.\n * @param type Event name (\"message\").\n * @param listener Event handler callback.\n */\n addEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /**\n * Unsubscribes from message events.\n * @param type Event name (\"message\").\n * @param listener Event handler to remove.\n */\n removeEventListener(type: \"message\", listener: (event: MessageEvent) => void): void;\n\n /** Starts message delivery on MessagePort instances. */\n start?: () => void;\n}\n\n/** Global symbol used to look up same-origin parent runtime instances. */\nconst RUNTIME_KEY = Symbol.for(RUNTIME_GLOBAL_KEY);\n\n/** What an opaque origin reads as, for example in a frame sandboxed without allow-same-origin. */\nconst OPAQUE_ORIGIN = \"null\";\n\n/**\n * Bus protocol of a parent that has busCanAccept but no protocol field, which is every release\n * from 0.9.5 to 0.12. Release 0.9.5 added busCanAccept and this tag together.\n */\nconst UNTAGGED_HOST_PROTOCOL = \"ui-observability/2\";\n\n/** Location with the ancestor list that Chromium and WebKit give. */\ninterface LocationWithAncestors {\n origin: string;\n ancestorOrigins?: { length: number; item: (index: number) => string | null };\n}\n\n/**\n * Builds the diagnostic text for something we ignored from an untrusted origin.\n * @param origin Origin of the sender.\n * @param what What the bus ignored, for example \"a message\".\n * @returns The text. For a sandboxed sender it includes the fix for its frame.\n */\nfunction untrustedText(origin: string, what: string): string {\n if (origin === OPAQUE_ORIGIN) {\n return `The bus ignored ${what} from a sandboxed frame. The frame has an opaque origin. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.`;\n }\n\n return `The bus ignored ${what} from ${origin}. If you own this origin, add it to bus.trustedOrigins.`;\n}\n\n/**\n * Reads the parent frame's origin. A cross-origin parent doesn't expose it.\n * @param diagnostics Counts a blocked read of the parent's origin global.\n * @returns The origin, or null when the browser doesn't reveal it.\n */\nfunction parentOrigin(diagnostics: Diagnostics): string | null {\n const ancestors = (location as LocationWithAncestors).ancestorOrigins;\n if (ancestors && ancestors.length > 0) {\n return ancestors.item(0);\n }\n\n return referrerOrigin() ?? sameOriginParent(diagnostics);\n}\n\n/**\n * Reads the parent's origin from the referrer, which for a frame is the page that loaded it.\n * Firefox has no ancestorOrigins, so this is its first source.\n * @returns The origin, or null for an empty referrer, as with Referrer-Policy: no-referrer, or\n * for a referrer that isn't a URL.\n */\nfunction referrerOrigin(): string | null {\n const referrer = document.referrer;\n if (referrer === \"\") {\n return null;\n }\n\n try {\n return new URL(referrer).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Reads the parent's origin straight from its origin global. Firefox gives a srcdoc frame no\n * ancestorOrigins and an empty referrer, so without this it can't find even a same-origin parent.\n * The origin global, unlike location.origin, is also real in a srcdoc parent.\n * @param diagnostics Counts a blocked read.\n * @returns The origin, or null for a cross-origin parent, an opaque one or a value that isn't a\n * string.\n */\nfunction sameOriginParent(diagnostics: Diagnostics): string | null {\n let origin: unknown;\n try {\n origin = (window.parent as { origin?: unknown }).origin;\n } catch {\n // A cross-origin or sandboxed parent throws here. Count it, but don't report it, because the\n // caller already reports the unknown origin.\n diagnostics.count(\"platform.api_blocked\");\n return null;\n }\n\n // A cross-origin parent with a child frame named \"origin\" gives that frame's window here\n // instead of a throw, and a parent script can overwrite the global. Only a same-origin parent\n // gives a string, and no message may target \"null\".\n if (typeof origin !== \"string\" || origin === OPAQUE_ORIGIN) {\n return null;\n }\n\n return origin;\n}\n\n/**\n * Returns the origin this frame runs on. A srcdoc or about:blank frame runs on the origin of\n * the document that made it, but its location.origin reads \"null\", because that comes from\n * the URL.\n * @returns location.origin, or the origin global when location.origin is \"null\". A frame\n * sandboxed from a URL keeps its URL origin here, and the parent refuses its \"null\" messages.\n */\nexport function frameOrigin(): string {\n if (location.origin !== OPAQUE_ORIGIN) {\n return location.origin;\n }\n\n // A same-origin script can overwrite the origin global. docs/threat-model.md leaves such a\n // script out of scope, and it gains nothing here, because it can already call the parent.\n const real = (globalThis as { origin?: unknown }).origin;\n if (typeof real !== \"string\") {\n return OPAQUE_ORIGIN;\n }\n\n return real;\n}\n\n/**\n * Establishes direct synchronous communication with a same-origin parent runtime.\n * @param receive Callback for parent replies.\n * @param diagnostics Diagnostics reporter.\n * @returns Direct link, or null if the parent is inaccessible, lacks a runtime, uses another\n * bus protocol or refuses this frame. When it is null, the bus tries the message link to the\n * parent.\n */\nexport function createDirectLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n let host: DirectHost | undefined;\n try {\n const parentGlobal = window.parent as unknown as Record<symbol, DirectHost | undefined>;\n host = parentGlobal[RUNTIME_KEY];\n } catch {\n // Cross-origin access throws on read.\n return null;\n }\n if (typeof host?.busAccept !== \"function\") {\n return null;\n }\n\n // Read protocol and busCanAccept once, before any call into the parent. A getter could answer\n // differently on a second read, and the check would then judge one value and act on another.\n const hostProtocol = host.protocol;\n const canAccept = host.busCanAccept;\n const hasSourceCheck = typeof canAccept === \"function\";\n\n // Without this, a frame under a 0.9.5 to 0.12 parent falls back to the message link. Where\n // that link can't find the parent's origin, the frame sends its own records and the parent's\n // redact never sees them.\n const untagged = hostProtocol === undefined && hasSourceCheck;\n const protocol = untagged ? UNTAGGED_HOST_PROTOCOL : hostProtocol;\n\n // A direct call skips the envelope, so this is the only version check on this path. Without\n // it, a parent on another library version gets messages in a shape it doesn't expect.\n if (protocol !== BUS_PROTOCOL) {\n // The parent controls this text, so cap it like an untrusted message type.\n const found =\n typeof protocol === \"string\" ? protocol.slice(0, BUS_TYPE_DETAIL_MAX_CHARS) : \"none\";\n diagnostics.report(\n \"bus.protocol_mismatch\",\n \"The same-origin parent runtime uses another bus protocol. This context tries a message link instead of a direct call.\",\n { found, own: BUS_PROTOCOL },\n );\n return null;\n }\n\n // A srcdoc frame's location.origin reads \"null\", which a parent refuses, and the frame then\n // sends its own records past the parent's redact. The runtime read above proved same-origin.\n const origin = frameOrigin();\n\n // Called as the parent's method, so a runtime that uses \"this\" inside it still works.\n if (hasSourceCheck && !canAccept.call(host, window, origin)) {\n return null;\n }\n\n const target = host;\n let open = true;\n\n return {\n kind: \"direct\",\n post(message) {\n if (!open) {\n return;\n }\n\n // Stops an error in the parent runtime from breaking a logging call in the child.\n diagnostics.guard(\n \"bus.send_failed\",\n \"The direct call into the parent runtime failed.\",\n () => {\n target.busAccept(message, receive, window);\n },\n );\n },\n close() {\n open = false;\n },\n };\n}\n\n/**\n * Creates a postMessage link to a parent window on a trusted origin. Records hold user data,\n * so a page on another origin that frames this app must not get them.\n * @param receive Callback for incoming parent messages.\n * @param trustedOrigins Parent origins that may receive the records, in addition to this origin.\n * @param diagnostics Diagnostics reporter.\n * @returns Link to the parent window, or null at the top level or with an untrusted parent.\n * When it is null, this context sends its own records.\n */\nexport function createParentLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n): Link | null {\n if (typeof window === \"undefined\" || window.parent === window) {\n return null;\n }\n\n // No parent can put \"null\" in its trust list. A srcdoc frame isn't that case, because it\n // runs on a real origin, so it goes on to the parent origin check below.\n const self = frameOrigin();\n if (self === OPAQUE_ORIGIN) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n 'This frame reports the origin \"null\". No parent can trust that origin. This context sends its own records. A frame that is sandboxed without allow-same-origin has this origin. Set bus.mode: \"sender\" in the frame. Add allow-same-origin to the sandbox attribute only for content that you trust.',\n { origin: self, type: \"parent\" },\n );\n return null;\n }\n\n const trusted = new Set([self, ...trustedOrigins]);\n const target = parentOrigin(diagnostics);\n if (target === null || !trusted.has(target)) {\n diagnostics.report(\n \"bus.untrusted_origin\",\n target === null\n ? \"The origin of the parent frame is unknown. This context sends its own records.\"\n : `The parent frame is on ${target}. This origin is not in bus.trustedOrigins. This context sends its own records.`,\n { origin: target ?? \"\", type: \"parent\" },\n );\n return null;\n }\n\n // Report every untrusted origin only once, because a hostile parent can send many messages.\n const reported = new Set<string>();\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message || event.source !== window.parent) {\n return;\n }\n\n // The parent can navigate to another origin after this frame loads.\n if (!trusted.has(event.origin)) {\n if (!reported.has(event.origin)) {\n reported.add(event.origin);\n // The parent controls message.t, so keep it out of the message text and truncate it\n // in the detail.\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n }\n return;\n }\n\n receive(message, { link: \"parent\", origin: event.origin, peer: event.source });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"parent\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to the parent failed.\", () => {\n // Target the trusted origin, not \"*\". The browser drops the message if the parent\n // navigated to another origin.\n window.parent.postMessage(envelope(message), target);\n });\n },\n close() {\n removeEventListener(\"message\", onMessage);\n },\n };\n}\n\n/**\n * Creates a link listening to child frames with origin allowlist filtering.\n * @param receive Callback for messages from authorized child frames.\n * @param trustedOrigins Additional origins allowed to communicate.\n * @param diagnostics Diagnostics reporter.\n * @returns Children link, or null in non-window environments.\n */\nexport function createChildrenLink(\n receive: Receive,\n trustedOrigins: string[],\n diagnostics: Diagnostics,\n authorize?: (source: MessageEventSource | null, origin: string) => boolean,\n mayPost?: (message: BusMessage, source: MessageEventSource) => boolean,\n): Link | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n // A sandboxed page has the opaque origin \"null\", and so does every sandboxed child.\n const trusted = new Set([location.origin, ...trustedOrigins]);\n trusted.delete(OPAQUE_ORIGIN);\n\n // Remembers every source's origin, so a child that navigates doesn't get the ids of its\n // previous origin.\n const sources = new Map<MessageEventSource, string>();\n\n /**\n * Posts one message to one child, and forgets a child that is closed or no longer permitted.\n * @param source Child window.\n * @param origin Last known origin of the child.\n * @param message Message to send.\n */\n const send = (source: MessageEventSource, origin: string, message: BusMessage): void => {\n if (authorize && !authorize(source, origin)) {\n sources.delete(source);\n return;\n }\n if (mayPost && !mayPost(message, source)) {\n return;\n }\n const target = source as Window;\n // Evicts closed child windows to prevent memory leaks.\n if (target.closed) {\n sources.delete(source);\n return;\n }\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to a child frame failed.\", () => {\n // Targets the last known origin of the child. The browser drops the\n // message if the child navigated to a different origin.\n target.postMessage(envelope(message), origin);\n });\n };\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (!message) {\n return;\n }\n // A nested frame also receives its parent's messages here. Those belong to the parent link.\n if (window.parent !== window && event.source === window.parent) {\n return;\n }\n if (!authorize && !trusted.has(event.origin)) {\n diagnostics.report(\"bus.untrusted_origin\", untrustedText(event.origin, \"a message\"), {\n origin: event.origin,\n type: message.t.slice(0, BUS_TYPE_DETAIL_MAX_CHARS),\n });\n return;\n }\n\n if (authorize && !authorize(event.source, event.origin)) {\n return;\n }\n const { source, origin } = event;\n if (source) {\n sources.set(source, origin);\n }\n // Answer only the child that asked. A broadcast would let one child use up every\n // sibling's budget.\n receive(message, {\n link: \"children\",\n origin,\n peer: source ?? undefined,\n reply: source\n ? (answer) => {\n send(source, origin, answer);\n }\n : undefined,\n });\n };\n addEventListener(\"message\", onMessage);\n\n return {\n kind: \"children\",\n post(message) {\n for (const [source, origin] of sources) {\n send(source, origin, message);\n }\n },\n close() {\n removeEventListener(\"message\", onMessage);\n sources.clear();\n },\n };\n}\n\n/**\n * Creates a same-origin BroadcastChannel link for cross-tab control messages.\n * @param channelName BroadcastChannel identifier.\n * @param receive Callback for incoming cross-tab messages.\n * @param diagnostics Diagnostics reporter.\n * @returns Broadcast link, or null if unsupported.\n */\nexport function createBroadcastLink(\n channelName: string,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const BC = (globalThis as { BroadcastChannel?: typeof BroadcastChannel }).BroadcastChannel;\n if (typeof BC === \"undefined\") {\n return null;\n }\n\n const channel = diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not open the BroadcastChannel.\",\n () => new BC(channelName),\n );\n if (!channel) {\n return null;\n }\n\n channel.onmessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"broadcast\", origin: \"same-origin\" });\n }\n };\n\n return {\n kind: \"broadcast\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The BroadcastChannel.postMessage call failed.\", () => {\n channel.postMessage(envelope(message));\n });\n },\n close() {\n diagnostics.guard(\n \"bus.send_failed\",\n \"The library could not close the BroadcastChannel.\",\n () => {\n channel.close();\n },\n );\n },\n };\n}\n\n/**\n * Creates an OpenFin InterApplicationBus link scoped to one application.\n * @param topic InterApplicationBus topic prefix.\n * @param appUuid OpenFin application uuid owning this context.\n * @param receive Callback for received topic messages.\n * @param diagnostics Diagnostics reporter.\n * @returns OpenFin link, or null if InterApplicationBus or the identity is unavailable.\n */\nexport function createOpenFinLink(\n topic: string,\n appUuid: string | undefined,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link | null {\n const iab = getFin()?.InterApplicationBus;\n if (!iab) {\n return null;\n }\n if (!appUuid) {\n // publish() sends to every subscriber on the runtime. Without a uuid scope,\n // this link would share this app's bus with every other app.\n diagnostics.report(\n \"openfin.unavailable\",\n \"OpenFin gives no application uuid. The InterApplicationBus link stays closed.\",\n );\n return null;\n }\n\n // The uuid goes into both the topic and the subscriber identity. The topic keeps this app's\n // messages away from other apps, and the identity rejects messages that come from them.\n const scoped = `${topic}.${appUuid}`;\n\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.subscribe call failed.\",\n () =>\n iab.subscribe({ uuid: appUuid }, scoped, (raw, uuid, name) => {\n const message = unwrap(raw);\n if (message) {\n receive(message, {\n link: \"openfin\",\n origin: \"openfin\",\n peer: uuid && name ? `${uuid}:${name}` : undefined,\n });\n }\n }),\n );\n\n return {\n kind: \"openfin\",\n post(message) {\n void diagnostics.guardAsync(\n \"bus.send_failed\",\n \"The InterApplicationBus.publish call failed.\",\n () => iab.publish(scoped, envelope(message)),\n );\n },\n close() {\n // OpenFin removes the subscriptions when the context closes.\n },\n };\n}\n\n/**\n * Creates the worker-side link pointing at the document that created this\n * worker. Emits `kind: \"owner\"`.\n * @param receive Callback for incoming messages from the owning document.\n * @param diagnostics Diagnostics reporter.\n * @returns Owner link, or null outside a DedicatedWorkerGlobalScope.\n */\nexport function createOwnerLink(receive: Receive, diagnostics: Diagnostics): Link | null {\n const scope = globalThis as unknown as {\n postMessage?: (message: unknown) => void;\n addEventListener?: (type: string, listener: (event: MessageEvent) => void) => void;\n WorkerGlobalScope?: unknown;\n };\n const send = scope.postMessage;\n if (typeof scope.WorkerGlobalScope === \"undefined\" || !send) {\n return null;\n }\n\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"owner\", origin: \"same-origin\" });\n }\n };\n scope.addEventListener?.(\"message\", onMessage);\n\n return {\n kind: \"owner\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call of the worker failed.\", () => {\n send(envelope(message));\n });\n },\n close() {\n // Worker scope listeners stop when the worker stops.\n },\n };\n}\n\n/**\n * Creates the document-side link pointing at one attached worker or port.\n * Emits `kind: \"worker\"`.\n * @param worker Target worker instance or MessagePort.\n * @param receive Callback for messages from the worker.\n * @param diagnostics Diagnostics reporter.\n * @returns Document-to-worker link.\n */\nexport function createWorkerLink(\n worker: WorkerLike,\n receive: Receive,\n diagnostics: Diagnostics,\n): Link {\n const onMessage = (event: MessageEvent): void => {\n const message = unwrap(event.data);\n if (message) {\n receive(message, { link: \"worker\", origin: \"same-origin\", peer: worker });\n }\n };\n worker.addEventListener(\"message\", onMessage);\n\n // Starts delivery on a MessagePort. A Worker has no start method.\n worker.start?.();\n\n return {\n kind: \"worker\",\n post(message) {\n diagnostics.guard(\"bus.send_failed\", \"The postMessage call to a worker failed.\", () => {\n worker.postMessage(envelope(message));\n });\n },\n close() {\n worker.removeEventListener(\"message\", onMessage);\n },\n };\n}\n","// src/bus/bus.ts\n//\n// Resolves the bus role and routes messages between realms.\n\nimport {\n BUS_CHANNEL_NAME,\n BUS_FLUSH_GAP_MS,\n BUS_HANDSHAKE_TIMEOUT_MS,\n BUS_MAX_FLUSH_REQUESTS,\n BUS_MAX_FLUSH_REQUESTS_PER_SOURCE,\n BUS_MAX_HANDSHAKE_ATTEMPTS,\n BUS_MAX_TRACKED_SOURCES,\n BUS_TYPE,\n FLUSH_TIMEOUT_MAX_MS,\n REMOTE_SAMPLING_POLL_MS,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport { type Journey, parseJourney } from \"../core/journey\";\nimport { applyRemote, parseRemoteRules } from \"../core/remote-rules\";\nimport type { RemoteSlot } from \"../core/remote-sampling\";\nimport type { BusMessage, BusRole, LinkKind, MessageSource } from \"../models/bus\";\nimport type { SourceOptions, FrameOptions } from \"../models/bus\";\nimport { readFlushResult, validMessage } from \"./validation\";\nimport type { JourneyScope, ResolvedConfig } from \"../models/config\";\nimport type { FlushResult } from \"../models/health\";\nimport type { LogRecord } from \"../models/log-record\";\nimport { newId } from \"../utils/identity\";\nimport { getFin } from \"../utils/openfin\";\nimport type { PlatformMetadata } from \"../utils/platform\";\nimport { countInWindow, windowEnded } from \"../utils/fixed-window\";\nimport { unrefTimer } from \"../utils/unref\";\nimport {\n createBroadcastLink,\n createChildrenLink,\n createDirectLink,\n createOpenFinLink,\n createOwnerLink,\n createParentLink,\n createWorkerLink,\n frameOrigin,\n type Link,\n type Receive,\n type WorkerLike,\n} from \"./links\";\n\n/** Handshake timing for a forwarder waiting on an owner. */\nexport interface HandshakeOptions {\n /** How long a forwarder waits for an owner to answer, in milliseconds. */\n timeoutMs: number;\n /** Attempts allowed before a cross-origin forwarder promotes itself to sender. */\n maxAttempts: number;\n}\n\n/** Default handshake timing. Tests build a bus with shorter values. */\nexport const HANDSHAKE_OPTIONS: HandshakeOptions = {\n timeoutMs: BUS_HANDSHAKE_TIMEOUT_MS,\n maxAttempts: BUS_MAX_HANDSHAKE_ATTEMPTS,\n};\n\n/** Callbacks for handling records and journey events from connected realms. */\nexport interface BusHandlers {\n /** Adopts the owner's delivery context. Returning false refuses a different identity. */\n onSecurityContext?: (id: string) => boolean;\n /** Processes records forwarded from child contexts. */\n onRecords: (records: LogRecord[]) => void;\n /**\n * Returns true while the runtime is paused. A paused forwarder hands a child's records to\n * onRecords, which drops them, instead of relaying them upstream.\n */\n paused?: () => boolean;\n /** Applies journey updates received from the control bus. */\n onJourney: (journey: Journey | null) => void;\n /** Returns the active journey to a child context that requests it. */\n onJourneyRequest: () => Journey | null;\n /** Runs when two windows use the same tab identifier. */\n onTabConflict: () => void;\n /**\n * Runs this context's own flush for a child that asked, with the child's time limit. Without\n * it, the bus answers no flush request.\n * @param timeoutMs How long the flush waits, in milliseconds, already in range.\n * @returns The flush result.\n */\n onFlush?: (timeoutMs: number) => Promise<FlushResult>;\n /** The runtime's slot for the remote sampling rules. The bus both reads and fills it. */\n remote: RemoteSlot;\n}\n\n/** Link types that a sender context may claim ownership over during handshakes. */\nconst OWNED: readonly LinkKind[] = [\"children\", \"direct\", \"worker\"];\n\n/** Journey scope after the bus resolves \"auto\". */\ntype ResolvedScope = Exclude<JourneyScope, \"auto\">;\n\n/** A child's flush request that waits for the next flush. */\ninterface FlushWait {\n /** The physical source, or its link when the link names none. Its cap counts on it. */\n source: unknown;\n /** Epoch time in milliseconds when the child stops waiting. */\n ends: number;\n /** Sends the result to the child that asked. */\n answer: (result: FlushResult) => void;\n}\n\n/** Coordinates cross-realm communication, role resolution, and message dispatch. */\nexport class Bus {\n /** Window and worker registrations with their permissions. */\n private readonly sources = new Map<object, SourceOptions & { origin?: string }>();\n /** Message counts for each window and worker in the current rate window. */\n private readonly rates = new WeakMap<object, { start: number; count: number }>();\n /** Message counts for each named source or link in the current rate window. */\n private readonly channelRates = new Map<string, { start: number; count: number }>();\n /** Each same-origin direct child's reply. Held weakly so a navigated frame can be freed. */\n private readonly directReplies = new Map<Window, WeakRef<Receive>>();\n\n /**\n * Checks whether this source may receive a control message. A window can read a message\n * even when it is addressed to another window.\n * @param message Control message to send.\n * @param peer Window or worker that receives the message.\n * @returns True if the source has the required permission.\n */\n private mayPost(message: BusMessage, peer: object): boolean {\n const permissions = this.sources.get(peer)?.permissions;\n if (!permissions) {\n return this.config.bus.sourcePolicy === \"trusted-origin\";\n }\n if (message.t === BUS_TYPE.journey) {\n return permissions.includes(\"journey:read\");\n }\n if (message.t === BUS_TYPE.journeyRequest) {\n return permissions.includes(\"journey:write\");\n }\n if (message.t === BUS_TYPE.sampling) {\n return permissions.includes(\"sampling:read\");\n }\n return true;\n }\n\n /**\n * Registers one child window and its permissions.\n * @param frame Frame element or window to register.\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 // Use instanceof here, because the \"in\" operator throws on a cross-origin window.\n const element = typeof HTMLIFrameElement === \"undefined\" ? undefined : HTMLIFrameElement;\n const source = element && frame instanceof element ? frame.contentWindow : frame;\n if (!source || new URL(options.origin).origin !== options.origin || options.origin === \"null\") {\n throw new Error(\"A frame registration requires a window and an exact origin.\");\n }\n const registration = { ...options, permissions: [...(options.permissions ?? [\"records\"])] };\n this.sources.set(source, registration);\n this.ensureChildrenLink();\n return () => {\n if (this.sources.get(source) === registration) {\n this.sources.delete(source);\n }\n };\n }\n\n /**\n * Checks if a source is permitted at the given origin.\n * @param source Window or port that sent the message.\n * @param origin Origin supplied by the transport.\n * @returns True if the current source policy permits this source.\n */\n isRegistered(source: object | null, origin: string): boolean {\n if (!source) {\n return false;\n }\n const registration = this.sources.get(source);\n // A registration is bound to its exact origin under every policy, so it needs no\n // trustedOrigins entry.\n if (registration) {\n return registration.origin === origin;\n }\n if (this.config.bus.sourcePolicy === \"registered\") {\n return false;\n }\n // A srcdoc parent's location.origin reads \"null\", and its same-origin children would then\n // need a trustedOrigins entry for the page's own origin.\n return (\n origin !== \"null\" &&\n (origin === frameOrigin() || this.config.bus.trustedOrigins.includes(origin))\n );\n }\n\n /**\n * Sends the new context id to child frames, workers and OpenFin views. Other tabs keep their\n * own context.\n */\n rotateContext(): void {\n // Only the owner sends on the OpenFin link. Without this message every view keeps the old id.\n this.passContext(this.role === \"sender\");\n }\n\n /**\n * Sends the context id to child frames and workers.\n * @param openFin True to send it to OpenFin views too.\n */\n private passContext(openFin: boolean): void {\n const message: BusMessage = {\n t: BUS_TYPE.securityContext,\n from: this.contextId,\n id: this.config.securityContext.id,\n };\n this.postOver(\"children\", message);\n this.postOver(\"worker\", message);\n this.postToDirectChildren(message);\n if (openFin) {\n this.postOver(\"openfin\", message);\n }\n }\n\n /**\n * Sends a security context message to every same-origin child on the direct link, dropping\n * any child that is closed, freed or no longer permitted.\n * @param message Security context message.\n */\n private postToDirectChildren(message: BusMessage): void {\n // A direct child runs on this document's origin. In a srcdoc parent, location.origin reads\n // \"null\", and without the real origin every child would miss the new id.\n const origin = frameOrigin();\n\n for (const [peer, ref] of this.directReplies) {\n const reply = ref.deref();\n if (!reply || peer.closed || !this.isRegistered(peer, origin)) {\n this.directReplies.delete(peer);\n continue;\n }\n\n this.diagnostics.guard(\"bus.send_failed\", \"The reply to a direct child failed.\", () => {\n reply(message, { link: \"direct\", origin: \"same-origin\", peer });\n });\n }\n }\n\n /**\n * Keeps a direct child's reply callback for the next context id. Closed children are dropped\n * along the way, so a removed frame doesn't keep its document in memory.\n * @param peer The child's window.\n * @param reply The child's reply callback.\n */\n private keepDirectReply(peer: Window, reply: Receive): void {\n for (const known of this.directReplies.keys()) {\n if (known.closed) {\n this.directReplies.delete(known);\n }\n }\n\n this.directReplies.set(peer, new WeakRef(reply));\n }\n\n /** Current bus role. Defaults to \"sender\". */\n private role: BusRole = \"sender\";\n /** Upstream forwarding link, or null when acting as sender. */\n private upstream: Link | null = null;\n /** Open control plane links. */\n private readonly links: Link[] = [];\n /** Shared OpenFin InterApplicationBus link instance. */\n private openFinLink: Link | null = null;\n /** True if this context is the OpenFin platform provider. */\n private isOpenFinProvider = false;\n /** Timer that asks the upstream owner for the remote sampling rules. */\n private rulesPoll: ReturnType<typeof setInterval> | undefined;\n /** True after destroy(), so a handshake that finishes later doesn't start a timer. */\n private destroyed = false;\n /** Context id of the owner that answered the handshake. Null if there was no handshake. */\n private ownerId: string | null = null;\n /** The owner's transport identity, taken from the handshake. */\n private ownerPeer?: object | string;\n /** Active handshake state awaiting welcome response. */\n private awaitingWelcome: {\n link: LinkKind;\n settle: (ok: boolean) => void;\n } | null = null;\n /** This forwarder's flush requests that wait for an answer, by request id. */\n private readonly flushAnswers = new Map<string, (result: FlushResult) => void>();\n /** Children's flush requests that wait for the flush after the one that runs. */\n private flushQueue: FlushWait[] = [];\n /** True while a flush that a child asked for runs, or waits for its gap. */\n private flushing = false;\n /** Epoch time in milliseconds when the last flush for a child started. */\n private flushedAt = 0;\n\n /**\n * @param config Active configuration instance.\n * @param diagnostics Diagnostics reporter.\n * @param platform Platform runtime metadata.\n * @param contextId Unique context identifier for loop prevention.\n * @param tabId Tab identifier announced on broadcast channels.\n * @param handlers Callbacks for routed bus events.\n */\n constructor(\n private readonly config: ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n private readonly platform: PlatformMetadata,\n private readonly contextId: string,\n private readonly tabId: string,\n private readonly handlers: BusHandlers,\n private readonly handshakeOptions: HandshakeOptions = HANDSHAKE_OPTIONS,\n ) {}\n\n /** Returns the resolved bus role. */\n getRole(): BusRole {\n return this.role;\n }\n\n /**\n * Resolves bus role and establishes control links.\n * @returns Resolved role.\n */\n async start(): Promise<BusRole> {\n const { bus } = this.config;\n\n if (bus.mode === \"off\") {\n this.role = \"sender\";\n return this.role;\n }\n\n this.isOpenFinProvider = this.resolveOpenFinProvider();\n\n if (bus.mode === \"sender\" || bus.mode === \"forwarder\") {\n this.role = bus.mode;\n this.openControlLinks();\n if (this.role === \"forwarder\") {\n this.upstream = this.candidateUpstream();\n if (!this.upstream) {\n this.diagnostics.report(\n \"bus.no_owner\",\n 'bus.mode is \"forwarder\". No owner exists. The library drops the records of this context.',\n );\n }\n }\n this.announce();\n return this.role;\n }\n\n this.openControlLinks();\n\n // A same-origin parent runtime accepts a direct synchronous link.\n const direct = createDirectLink(this.receive, this.diagnostics);\n if (direct) {\n this.role = \"forwarder\";\n this.upstream = direct;\n await this.handshake(direct);\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"This context attached directly to the runtime of its same-origin parent.\",\n {\n role: \"forwarder\",\n via: \"direct\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const candidate = this.candidateUpstream();\n\n if (!candidate) {\n this.role = \"sender\";\n this.diagnostics.report(\n \"bus.role_resolved\",\n \"No owner exists. This context sends its own records.\",\n {\n role: \"sender\",\n },\n );\n this.announce();\n return this.role;\n }\n\n const attempts = this.orphanPolicy() === \"retry\" ? this.handshakeOptions.maxAttempts : 1;\n\n let welcomed = false;\n for (let attempt = 0; attempt < attempts && !welcomed; attempt++) {\n welcomed = await this.handshake(candidate);\n }\n\n this.role = welcomed ? \"forwarder\" : \"sender\";\n this.upstream = welcomed ? candidate : null;\n if (!welcomed) {\n // The OpenFin link stays open for control messages.\n if (candidate !== this.openFinLink) {\n candidate.close();\n }\n this.diagnostics.report(\n \"bus.handshake_timeout\",\n `No owner answered after ${String(attempts)} attempt(s) of ${String(this.handshakeOptions.timeoutMs)} ms. This context becomes the sender.`,\n { via: candidate.kind, crossOrigin: this.isCrossOriginFrame() },\n );\n }\n this.diagnostics.report(\"bus.role_resolved\", `The bus role is ${this.role}.`, {\n role: this.role,\n via: welcomed ? candidate.kind : \"none\",\n });\n\n this.announce();\n return this.role;\n }\n\n /**\n * Forwards records to the upstream owner if configured.\n * @param records Batch of log records to send.\n * @returns How many records went upstream. A record above the size limit doesn't go.\n */\n sendRecords(records: LogRecord[]): number {\n const { maxRecordsPerMessage, maxMessageBytes } = this.config.bus;\n const encoder = new TextEncoder();\n const size = (value: unknown): number =>\n maxMessageBytes === null ? 0 : encoder.encode(JSON.stringify(value)).length;\n const message = (chunk: LogRecord[]): BusMessage => ({\n t: BUS_TYPE.records,\n from: this.contextId,\n records: chunk,\n routingContextId: this.config.securityContext.id || undefined,\n });\n\n // Measure every record once. A message is the empty envelope plus its records and the\n // commas between them.\n const envelope = size(message([]));\n let chunk: LogRecord[] = [];\n let bytes = envelope;\n let rejected = 0;\n\n for (const record of records) {\n const recordBytes = size(record);\n if (maxMessageBytes !== null && envelope + recordBytes > maxMessageBytes) {\n this.diagnostics.count(\"bus.rejected_message\");\n rejected++;\n continue;\n }\n\n const comma = chunk.length > 0 ? 1 : 0;\n if (\n (maxRecordsPerMessage !== null && chunk.length >= maxRecordsPerMessage) ||\n (maxMessageBytes !== null && bytes + comma + recordBytes > maxMessageBytes)\n ) {\n this.upstream?.post(message(chunk));\n chunk = [];\n bytes = envelope;\n }\n\n bytes += (chunk.length > 0 ? 1 : 0) + recordBytes;\n chunk.push(record);\n }\n\n if (chunk.length > 0) {\n this.upstream?.post(message(chunk));\n }\n\n return this.upstream ? records.length - rejected : 0;\n }\n\n /**\n * Asks the upstream sender to flush, then waits for its answer. The records that went before\n * the request on the same link are in the sender's snapshot, because a link keeps its order.\n * @param timeoutMs The time this context has left, in milliseconds. The sender uses it as its\n * own limit.\n * @param expired Resolves when this context stops waiting.\n * @returns The sender's result, or null when no valid answer came in time.\n */\n async requestFlush(timeoutMs: number, expired: Promise<void>): Promise<FlushResult | null> {\n const { upstream } = this;\n if (!upstream) {\n return null;\n }\n\n const id = newId(this.diagnostics);\n let settle!: (result: FlushResult) => void;\n const answered = new Promise<FlushResult>((resolve) => {\n settle = resolve;\n });\n this.flushAnswers.set(id, settle);\n upstream.post({ t: BUS_TYPE.flushRequest, from: this.contextId, id, timeoutMs });\n\n try {\n return await Promise.race([answered, expired.then(() => null)]);\n } finally {\n this.flushAnswers.delete(id);\n }\n }\n\n /**\n * Synchronously processes direct messages from same-origin child contexts.\n * @param message Received bus message.\n * @param reply Direct response callback.\n */\n acceptDirect(message: BusMessage, reply: Receive, peer?: Window): void {\n // The child gets the plain source. The reply field stays on this side.\n const plain: MessageSource = { link: \"direct\", origin: \"same-origin\", peer };\n const source: MessageSource = {\n ...plain,\n reply: (answer) => {\n reply(answer, plain);\n },\n };\n if (!this.acceptsMessage(message, source, true)) {\n return;\n }\n if (message.from === this.contextId) {\n return;\n }\n\n // A rotation sends the new id through this reply, so the child doesn't send a stale batch.\n if (peer) {\n this.keepDirectReply(peer, reply);\n }\n\n // A direct link has no channel from parent to child, so the parent answers here. The\n // forwarder rule in routeMessage() would refuse a sampling question on a direct link.\n if (message.t === BUS_TYPE.samplingRequest) {\n reply(this.rulesAnswer(message.from), plain);\n return;\n }\n // While this context still waits for its own owner it has no final id, so it sends none.\n if (\n message.t === BUS_TYPE.records &&\n !this.awaitingWelcome &&\n message.routingContextId !== this.config.securityContext.id\n ) {\n reply(\n { t: BUS_TYPE.securityContext, from: this.contextId, id: this.config.securityContext.id },\n plain,\n );\n }\n this.routeMessage(message, source);\n }\n\n /**\n * Connects a worker instance to the bus control plane.\n * @param worker Worker instance.\n */\n attachWorker(worker: WorkerLike, options: SourceOptions = {}): () => void {\n const registration = { ...options, permissions: [...(options.permissions ?? [\"records\"])] };\n this.sources.set(worker, registration);\n // An answer goes to this worker only. Over postOver() it would reach every attached worker.\n const receive: Receive = (message, source) => {\n this.receive(message, {\n ...source,\n reply: (answer) => {\n link.post(answer);\n },\n });\n };\n const raw = createWorkerLink(worker, receive, this.diagnostics);\n const link: Link = {\n ...raw,\n post: (message) => {\n if (this.mayPost(message, worker)) {\n raw.post(message);\n }\n },\n };\n this.links.push(link);\n return () => {\n link.close();\n const index = this.links.indexOf(link);\n if (index >= 0) {\n this.links.splice(index, 1);\n }\n if (this.sources.get(worker) === registration) {\n this.sources.delete(worker);\n }\n };\n }\n\n /**\n * Sends journey state changes over every link in the journey scope.\n * @param journey Active journey or null if ended.\n */\n broadcastJourney(journey: Journey | null): void {\n this.postJourney({ t: BUS_TYPE.journey, from: this.contextId, journey });\n }\n\n /** Closes all open links and clears internal state. */\n destroy(): void {\n this.sources.clear();\n this.directReplies.clear();\n this.flushQueue = [];\n this.destroyed = true;\n clearInterval(this.rulesPoll);\n this.rulesPoll = undefined;\n for (const link of this.allLinks()) {\n link.close();\n }\n this.links.length = 0;\n this.upstream = null;\n this.ownerId = null;\n this.openFinLink = null;\n }\n\n /** Returns all unique active links including upstream. */\n private allLinks(): Link[] {\n if (!this.upstream || this.links.includes(this.upstream)) {\n return this.links;\n }\n return [...this.links, this.upstream];\n }\n\n /** Sends a message only over links of the given kind. */\n private postOver(link: LinkKind, message: BusMessage): void {\n for (const candidate of this.allLinks()) {\n if (candidate.kind === link) {\n candidate.post(message);\n }\n }\n }\n\n /** Sends a journey message over every link in the journey scope. */\n private postJourney(message: BusMessage): void {\n for (const link of this.allLinks()) {\n if (this.journeyLink(link.kind)) {\n link.post(message);\n }\n }\n }\n\n /** Routes incoming messages to registered handlers or upstream targets. */\n private readonly receive = (message: BusMessage, source: MessageSource): void => {\n // Anything arriving here on the direct link is an answer from the parent, because\n // acceptDirect() handles a direct child's messages. That leaves only the children and worker\n // links carrying child traffic.\n const child = source.link === \"children\" || source.link === \"worker\";\n if (this.acceptsMessage(message, source, child)) {\n this.routeMessage(message, source);\n }\n };\n\n /**\n * Checks the source, the message limits and the message shape before delivery.\n * @param message Message from the source.\n * @param source Link and identity of the source.\n * @param child True if the source is a child of this context.\n * @returns True if the bus can accept the message.\n */\n private acceptsMessage(message: BusMessage, source: MessageSource, child: boolean): boolean {\n if (this.destroyed) {\n return false;\n }\n\n let accepted: boolean;\n try {\n accepted = this.passesChecks(message, source, child);\n } catch {\n // Either a value JSON can't encode or a non-finite number fails the checks.\n // The count below reports the rejection.\n accepted = false;\n }\n\n if (!accepted) {\n this.diagnostics.count(\"bus.rejected_message\");\n }\n return accepted;\n }\n\n /**\n * Runs the source, budget, shape and permission checks. A failed check returns false instead\n * of throwing, so a flood of rejected messages builds no stack traces. Only the JSON encoding\n * can throw, and acceptsMessage catches that.\n * @param message Message from the source.\n * @param source Link and identity of the source.\n * @param child True if the source is a child of this context.\n * @returns True if the message passes every check.\n */\n private passesChecks(message: BusMessage, source: MessageSource, child: boolean): boolean {\n const { bus } = this.config;\n const registration =\n typeof source.peer === \"object\" ? this.sources.get(source.peer) : undefined;\n if (child && bus.sourcePolicy === \"registered\" && !registration) {\n return false;\n }\n\n const object = typeof source.peer === \"object\" ? source.peer : undefined;\n const key = typeof source.peer === \"string\" ? source.peer : source.link;\n const now = Date.now();\n const rate = (object ? this.rates.get(object) : this.channelRates.get(key)) ?? {\n start: now,\n count: 0,\n };\n if (object) {\n this.rates.set(object, rate);\n } else {\n for (const [peer, entry] of this.channelRates) {\n if (windowEnded(entry, 1000, now)) {\n this.channelRates.delete(peer);\n }\n }\n if (this.channelRates.size >= BUS_MAX_TRACKED_SOURCES && !this.channelRates.has(key)) {\n return false;\n }\n this.channelRates.set(key, rate);\n }\n\n // With no limit the window still counts, without a cap, so a named source's window stays\n // current.\n if (!countInWindow(rate, bus.maxMessagesPerSecond ?? Infinity, 1000)) {\n return false;\n }\n\n const encoded = JSON.stringify(message, (_key, value: unknown) => {\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw new Error(\"Non-finite value\");\n }\n return value;\n });\n if (\n bus.maxMessageBytes !== null &&\n new TextEncoder().encode(encoded).length > bus.maxMessageBytes\n ) {\n return false;\n }\n if (!validMessage(message)) {\n return false;\n }\n if (\n message.t === BUS_TYPE.records &&\n bus.maxRecordsPerMessage !== null &&\n message.records.length > bus.maxRecordsPerMessage\n ) {\n return false;\n }\n\n if (registration) {\n // A flush request asks for the delivery of records, so it needs the same permission.\n const permission =\n message.t === BUS_TYPE.records || message.t === BUS_TYPE.flushRequest\n ? \"records\"\n : message.t === BUS_TYPE.journey\n ? \"journey:write\"\n : message.t === BUS_TYPE.journeyRequest\n ? \"journey:read\"\n : message.t === BUS_TYPE.samplingRequest\n ? \"sampling:read\"\n : undefined;\n if (permission && !registration.permissions?.includes(permission)) {\n return false;\n }\n }\n\n // Only an upstream owner can publish these control messages.\n if (\n child &&\n (message.t === BUS_TYPE.sampling ||\n message.t === BUS_TYPE.securityContext ||\n message.t === BUS_TYPE.flushResult)\n ) {\n return false;\n }\n\n // Broadcast reaches each tab on the origin, so no tab may ask the others to flush.\n if (source.link === \"broadcast\" && message.t === BUS_TYPE.flushRequest) {\n return false;\n }\n\n // Under the registered policy, broadcast is a control channel only and carries no records.\n return !(\n bus.sourcePolicy === \"registered\" &&\n source.link === \"broadcast\" &&\n message.t === BUS_TYPE.records\n );\n }\n\n /**\n * Hands an accepted message to its handler or to the upstream link.\n * @param message Message that passed the source and shape checks.\n * @param source Link and identity of the source.\n */\n private routeMessage(message: BusMessage, source: MessageSource): void {\n if (message.from === this.contextId) {\n return;\n }\n\n switch (message.t) {\n case BUS_TYPE.hello:\n if (this.canOwn(source.link)) {\n // While this context still waits for its own owner, its id is only temporary, so send\n // none. announce() sends the final id once the role is known.\n this.answer(source, {\n t: BUS_TYPE.welcome,\n from: this.contextId,\n to: message.from,\n tabId: this.tabId,\n routingContextId: this.awaitingWelcome\n ? undefined\n : this.config.securityContext.id || undefined,\n });\n }\n break;\n\n case BUS_TYPE.welcome:\n if (message.to !== this.contextId) {\n break;\n }\n if (\n this.awaitingWelcome?.link === source.link ||\n (this.upstream?.kind === source.link && this.ownerId === null)\n ) {\n // Remember the owner. On a shared link, only the owner may set this context's journey.\n this.ownerId = message.from;\n this.ownerPeer = source.peer;\n const before = this.config.securityContext.id;\n if (\n message.routingContextId &&\n this.handlers.onSecurityContext?.(message.routingContextId) === false\n ) {\n break;\n }\n // Our children may still hold the old id, so pass the owner's id on to them. During a\n // handshake the role can still be \"sender\", so don't send on the OpenFin link here.\n if (this.config.securityContext.id !== before) {\n this.passContext(false);\n }\n this.awaitingWelcome?.settle(true);\n }\n break;\n\n case BUS_TYPE.records:\n if (\n this.config.securityContext.isolation &&\n this.config.securityContext.id &&\n message.routingContextId !== this.config.securityContext.id\n ) {\n this.diagnostics.count(\"security.context_mismatch\");\n break;\n }\n // A paused forwarder takes only the records it would relay, never its owner's traffic.\n if (this.role === \"sender\" || (this.handlers.paused?.() && this.canRelay(source.link))) {\n this.handlers.onRecords(message.records);\n } else if (this.upstream && this.canRelay(source.link)) {\n // Relays records upstream in nested frame chains.\n this.upstream.post(message);\n }\n break;\n\n case BUS_TYPE.securityContext:\n if (\n source.link === this.upstream?.kind &&\n this.ownerId === message.from &&\n this.ownerPeer === source.peer\n ) {\n if (this.handlers.onSecurityContext?.(message.id) !== false) {\n this.rotateContext();\n }\n }\n break;\n\n case BUS_TYPE.journey:\n if (this.acceptsJourney(message, source)) {\n this.applyJourney(message.journey);\n }\n break;\n\n case BUS_TYPE.journeyRequest: {\n const current = this.handlers.onJourneyRequest();\n // Address the answer, so that every other context on a shared link ignores it.\n if (current && this.journeyLink(source.link)) {\n this.answer(source, {\n t: BUS_TYPE.journey,\n from: this.contextId,\n to: message.from,\n journey: current,\n });\n }\n break;\n }\n\n case BUS_TYPE.samplingRequest:\n // A forwarder answers only its own children, although siblings on its upstream link ask\n // too. Siblings answering each other on OpenFin would mean N squared messages, and a\n // stale copy could win.\n if (\n this.role === \"forwarder\" ? source.link !== this.upstream?.kind : this.canOwn(source.link)\n ) {\n this.answer(source, this.rulesAnswer(message.from));\n }\n break;\n\n case BUS_TYPE.sampling:\n if (this.acceptsRules(message.to, source)) {\n this.applyRules(message.rules);\n }\n break;\n\n case BUS_TYPE.flushRequest:\n // The links that may send records: a sender takes each one, and a forwarder its own\n // children, never a sibling on its upstream link.\n if (this.role === \"sender\" || this.canRelay(source.link)) {\n this.queueFlush(message, source);\n }\n break;\n\n case BUS_TYPE.flushResult:\n this.settleFlush(message, source);\n break;\n\n case BUS_TYPE.tab:\n // Only two different contexts on the broadcast channel can collide. The id comparison\n // picks one of the pair, otherwise both would report the conflict and rename.\n if (\n source.link === \"broadcast\" &&\n message.tabId === this.tabId &&\n this.contextId > message.from\n ) {\n this.handlers.onTabConflict();\n }\n break;\n }\n }\n\n /**\n * Queues a child's flush request. The first request runs its flush alone, and the requests\n * that arrive meanwhile share one flush after it, so a flood has one flush running at most.\n * @param message The request.\n * @param source Link and identity of the child, which gets the answer.\n */\n private queueFlush(\n message: Extract<BusMessage, { t: typeof BUS_TYPE.flushRequest }>,\n source: MessageSource,\n ): void {\n const from = source.peer ?? source.link;\n const own = this.flushQueue.filter((wait) => wait.source === from).length;\n if (\n this.flushQueue.length >= BUS_MAX_FLUSH_REQUESTS ||\n own >= BUS_MAX_FLUSH_REQUESTS_PER_SOURCE\n ) {\n this.diagnostics.count(\"bus.rejected_message\");\n return;\n }\n\n const timeoutMs = Math.min(Math.max(message.timeoutMs, 0), FLUSH_TIMEOUT_MAX_MS);\n this.flushQueue.push({\n source: from,\n ends: Date.now() + timeoutMs,\n answer: (result) => {\n this.answer(source, {\n t: BUS_TYPE.flushResult,\n from: this.contextId,\n id: message.id,\n result,\n });\n },\n });\n\n if (!this.flushing) {\n void this.runFlushes();\n }\n }\n\n /**\n * Runs one flush for the waiting requests, and one more while new requests wait. Two flushes\n * start at least BUS_FLUSH_GAP_MS apart, and a request in the gap joins the next one.\n */\n private async runFlushes(): Promise<void> {\n this.flushing = true;\n\n try {\n while (this.flushQueue.length > 0) {\n const gap = this.flushedAt + BUS_FLUSH_GAP_MS - Date.now();\n // Wait only when the gap isn't over, so the first request's flush starts at once.\n if (gap > 0) {\n await new Promise<void>((resolve) => {\n unrefTimer(setTimeout(resolve, gap));\n });\n }\n\n // Only destroy() empties the queue during the gap, and then no child waits for an answer.\n if (this.flushQueue.length === 0) {\n return;\n }\n\n this.flushedAt = Date.now();\n const waiting = this.flushQueue;\n this.flushQueue = [];\n // The latest end, so a short request doesn't cut the others' wait. The flush still ends\n // once its batches end.\n const ends = Math.max(...waiting.map((wait) => wait.ends));\n const result = await this.diagnostics.guardAsync(\n \"pipeline.crashed\",\n \"The flush that a child context asked for failed. The child gets no answer.\",\n async () => this.handlers.onFlush?.(Math.max(0, ends - Date.now())),\n );\n\n if (result && !this.destroyed) {\n for (const wait of waiting) {\n // A child whose reply throws must not cost the next child its answer.\n this.diagnostics.guard(\n \"bus.send_failed\",\n \"The answer to a flush request failed.\",\n () => {\n wait.answer(result);\n },\n );\n }\n }\n }\n } finally {\n this.flushing = false;\n }\n }\n\n /**\n * Hands a flush answer to the request that waits for it. Only the upstream owner can answer,\n * because a sibling on a shared link can read the request's id.\n * @param message The answer.\n * @param source Link and identity of the sender of the answer.\n */\n private settleFlush(\n message: Extract<BusMessage, { t: typeof BUS_TYPE.flushResult }>,\n source: MessageSource,\n ): void {\n const settle = this.flushAnswers.get(message.id);\n // Each view on the OpenFin link reads each answer, so there the owner's identity must be known.\n const peer =\n this.ownerPeer === undefined ? source.link !== \"openfin\" : this.ownerPeer === source.peer;\n if (!settle || !peer || !this.fromOwner(message.from, source.link)) {\n return;\n }\n\n let result: FlushResult | null;\n try {\n result = readFlushResult(message.result);\n } catch {\n // A getter on a same-origin parent's object can throw on this second read.\n result = null;\n }\n\n if (!result) {\n this.diagnostics.count(\"bus.rejected_message\");\n return;\n }\n\n settle(result);\n }\n\n /**\n * Answers whoever sent a message. A link that can address a single source sends to it only.\n * @param source Link and identity of the source.\n * @param message Answer to send.\n */\n private answer(source: MessageSource, message: BusMessage): void {\n if (source.reply) {\n source.reply(message);\n return;\n }\n this.postOver(source.link, message);\n }\n\n /**\n * Checks whether records from a link can go upstream. Records sent back out on the link\n * they arrived on would return to their sender. A direct link is the exception, because\n * each one is a single call into one parent, so two direct links in a chain are\n * different links.\n * @param link Kind of the link the records arrived on.\n * @returns True if the relay is safe.\n */\n private canRelay(link: LinkKind): boolean {\n return link === \"direct\" || link !== this.upstream?.kind;\n }\n\n /** Checks whether this context can own the given link type. */\n private canOwn(link: LinkKind): boolean {\n // A forwarder that knows its owner also owns its own children and relays their records\n // upstream.\n const owner = this.role === \"sender\" || this.ownerId !== null;\n if (!owner) {\n return false;\n }\n if (link === \"openfin\") {\n return this.role === \"sender\" && this.isOpenFinProvider;\n }\n return OWNED.includes(link);\n }\n\n /** Works out whether this context is the OpenFin platform provider. */\n private resolveOpenFinProvider(): boolean {\n const configured = this.config.bus.openFinRole;\n if (configured !== \"auto\") {\n return configured === \"provider\";\n }\n if (this.platform.platform !== \"openfin\" && this.platform.platform !== \"openfin_web\") {\n return false;\n }\n\n const me = getFin()?.me;\n if (!me?.identity || me.isView) {\n return false;\n }\n return Boolean(me.identity.name && me.identity.name === me.identity.uuid);\n }\n\n /** Resolves the handshake orphan policy for the current platform context. */\n private orphanPolicy(): \"promote\" | \"retry\" {\n return this.isCrossOriginFrame() ? \"retry\" : \"promote\";\n }\n\n /** Checks whether a cross-origin boundary blocks access to the parent window. */\n private isCrossOriginFrame(): boolean {\n if (typeof window === \"undefined\" || window.parent === window) {\n return false;\n }\n try {\n // A cross-origin parent throws on this read. It goes through Reflect.get because lint\n // rejects a bare property read.\n Reflect.get(window.parent, \"location\");\n return false;\n } catch {\n return true;\n }\n }\n\n /** Identifies the candidate upstream link based on platform hierarchy. */\n private candidateUpstream(): Link | null {\n if (this.platform.isWorker) {\n return createOwnerLink(this.receive, this.diagnostics);\n }\n if (!this.platform.isTopLevelDocument) {\n return createParentLink(this.receive, this.config.bus.trustedOrigins, this.diagnostics);\n }\n if (this.platform.platform === \"openfin\" && !this.isOpenFinProvider) {\n return this.ensureOpenFinLink();\n }\n return null;\n }\n\n /** Opens control links supported by the current runtime environment. */\n private openControlLinks(): void {\n const push = (link: Link | null): void => {\n if (link) {\n this.links.push(link);\n }\n };\n\n if (!this.platform.isWorker) {\n this.ensureChildrenLink();\n }\n if (this.platform.isTopLevelDocument) {\n push(createBroadcastLink(BUS_CHANNEL_NAME, this.receive, this.diagnostics));\n }\n if (this.platform.platform === \"openfin\" || this.platform.platform === \"openfin_web\") {\n push(this.ensureOpenFinLink());\n }\n }\n\n /** Opens the link to child frames if it is not already open. */\n private ensureChildrenLink(): void {\n if (this.links.some((link) => link.kind === \"children\")) {\n return;\n }\n const link = createChildrenLink(\n this.receive,\n this.config.bus.trustedOrigins,\n this.diagnostics,\n (source, origin) => {\n const accepted = this.isRegistered(source, origin);\n if (!accepted) {\n this.diagnostics.count(\"bus.rejected_message\");\n // A registered window speaking from another origin is untrusted too. Without this\n // report, a registration with the wrong origin silences the frame with no named cause.\n const registered = source !== null && this.sources.has(source);\n const trusted =\n origin === frameOrigin() || this.config.bus.trustedOrigins.includes(origin);\n if (registered || !trusted) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n \"The bus rejected a message from an untrusted origin.\",\n );\n }\n }\n return accepted;\n },\n (message, source) => this.mayPost(message, source),\n );\n if (link) {\n this.links.push(link);\n }\n }\n\n /** Returns the singleton OpenFin InterApplicationBus link. */\n private ensureOpenFinLink(): Link | null {\n this.openFinLink ??= createOpenFinLink(\n BUS_CHANNEL_NAME,\n this.platform.openfinUuid,\n this.receive,\n this.diagnostics,\n );\n return this.openFinLink;\n }\n\n /**\n * Runs a hello/welcome handshake over the candidate link.\n * @param candidate Upstream link candidate.\n * @returns True if the welcome arrived before the timeout.\n */\n private handshake(candidate: Link): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n\n const finish = (result: boolean): void => {\n if (settled) {\n return;\n }\n settled = true;\n this.awaitingWelcome = null;\n clearTimeout(timer);\n resolve(result);\n };\n\n this.awaitingWelcome = { link: candidate.kind, settle: finish };\n // finish reads timer, which is declared after it. That's safe, because finish can only\n // run after the post below, and by then the timer exists.\n const timer = setTimeout(() => {\n finish(false);\n }, this.handshakeOptions.timeoutMs);\n unrefTimer(timer);\n candidate.post({ t: BUS_TYPE.hello, from: this.contextId, tabId: this.tabId });\n });\n }\n\n /** Broadcasts tab claim and queries existing journey state. */\n private announce(): void {\n this.postOver(\"broadcast\", {\n t: BUS_TYPE.tab,\n from: this.contextId,\n tabId: this.tabId,\n });\n if (this.upstream && this.ownerId === null) {\n this.upstream.post({ t: BUS_TYPE.hello, from: this.contextId, tabId: this.tabId });\n }\n this.postJourney({ t: BUS_TYPE.journeyRequest, from: this.contextId });\n this.pollRules();\n // The role is final now. Children welcomed during the handshake got no id, so send it now.\n this.passContext(false);\n }\n\n /**\n * Resolves the journey scope. \"auto\" becomes \"origin\" in OpenFin and \"tab\" in a browser.\n * @returns The scope in effect.\n */\n private journeyScope(): ResolvedScope {\n const { scope } = this.config.journey;\n if (scope !== \"auto\") {\n return scope;\n }\n\n const { platform } = this.platform;\n return platform === \"openfin\" || platform === \"openfin_web\" ? \"origin\" : \"tab\";\n }\n\n /**\n * Checks whether a link carries journey messages in the current scope.\n * Only \"origin\" uses the broadcast link, which reaches every tab on the origin.\n * @param link Link kind.\n * @returns True if the link carries journey messages.\n */\n private journeyLink(link: LinkKind): boolean {\n const scope = this.journeyScope();\n if (scope === \"context\") {\n return false;\n }\n\n return scope === \"origin\" || link !== \"broadcast\";\n }\n\n /**\n * Checks whether this context adopts a journey message.\n * @param message Journey message.\n * @param source Link and origin of the message.\n * @returns True for a message on a journey link, addressed to this context, from an accepted\n * sender. In \"tab\" scope, the only accepted sender is a forwarder's owner.\n */\n private acceptsJourney(\n message: Extract<BusMessage, { t: typeof BUS_TYPE.journey }>,\n source: MessageSource,\n ): boolean {\n if (!this.journeyLink(source.link)) {\n return false;\n }\n\n if (message.to !== undefined && message.to !== this.contextId) {\n return false;\n }\n\n return (\n this.journeyScope() === \"origin\" ||\n (this.fromOwner(message.from, source.link) &&\n (this.ownerPeer === undefined || this.ownerPeer === source.peer))\n );\n }\n\n /**\n * Checks whether a message comes from this forwarder's upstream owner.\n * @param from Context id of the sender.\n * @param link Link kind of the message.\n * @returns True for the upstream link and, after a handshake, the owner that answered it.\n */\n private fromOwner(from: string, link: LinkKind): boolean {\n if (this.role !== \"forwarder\" || link !== this.upstream?.kind) {\n return false;\n }\n\n return this.ownerId === null || from === this.ownerId;\n }\n\n /**\n * Parses a journey payload from another realm and hands it to the runtime.\n * @param payload Journey, or null when the journey ended.\n */\n private applyJourney(payload: unknown): void {\n if (payload === null) {\n this.handlers.onJourney(null);\n return;\n }\n\n const journey = parseJourney(payload);\n if (journey === null) {\n this.diagnostics.report(\n \"record.dropped_malformed\",\n \"The bus dropped a journey message. Its payload is not a journey.\",\n { type: \"journey\" },\n );\n return;\n }\n\n this.handlers.onJourney(journey);\n }\n\n /**\n * Builds the answer to a sampling question. Null rules clear the forwarder's copy.\n * @param to Context id of the forwarder that asked.\n * @returns The answer.\n */\n private rulesAnswer(to: string): BusMessage {\n const rules = this.handlers.remote.sampling?.wire() ?? null;\n\n return { t: BUS_TYPE.sampling, from: this.contextId, to, rules };\n }\n\n /**\n * Checks whether this context accepts sampling rules from a source.\n * @param to Context id that the answer names.\n * @param source Link and origin of the answer.\n * @returns True only for an answer from the upstream owner to this context.\n */\n private acceptsRules(to: string, source: MessageSource): boolean {\n // Accept rules only from the upstream owner. A sibling on a shared link isn't trusted.\n if (this.role !== \"forwarder\" || to !== this.contextId || source.link !== this.upstream?.kind) {\n return false;\n }\n\n // A page on another origin can embed this app. Don't let it lower minLevel and read the\n // records. A srcdoc frame's location.origin reads \"null\", so compare with its real origin,\n // as the parent link does.\n const { origin } = source;\n\n if (\n source.link === \"parent\" &&\n origin !== frameOrigin() &&\n !this.config.bus.trustedOrigins.includes(origin)\n ) {\n this.diagnostics.report(\n \"bus.untrusted_origin\",\n `The bus ignored sampling rules from ${origin}. If you own this origin, add it to bus.trustedOrigins.`,\n { origin, type: \"sampling\" },\n );\n return false;\n }\n\n return this.ownerPeer === undefined || this.ownerPeer === source.peer;\n }\n\n /**\n * Applies the rules from an answer, ignoring any that are invalid.\n * @param raw The answer's rules, or null when the upstream has none.\n */\n private applyRules(raw: unknown): void {\n if (raw === null) {\n applyRemote(this.handlers.remote, this.config, null);\n return;\n }\n\n const update = parseRemoteRules(raw, this.diagnostics);\n\n if (update) {\n applyRemote(this.handlers.remote, this.config, update);\n }\n }\n\n /**\n * Asks the upstream owner for the remote sampling rules now, then on every poll interval.\n * A direct link can't push the rules to a child, but a poll works on every link kind.\n */\n private pollRules(): void {\n const { upstream } = this;\n\n if (this.destroyed || this.role !== \"forwarder\" || !upstream) {\n return;\n }\n\n // Read the config on every poll, because a later configure() can turn remote sampling on\n // or off.\n const ask = (): void => {\n if (this.config.sampling.remote) {\n upstream.post({ t: BUS_TYPE.samplingRequest, from: this.contextId });\n }\n };\n\n ask();\n this.rulesPoll = setInterval(ask, REMOTE_SAMPLING_POLL_MS);\n unrefTimer(this.rulesPoll);\n }\n}\n"],"mappings":"A,kYAWA,IAAM+B,EAAqC,CAAC,WAAY,UAAW,UAAU,EAO7E,SAAgBC,EAAa,EAAqC,CAChE,GAAI,OAAOC,GAAU,WAAYA,EAC/B,MAAO,GAET,IAAMC,EAAID,EACV,GAAI,OAAOC,EAAE,MAAS,UAAY,CAACA,EAAE,MAAQ,OAAOA,EAAE,GAAM,SAC1D,MAAO,GAET,IAAMC,EAAQ,GAAyB,OAAOD,EAAEE,IAAS,SACzD,OAAQF,EAAE,EAAV,CACE,KAAKlC,EAAAA,EAAS,MACd,KAAKA,EAAAA,EAAS,IACZ,OAAOmC,EAAK,OAAO,EACrB,KAAKnC,EAAAA,EAAS,QACZ,OACEmC,EAAK,IAAI,GACTA,EAAK,OAAO,IACXD,EAAE,mBAAqB,IAAA,IAAaC,EAAK,kBAAkB,GAEhE,KAAKnC,EAAAA,EAAS,eACd,KAAKA,EAAAA,EAAS,gBACZ,MAAO,GACT,KAAKA,EAAAA,EAAS,gBACZ,OAAOmC,EAAK,IAAI,GAAKD,EAAE,KAAO,GAChC,KAAKlC,EAAAA,EAAS,QACZ,OAA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AM,UAAW,CAC7B,EACO,IAGF,KAAK,YAAc,IAAA,IAAa,KAAK,YAAc+B,EAAO,IACnE,CAMA,WAAmB,EAAoB,CACrC,GAAIY,IAAQ,KAAM,CAChB3E,EAAA,EAAY,KAAK,SAAS,OAAQ,KAAK,OAAQ,IAAI,EACnD,MACF,CAEA,IAAM2J,EAAS/J,EAAAA,EAAiB+E,EAAK,KAAK,WAAW,EAEjDgF,GACF3J,EAAA,EAAY,KAAK,SAAS,OAAQ,KAAK,OAAQ2J,CAAM,CAEzD,CAMA,WAA0B,CACxB,GAAM,CAAE,YAAa,KAErB,GAAI,KAAK,WAAa,KAAK,OAAS,aAAe,CAACpC,EAClD,OAKF,IAAMqC,MAAkB,CAClB,KAAK,OAAO,SAAS,QACvBrC,EAAS,KAAK,CAAE,EAAGpI,EAAAA,EAAS,gBAAiB,KAAM,KAAK,SAAU,CAAC,CAEvE,EAEAyK,EAAI,EACJ,KAAK,UAAY,YAAYA,EAAK/J,EAAAA,EAAuB,EACzDS,EAAA,EAAW,KAAK,SAAS,CAC3B,CACF,E"}
@@ -1,2 +0,0 @@
1
- const e=require("./constants-CqdJhTxH.cjs"),t=require("./guards-EjG3ahFp.cjs");var n=Object.keys(e.kt),r=[`gzip`,`none`],i=[`omit`,`same-origin`,`include`],a=[`auto`,`indexeddb`,`localstorage`,`memory`,`none`],o=[`storage`,`memory`],s=[`auto`,`sender`,`forwarder`,`off`],c=[`auto`,`provider`,`client`],l=[`auto`,`context`,`tab`,`origin`],u=[`error`,`warn`,`info`,`log`],d=[`action`,`event`,`metric`,`log`,`system`,`span`],f={logFlushIntervalMs:[100,6e4],logBatchSize:[1,1e3],metricBatchSize:[1,1e3]},p=[1,5e3],ee=[6e4,6048e5],te=[1,20],ne={maxBodyChars:[256,65536],maxAttributeChars:[256,65536],maxAttributeCount:[1,1024],maxStackChars:[256,65536],maxDepth:[1,16],maxArrayLength:[1,1e4],maxNodes:[100,1e5],maxRecordBytes:[1024,e.D]},re=[6e4,864e5],m=[0,2147483647],h=[1,m[1]],g=[0,2**53-1],_=[1,2**53-1],v=[100,1e4],y=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),b=e=>Array.isArray(e)&&e.every(e=>typeof e==`function`),x=e=>e===null||typeof e==`function`,S=e=>e===null,ie=/^[a-z][a-z\d+.-]*:/i,C=e=>typeof e==`number`&&e>=0&&e<=1,w=`a function or null`,T=`a URL string or null`,ae=e=>x(e)||E(e)&&Object.values(e).every(e=>typeof e==`string`),E=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function D(e,t,n=I){return(r,i,a,o)=>i===void 0?a:e(i)?i:(R(o,r,t,i,`the current value`,n),a)}function oe(){return typeof document<`u`?document.baseURI:typeof location>`u`?void 0:location.href}function O(e,t,n,r){let i;try{i=new URL(t,oe())}catch(t){return r.report(`config.invalid`,`${e} is not a valid URL. The library keeps the current value.`,void 0,t),n}return i.username!==``||i.password!==``?(r.report(`config.invalid`,`${e} has a user name or a password. The library keeps the current value.`),n):ie.test(t)?t:(r.report(`config.invalid`,`${e} is relative. The library sends to ${i.origin}.`),i.href)}function k(e,t,n,r){return typeof t==`string`?t.trim()===``?(r.report(`config.invalid`,`${e} is empty. The library turns it off. Use null to turn it off.`),null):t===n?t:O(e,t,n,r):D(S,T,L)(e,t,n,r)}function A(e,t,n){return typeof e==`string`?e===``||e===t?e:e.trim()===``?(n.report(`config.invalid`,`endpoint is blank. The library keeps the current value.`),t):O(`endpoint`,e,t,n):D(S,T,L)(`endpoint`,e,t,n)}var j={captureLimits:{ranges:{breadcrumbs:[0,1e6],errorDedupeMs:m,windowMs:h},limits:{errorsPerWindow:g,consolePerWindow:g,longFramesPerWindow:g,webSocketPerWindow:g,reportsPerWindow:g,resourcesPerWindow:g,lifecyclePerWindow:g}},metadata:{ranges:{},limits:{}},storage:{ranges:{},limits:{},choices:{backend:a}},diagnostics:{ranges:{throttleMs:m},limits:{},custom:{records:ve}},correlation:{ranges:{},limits:{sessionIdleMs:h,traceMaxAgeMs:h}},metrics:{ranges:{intervalMs:[1e3,6e5]},limits:{maxSeries:g,maxInstruments:g,maxHistogramBoundaries:g}},buffering:{ranges:{maxHeldRecords:[200,1e4]},limits:{maxPendingRecords:_,maxPendingBytes:_},choices:{overflow:[`drop-oldest`,`drop-newest`,`persist`]}},delivery:{ranges:{requestTimeoutMs:[1,m[1]],maxConcurrentRequests:_,retryBaseDelayMs:m,retryMaxDelayMs:m},limits:{},choices:{priority:[`low`,`auto`,`high`]}},debugBuffer:{ranges:{maxRecords:[1,1e4]},limits:{maxAgeMs:h}},profiler:{ranges:{maxProbes:[1,e.Xt]},limits:{}},replay:{ranges:{bufferMs:[5e3,6e5],maxBufferBytes:[1e5,2e8],afterErrorMs:[0,6e5],uploadWindowMs:h,maxSegmentEvents:[1,1e4],maxSegmentBytes:[1e4,1e7],flushIntervalMs:[100,6e4],maxQueueBytes:[1e5,2e8],maxAttempts:[1,10]},limits:{uploadsPerWindow:g},choices:{mode:[`onError`]},custom:{endpoint:k,maskSelectors:D(y,`a list of strings`),blockSelectors:D(y,`a list of strings`),loader:D(x,w,L),onSegment:D(x,w,L),headers:D(ae,`an object of strings, a function or null`,L),plugins:D(b,`a list of functions`),recordOptions:D(E,`an object`)}}},se=[`errors`,`rejections`,`resourceErrors`,`fetch`,`xhr`,`httpMetrics`,`navigation`,`fullUrls`,`webSocket`,`uncleanExit`,`serverTiming`,`reports`,`lifecycle`],ce=`null`,M=`a level name: ${F(n)}`,le=`a list of ${F(u)}`,N=`a list of strings and RegExp patterns`,ue=`a list of origin URLs such as "https://api.example" and RegExp patterns`,de=`a list of origin URLs such as "https://app.example". For a sandboxed frame, set bus.mode: "sender" in the frame`,fe=`a list of log types: ${F(d)}`,P=`true, false or a list of diagnostic codes`;function F(e){let t=e.map(e=>`"${e}"`);return`${t.slice(0,-1).join(`, `)} or ${t[t.length-1]}`}function I(e){return typeof e==`string`?`"${e}"`:typeof e==`function`?`a function`:typeof e==`object`&&e?`an object`:String(e)}function L(e){return e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:`a ${typeof e}`}function R(e,t,n,r,i,a=I){e.report(`config.invalid`,`${t} must be ${n}. The value is ${a(r)}. The library keeps ${i}.`)}function z(e,t,n,r,i){if(t===void 0)return r;let a=n.find(e=>e===t);return a===void 0?(i.report(`config.invalid`,`${e} must be ${F(n)}. The library keeps "${r}".`),r):a}function B(e,t,n,r){return t===void 0?n:typeof t==`boolean`?t:(R(r,e,`true or false`,t,String(n)),n)}function V(e,t,n,r){return t===void 0?n:typeof t==`number`&&Number.isFinite(t)&&t>=0?t:(R(r,e,`a finite number of 0 or more`,t,String(n)),n)}function H(e,t,n,r,i){if(t===void 0)return r;let[a,o]=n;return typeof t==`number`&&Number.isInteger(t)&&t>=a&&t<=o?t:(R(i,e,`an integer from ${String(a)} to ${String(o)}`,t,String(r)),r)}function U(e,t,n,r,i){if(t===void 0)return r;if(t===null)return null;let[a,o]=n;return typeof t==`number`&&Number.isInteger(t)&&t>=a&&t<=o?t:(R(i,e,`an integer from ${String(a)} to ${String(o)}, or null for no limit`,t,String(r)),r)}function W(e,t,n,r){if(t===void 0)return n;if(t!==null)return typeof t==`function`?t:(R(r,e,w,t,`the current value`,L),n)}var G=()=>null;function pe(e,t,n){return e==null||typeof e==`function`||t?W(`redact`,e,t,n):(n.report(`config.invalid`,`redact must be ${w}. The value is ${L(e)}. The library drops each record until redact is a function or null.`),G)}function me(e,t,n){return e===void 0?t:b(e)?[...e]:t.length>0?(R(n,`processors`,`a list of functions`,e,`the current list`,L),t):(n.report(`config.invalid`,`processors must be a list of functions. The value is ${L(e)}. The library drops each record until processors is a list of functions or [].`),[G])}function K(e,t,n,r){return t===void 0?n:typeof t==`string`?t:(R(r,e,`a string`,t,`the current value`),n)}function q(e,t,n,r){return t===void 0?n:C(t)?t:(r.report(`config.invalid`,`${e} must be 0..1. The value is ${I(t)}. The library keeps ${String(n)}.`),n)}function he(e,n,r){if(e===void 0)return n;if(!t.n(e))return R(r,`sampling.rates`,`an object of rates`,e,`the current value`),n;let i=[];for(let[t,n]of Object.entries(e))C(n)?i.push([t,n]):n!==void 0&&r.report(`config.invalid`,`sampling.rates["${t}"] must be 0..1. The value is ${I(n)}. The library ignores this entry.`);return Object.fromEntries(i)}function J(e,t,n,r,i){let a=t??{},o=Object.keys(r);return Object.fromEntries(o.map(t=>[t,H(`${e}.${t}`,a[t],r[t],n[t],i)]))}function Y(e){if(typeof e!=`string`)return;let t=e.toUpperCase();return n.find(e=>e===t)}function X(e,t,n,r){if(t===void 0)return n;let i=Y(t);return i===void 0?(R(r,e,M,t,`"${n}"`),n):i}function ge(e,n,r){if(e===void 0)return n;if(!t.n(e))return R(r,`minLevels`,`an object of level names`,e,`the current value`),n;let i=[];for(let[t,n]of Object.entries(e)){let e=Y(n);t!==``&&e!==void 0?i.push([t,e]):R(r,`minLevels["${t}"]`,M,n,`minLevel for it`)}return Object.fromEntries(i)}function Z(e,t,n,r,i,a){if(t===void 0)return n;if(!Array.isArray(t))return R(a,e,r,t,`the current list`),n;let o=[],s=t;for(let t of s){let n=i(t);n===void 0?a.report(`config.invalid`,`The library ignores the ${e} entry ${I(t)}. ${e} must be ${r}.`):o.push(n)}return o}function _e(e){return t.n(e)&&typeof e.name==`string`&&e.name!==``&&typeof e.install==`function`&&typeof e.uninstall==`function`?e:void 0}function ve(e,t,n,r){return t===void 0||typeof t==`boolean`?t??n:Array.isArray(t)?Z(e,t,[],P,ye,r):(R(r,e,P,t,`the current value`),n)}function ye(e){return typeof e==`string`?e:void 0}function be(e){return d.find(t=>t===e)}function Q(e){return typeof e==`string`||e instanceof RegExp?e:void 0}function xe(e){return u.find(t=>t===e)}function Se(e){if(typeof e==`string`)try{let{origin:t}=new URL(e);return t===ce?void 0:t}catch{return}}function Ce(e){return e instanceof RegExp?e:Se(e)}function we(e){return t.n(e)?Object.values(e).every(e=>typeof e==`string`):!1}function Te(e,t,n){if(e===void 0)return t;if(e!==null)return typeof e==`function`||we(e)?e:(n.report(`config.invalid`,`headers must be an object of strings or a function. The library keeps the current headers.`),t)}function Ee(e){return typeof e!=`object`||!e?!1:typeof Reflect.get(e,`serialize`)==`function`}function De(t,n,r){return t===void 0?n??`otlp`:t===`otlp`||t===`ecs`||Ee(t)?t:(r.report(`config.invalid`,`serializer must be "${e.Fn}", "ecs" or an implementation. The library keeps the current serializer.`),n??`otlp`)}var Oe=new Set(Object.keys(e.R));function ke(e,n){let r={};if(e!==void 0&&!t.n(e))return R(n,`consoleOutput.styles`,`an object of CSS strings`,e,`the styles`),r;let i=Object.entries(e??{});for(let[e,t]of i)Oe.has(e)?t!==void 0&&(typeof t==`string`?r[e]=t:n.report(`config.invalid`,`consoleOutput.styles.${e} must be a string. The library keeps the current style.`)):n.report(`config.invalid`,`The library ignores the unknown consoleOutput.styles key "${e}". Check the spelling.`);return r}function Ae(e,t,n){if(e===void 0)return t;let r=Y(e);return r===void 0?(R(n,`consoleOutput.level`,M,e,`the current console level`),t):r}function je(t,n,r){if(t===void 0)return n;if(t===!1)return{level:null,styles:n.styles};if(t===!0)return{level:e.L,styles:n.styles};if(typeof t==`string`){let e=Y(t);return e===void 0?(R(r,`consoleOutput`,M,t,`the current console level`),n):{level:e,styles:n.styles}}return typeof t!=`object`||!t?(r.report(`config.invalid`,`consoleOutput must be a boolean, a level or an object. The current console settings stay.`),n):{level:Ae(t.level,n.level,r),styles:{...n.styles,...ke(t.styles,r)}}}function Me(e,t,n){let r=e??{};return{defaultRate:q(`sampling.defaultRate`,r.defaultRate,t.defaultRate,n),remoteMaxRate:q(`sampling.remoteMaxRate`,r.remoteMaxRate,t.remoteMaxRate,n),rates:he(r.rates,t.rates,n),alwaysSampleTypes:Z(`sampling.alwaysSampleTypes`,r.alwaysSampleTypes,t.alwaysSampleTypes,fe,be,n),alwaysSampleFrom:X(`sampling.alwaysSampleFrom`,r.alwaysSampleFrom,t.alwaysSampleFrom,n),errorCeiling:U(`sampling.errorCeiling`,r.errorCeiling,g,t.errorCeiling,n),errorCeilingWindowMs:H(`sampling.errorCeilingWindowMs`,r.errorCeilingWindowMs,h,t.errorCeilingWindowMs,n),remote:B(`sampling.remote`,r.remote,t.remote,n)}}function Ne(e,t,n){let r=e??{};return{sourcePolicy:z(`bus.sourcePolicy`,r.sourcePolicy,[`registered`,`trusted-origin`],t.sourcePolicy,n),maxMessageBytes:U(`bus.maxMessageBytes`,r.maxMessageBytes,_,t.maxMessageBytes,n),maxRecordsPerMessage:U(`bus.maxRecordsPerMessage`,r.maxRecordsPerMessage,_,t.maxRecordsPerMessage,n),maxMessagesPerSecond:U(`bus.maxMessagesPerSecond`,r.maxMessagesPerSecond,_,t.maxMessagesPerSecond,n),mode:z(`bus.mode`,r.mode,s,t.mode,n),trustedOrigins:Z(`bus.trustedOrigins`,r.trustedOrigins,t.trustedOrigins,de,Se,n),openFinRole:z(`bus.openFinRole`,r.openFinRole,c,t.openFinRole,n)}}function Pe(e,t,n){let r=e??{};return{scope:z(`journey.scope`,r.scope,l,t.scope,n),maxAgeMs:H(`journey.maxAgeMs`,r.maxAgeMs,re,t.maxAgeMs,n)}}function Fe(e,t,n){let r=e??{};return{maxBatches:H(`retention.maxBatches`,r.maxBatches,p,t.maxBatches,n),maxAgeMs:U(`retention.maxAgeMs`,r.maxAgeMs,ee,t.maxAgeMs,n),maxAttempts:U(`retention.maxAttempts`,r.maxAttempts,te,t.maxAttempts,n)}}function $(e,n,r,i,a){if(n===void 0)return r;if(typeof n==`boolean`)return n;if(!t.n(n))return i.report(`config.invalid`,`capture.${e} must be a boolean or an options object.`),r;let o=a(n,typeof r==`object`?r:{});for(let r of Object.keys(n))t.t(o,r)||i.report(`config.invalid`,`The library ignores the unknown config key "capture.${e}.${r}". Check the spelling.`);return o}function Ie(t,n,r){let i=t??{},a={...n,urlTransform:W(`capture.urlTransform`,i.urlTransform,n.urlTransform,r),remoteToggles:Z(`capture.remoteToggles`,i.remoteToggles,n.remoteToggles,`a list of capture switch names without privacy controls`,t=>e.sn.find(e=>e===t),r),resourceTiming:$(`resourceTiming`,i.resourceTiming,n.resourceTiming,r,(e,t)=>({slowMs:V(`capture.resourceTiming.slowMs`,e.slowMs,t.slowMs??1e3,r)})),interactions:$(`interactions`,i.interactions,n.interactions,r,(e,t)=>Le(e,t,r)),console:$(`console`,i.console,n.console,r,(e,t)=>({levels:Z(`capture.console.levels`,e.levels,t.levels??[`error`,`warn`],le,xe,r)})),longFrames:$(`longFrames`,i.longFrames,n.longFrames,r,(e,t)=>({thresholdMs:V(`capture.longFrames.thresholdMs`,e.thresholdMs,t.thresholdMs??100,r)})),userTiming:$(`userTiming`,i.userTiming,n.userTiming,r,(e,t)=>({include:Z(`capture.userTiming.include`,e.include,t.include??[],N,Q,r)})),webVitals:$(`webVitals`,i.webVitals,n.webVitals,r,(e,t)=>({loader:W(`capture.webVitals.loader`,e.loader,t.loader,r)})),ignoreUrls:Z(`capture.ignoreUrls`,i.ignoreUrls,n.ignoreUrls,N,Q,r),propagateTraceHeaderTo:Z(`capture.propagateTraceHeaderTo`,i.propagateTraceHeaderTo,n.propagateTraceHeaderTo,ue,Ce,r),plugins:Z(`capture.plugins`,i.plugins,n.plugins,`a list of objects with a name, install() and uninstall()`,_e,r)};for(let e of se)a[e]=B(`capture.${e}`,i[e],n[e],r);return a}function Le(e,t,n){let r=e.ignoreSelector,i=r===void 0?t.ignoreSelector:r;if(i!=null)try{if(typeof i!=`string`)throw Error(`Invalid selector`);typeof document<`u`&&document.createElement(`div`).matches(i)}catch{n.report(`config.invalid`,`capture.interactions.ignoreSelector must be a valid CSS selector or null.`),i=t.ignoreSelector}let a=t.actionAttribute??`data-observability-action`;return e.actionAttribute!==void 0&&(typeof e.actionAttribute==`string`&&/^[a-z][\w-]*$/i.test(e.actionAttribute)?a=e.actionAttribute:R(n,`capture.interactions.actionAttribute`,`an attribute name of letters, digits, hyphens and underscores`,e.actionAttribute,`"${a}"`)),{actionAttribute:a,text:B(`capture.interactions.text`,e.text,t.text??!1,n),selector:B(`capture.interactions.selector`,e.selector,t.selector??!1,n),ignoreSelector:typeof i==`string`||i===null?i:void 0,maxTextChars:H(`capture.interactions.maxTextChars`,e.maxTextChars,[0,2**53-1],t.maxTextChars??50,n),rageClicks:B(`capture.interactions.rageClicks`,e.rageClicks,t.rageClicks??!1,n),rageClickCount:H(`capture.interactions.rageClickCount`,e.rageClickCount,[2,20],t.rageClickCount??3,n),rageClickWindowMs:H(`capture.interactions.rageClickWindowMs`,e.rageClickWindowMs,v,t.rageClickWindowMs??1e3,n),deadClicks:B(`capture.interactions.deadClicks`,e.deadClicks,t.deadClicks??!1,n),deadClickMs:H(`capture.interactions.deadClickMs`,e.deadClickMs,v,t.deadClickMs??1e3,n)}}var Re={metricsEndpoint:`The library sends metric records as log records.`,tracesEndpoint:`The library sends no span.`};function ze(t,n,r,i,a){let o=k(t,n,r,a);return o!==null&&i!==`otlp`?(a.report(`config.invalid`,`${t} needs serializer "${e.Fn}". ${Re[t]}`),null):o}function Be(e,t,n,r,i){let a={...n};for(let o of Object.keys(n)){let s=t?.[o],c=n[o],l=r.ranges[o],u=r.limits[o],d=r.choices?.[o],f=r.custom?.[o],p=c;f?p=f(`${e}.${o}`,s,c,i):u?p=U(`${e}.${o}`,s,u,c,i):typeof c==`number`&&l?p=H(`${e}.${o}`,s,l,c,i):typeof c==`boolean`?p=B(`${e}.${o}`,s,c,i):d?p=z(`${e}.${o}`,s,d,String(c),i):s===void 0||typeof s==`string`?p=s??c:R(i,`${e}.${o}`,`a string`,s,String(c)),Object.assign(a,{[o]:p})}return a}function Ve(n,r){let i=n;for(let a of e.I){let e=n[a];e!==void 0&&!t.n(e)&&(R(r,a,`an object`,e,`the current values`),i={...i,[a]:void 0})}return i}function He(e,t,n){let{capture:r,sampling:i}=t,a=(e,t)=>{n.report(`config.invalid`,`${e} has no effect ${t}. The value stays.`)};(e.transport!==void 0||e.transportWorker!==void 0)&&t.transport&&t.transportWorker&&a(`transportWorker`,`with transport`),(e.transport!==void 0||e.transportOnExit!==void 0)&&t.transportOnExit&&!t.transport&&a(`transportOnExit`,`without transport`),(e.capture?.remoteToggles!==void 0||e.sampling?.remote!==void 0)&&r.remoteToggles.length>0&&!i.remote&&a(`capture.remoteToggles`,`without sampling.remote`);let o=r.fetch||r.xhr||r.remoteToggles.includes(`fetch`)||r.remoteToggles.includes(`xhr`);(e.capture?.propagateTraceHeaderTo!==void 0||e.capture?.fetch!==void 0||e.capture?.xhr!==void 0)&&r.propagateTraceHeaderTo.length>0&&!o&&a(`capture.propagateTraceHeaderTo`,`without capture.fetch or capture.xhr`)}function Ue(t,n,a){let s=a??e.W,c=Ve(t,n),l=Object.fromEntries(Object.keys(j).map(e=>[e,Be(e,c[e],s[e],j[e],n)])),u={...s,...l,lockConfiguration:B(`lockConfiguration`,c.lockConfiguration,s.lockConfiguration,n),loggerCache:{maxEntries:U(`loggerCache.maxEntries`,c.loggerCache?.maxEntries,g,s.loggerCache.maxEntries,n)},securityContext:{id:K(`securityContext.id`,c.securityContext?.id,s.securityContext.id,n)||s.securityContext.id,isolation:B(`securityContext.isolation`,c.securityContext?.isolation,s.securityContext.isolation,n)},endpoint:A(c.endpoint,s.endpoint,n),serviceName:K(`serviceName`,c.serviceName,s.serviceName,n),serviceVersion:K(`serviceVersion`,c.serviceVersion,s.serviceVersion,n),environment:K(`environment`,c.environment,s.environment,n),enabled:B(`enabled`,c.enabled,s.enabled,n),payloadMode:z(`payloadMode`,c.payloadMode,[`copy`,`defer`],s.payloadMode,n),minLevel:X(`minLevel`,c.minLevel,s.minLevel,n),minLevels:ge(c.minLevels,s.minLevels,n),processors:me(c.processors,s.processors,n),compression:z(`compression`,c.compression,r,s.compression,n),credentials:z(`credentials`,c.credentials,i,s.credentials,n),headers:Te(c.headers,s.headers,n),identity:z(`identity`,c.identity,o,s.identity,n),serializer:De(c.serializer,a?.serializer,n),consoleOutput:je(c.consoleOutput,s.consoleOutput,n),sampling:Me(c.sampling,s.sampling,n),bus:Ne(c.bus,s.bus,n),batching:J(`batching`,c.batching,s.batching,f,n),retention:Fe(c.retention,s.retention,n),limits:J(`limits`,c.limits,s.limits,ne,n),journey:Pe(c.journey,s.journey,n),capture:Ie(c.capture,s.capture,n),transport:W(`transport`,c.transport,s.transport,n),transportOnExit:W(`transportOnExit`,c.transportOnExit,s.transportOnExit,n),transportWorker:W(`transportWorker`,c.transportWorker,s.transportWorker,n),otelLoader:W(`otelLoader`,c.otelLoader,s.otelLoader,n),contextProvider:W(`contextProvider`,c.contextProvider,s.contextProvider,n),redact:pe(c.redact,s.redact,n),onDiagnostic:W(`onDiagnostic`,c.onDiagnostic,s.onDiagnostic,n),onDrop:W(`onDrop`,c.onDrop,s.onDrop,n)};for(let e of[`metricsEndpoint`,`tracesEndpoint`])u[e]=ze(e,c[e],s[e],u.serializer,n);u.endpoint===``&&u.transport===void 0&&n.report(`config.invalid`,`endpoint is missing. The library drops each record. Set endpoint: null for console-only mode.`);for(let e of[`metricsEndpoint`,`tracesEndpoint`])u[e]!==null&&u.endpoint===null&&!u.transport&&n.report(`config.invalid`,`${e} needs endpoint or transport. The library sends nothing to ${e}.`);u.serviceName||=(n.report(`config.invalid`,`serviceName is missing. Every record reports service.name as '${e.dr}'.`),e.dr),u.capture.ignoreUrls=u.capture.ignoreUrls.filter(e=>e!==a?.endpoint&&e!==a?.metricsEndpoint&&e!==a?.tracesEndpoint&&e!==a?.replay.endpoint);for(let e of[u.endpoint,u.metricsEndpoint,u.tracesEndpoint,u.replay.endpoint])e&&!u.capture.ignoreUrls.includes(e)&&(u.capture.ignoreUrls=[...u.capture.ignoreUrls,e]);return u.delivery.retryMaxDelayMs<u.delivery.retryBaseDelayMs&&(n.report(`config.invalid`,`delivery.retryMaxDelayMs must be at least retryBaseDelayMs.`),u.delivery.retryBaseDelayMs=s.delivery.retryBaseDelayMs,u.delivery.retryMaxDelayMs=s.delivery.retryMaxDelayMs),He(c,u,n),We(t,n),u}function We(t,n){let r=new Set([...Object.keys(e.W),...e.lr]);for(let e of Object.keys(t))r.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${e}". Check the spelling.`);for(let r of e.I){let i=t[r];if(typeof i!=`object`||!i)continue;let a=new Set([...Object.keys(e.W[r]),...e.ur[r]]);for(let e of Object.keys(i))a.has(e)||n.report(`config.invalid`,`The library ignores the unknown config key "${r}.${e}". Check the spelling.`)}}function Ge(t,n){for(let r of Object.keys(n))e.I.includes(r)||Object.assign(t,{[r]:n[r]});for(let r of e.I)Object.assign(t[r],n[r])}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Ge}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return G}});
2
- //# sourceMappingURL=config-DUs7uHHt.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-DUs7uHHt.cjs","names":["LEVEL_ORDER","BEACON_LIMIT_BYTES","PROFILER_PROBE_LIMIT","isObject","SERIALIZER_NAME_OTLP","CONSOLE_DEFAULT_STYLES","CONSOLE_DEFAULT_LEVEL","hasOwn","REMOTE_CAPTURE_FLAGS","CONFIG_SECTIONS","DEFAULT_CONFIG","UNKNOWN_SERVICE_NAME","UNDEFAULTED_CONFIG_KEYS","UNDEFAULTED_SECTION_KEYS","require_constants","require_guards","LEVEL_NAMES","COMPRESSION_VALUES","CREDENTIALS_VALUES","STORAGE_VALUES","IDENTITY_VALUES","BUS_MODE_VALUES","OPENFIN_ROLE_VALUES","JOURNEY_SCOPE_VALUES","CONSOLE_METHOD_VALUES","LOG_TYPE_VALUES","BATCHING_RANGES","MAX_BATCHES_RANGE","RETENTION_AGE_RANGE","RETENTION_ATTEMPTS_RANGE","LIMIT_RANGES","JOURNEY_AGE_RANGE","DURATION_RANGE","POSITIVE_DURATION_RANGE","COUNT_RANGE","POSITIVE_RANGE","CLICK_WAIT_RANGE","isStrings","value","entry","isFunctions","isFunctionOrNull","isNull","SCHEME_PATTERN","isRate","HOOK_EXPECTED","URL_EXPECTED","isHeaders","isRecord","keepKind","describeValue","fallback","test","reportInvalid","diagnostics","key","expected","describe","pageBase","absoluteUrl","url","error","resolveDestination","describeKind","resolveEndpoint","POLICY_RULES","resolveDiagnosticRecords","CAPTURE_FLAG_KEYS","SANDBOX_ORIGIN","LEVEL_EXPECTED","listOf","CONSOLE_LEVELS_EXPECTED","PATTERN_LIST_EXPECTED","TARGET_LIST_EXPECTED","ORIGIN_LIST_EXPECTED","LOG_TYPE_LIST_EXPECTED","DIAGNOSTIC_RECORDS_EXPECTED","quoted","values","kept","resolveChoice","match","accepted","resolveBoolean","resolveNonNegative","resolveInteger","min","max","range","resolveLimit","resolveHook","REFUSE_RECORDS","resolveRedact","resolveProcessors","resolveString","resolveRate","resolveRates","rates","ns","rate","resolveRanges","given","input","keys","ranges","section","base","toLevel","upper","level","resolveLevel","resolveMinLevels","levels","prefix","raw","resolveList","entries","accept","toPlugin","toStringEntry","toLogType","type","toPattern","toConsoleMethod","method","toOrigin","origin","toTarget","isStringRecord","resolveHeaders","isSerializer","resolveSerializer","requested","previous","CONSOLE_STYLE_KEYS","validStyles","valid","styles","resolveConsoleLevel","resolveConsole","resolveSampling","resolveBus","resolveJourney","resolveRetention","resolveCaptureOptions","resolved","fields","name","resolveCapture","capture","resolveInteractions","ignore","ignoreSelector","actionAttribute","SIGNAL_OFF","resolveSignalEndpoint","serializer","resolvePolicy","next","rules","limit","choice","custom","checkSections","checked","reportIneffective","config","noEffect","condition","sampling","requests","resolveConfig","policies","merged","reportUnknownKeys","known","sectionKeys","applyResolvedConfig","target"],"sources":["../src/core/config.ts"],"sourcesContent":["// src/core/config.ts\n//\n// Resolves partial consumer options into a validated config, and updates the live config.\n// Three rules to follow here, because breaking any 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// 3. An omitted key or undefined keeps the current value at every depth. Only null clears a\n// hook or lifts a limit, so an unset variable can't remove redact.\n// A getter in the app's input can throw here. ObservabilityRuntime.configure() catches it, so\n// configure() never throws into the app.\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 HOLD_BUFFER_HEAD_RECORDS,\n LEVEL_ORDER,\n LONG_FRAME_THRESHOLD_MS,\n PROFILER_PROBE_LIMIT,\n REMOTE_CAPTURE_FLAGS,\n RESOURCE_SLOW_MS,\n RAGE_CLICK_COUNT,\n RAGE_CLICK_WINDOW_MS,\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 ConsoleStyles,\n InteractionOptions,\n JourneyOptions,\n LimitsOptions,\n ObservabilityConfig,\n ResolvedConfig,\n ResolvedConsole,\n RetentionOptions,\n SamplingOptions,\n SerializerChoice,\n} from \"../models/config\";\nimport type { LogLevel, LogType } from \"../models/log-record\";\nimport type { CapturePlugin } from \"../models/plugin\";\nimport type { LogSerializer } from \"../models/serializer\";\nimport { hasOwn, isObject } from \"../utils/guards\";\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 LOG_TYPE_VALUES: readonly LogType[] = [\"action\", \"event\", \"metric\", \"log\", \"system\", \"span\"];\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 metricBatchSize: [1, 1000],\n};\n\n/** Accepted range for retention.maxBatches. */\nconst MAX_BATCHES_RANGE: Range = [1, 5000];\n\n/** Accepted range for retention.maxAgeMs. null lifts the age limit. */\nconst RETENTION_AGE_RANGE: Range = [60_000, 7 * 24 * 60 * 60 * 1000];\n\n/** Accepted range for retention.maxAttempts. null lifts the attempt limit. */\nconst RETENTION_ATTEMPTS_RANGE: Range = [1, 20];\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 LimitsOptions, 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 duration that must be at least 1 ms, because 0 would expire at once. */\nconst POSITIVE_DURATION_RANGE: Range = [1, DURATION_RANGE[1]];\n\n/** Range for a count. Zero allows nothing. */\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 keys of a policy section that take a number, or null for no limit. */\ntype LimitKeys<T> = {\n [K in keyof T]: T[K] extends number | null ? (null extends T[K] ? K : never) : never;\n}[keyof T];\n\n/** The policy sections resolvePolicy() checks. */\ntype PolicySection =\n | \"captureLimits\"\n | \"metadata\"\n | \"storage\"\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 null. */\nconst isNull = (value: unknown): boolean => value === null;\n\n/** Matches a URL that names its scheme, for example \"https:\". A relative URL has none. */\nconst SCHEME_PATTERN = /^[a-z][a-z\\d+.-]*:/i;\n\n/** True for a sampling rate from 0 to 1. NaN fails both comparisons, so it's rejected too. */\nconst isRate = (value: unknown): value is number =>\n typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n\n/** How a hook value and a URL value read in a config.invalid message. */\nconst HOOK_EXPECTED = \"a function or null\";\nconst URL_EXPECTED = \"a URL string or null\";\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 * @param describe Describes a rejected value. A key whose text can hold a secret passes\n * describeKind.\n * @returns The resolver. A value that fails the test is ignored, and the current one stays.\n */\nfunction keepKind(\n test: (value: unknown) => boolean,\n expected: string,\n describe: (value: unknown) => string = describeValue,\n): 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\", describe);\n return fallback;\n };\n}\n\n/**\n * Returns the URL that a relative destination resolves against. A worker has no document, so\n * it uses its own location.\n * @returns The base URL, or undefined when the scope has neither.\n */\nfunction pageBase(): string | undefined {\n if (typeof document !== \"undefined\") {\n return document.baseURI;\n }\n\n return typeof location === \"undefined\" ? undefined : location.href;\n}\n\n/**\n * Checks a destination URL and returns the form the library sends to. A relative URL resolves\n * against the page, so the records go where the app's own requests go, and the report names\n * that origin. A URL with a user name or a password is refused, because each request would\n * carry it.\n * @param key Config key.\n * @param value The URL the consumer passed.\n * @param fallback The current destination.\n * @param diagnostics Diagnostics reporter.\n * @returns The URL, its absolute form for a relative URL, or the fallback for a refused URL.\n */\nfunction absoluteUrl(\n key: string,\n value: string,\n fallback: unknown,\n diagnostics: Diagnostics,\n): unknown {\n let url: URL;\n try {\n url = new URL(value, pageBase());\n } catch (error) {\n // The URL can hold a token, and this message can become a record.\n diagnostics.report(\n \"config.invalid\",\n `${key} is not a valid URL. The library keeps the current value.`,\n undefined,\n error,\n );\n return fallback;\n }\n\n if (url.username !== \"\" || url.password !== \"\") {\n diagnostics.report(\n \"config.invalid\",\n `${key} has a user name or a password. The library keeps the current value.`,\n );\n return fallback;\n }\n\n if (SCHEME_PATTERN.test(value)) {\n return value;\n }\n\n diagnostics.report(\"config.invalid\", `${key} is relative. The library sends to ${url.origin}.`);\n return url.href;\n}\n\n/**\n * Reads a destination that null turns off. An empty or blank string turns it off too, with a\n * report, because an empty environment variable must not leave the records going to the old\n * destination. A rotation runs it too, to find a refused URL.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current destination.\n * @param diagnostics Diagnostics reporter.\n * @returns The URL, null when it's off, or the fallback for a refused value.\n */\nexport function resolveDestination(\n key: string,\n value: unknown,\n fallback: unknown,\n diagnostics: Diagnostics,\n): unknown {\n if (typeof value !== \"string\") {\n return keepKind(isNull, URL_EXPECTED, describeKind)(key, value, fallback, diagnostics);\n }\n\n if (value.trim() === \"\") {\n diagnostics.report(\n \"config.invalid\",\n `${key} is empty. The library turns it off. Use null to turn it off.`,\n );\n return null;\n }\n\n // The current value passed the check already, so it gets no second report.\n return value === fallback ? value : absoluteUrl(key, value, fallback, diagnostics);\n}\n\n/**\n * Reads the endpoint. \"\" stays \"\", the value for \"not set\", so resolveConfig reports a missing\n * endpoint. A blank string is refused, because it would send to the page itself. A rotation\n * runs it too, to find a refused URL.\n * @param value The value the consumer passed.\n * @param fallback The current endpoint.\n * @param diagnostics Diagnostics reporter.\n * @returns The endpoint, null for console-only mode, or the fallback for a refused value.\n */\nexport function resolveEndpoint(\n value: unknown,\n fallback: unknown,\n diagnostics: Diagnostics,\n): unknown {\n if (typeof value !== \"string\") {\n return keepKind(isNull, URL_EXPECTED, describeKind)(\"endpoint\", value, fallback, diagnostics);\n }\n\n if (value === \"\" || value === fallback) {\n return value;\n }\n\n if (value.trim() === \"\") {\n diagnostics.report(\"config.invalid\", \"endpoint is blank. The library keeps the current value.\");\n return fallback;\n }\n\n return absoluteUrl(\"endpoint\", value, fallback, diagnostics);\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 range for each key that also takes null, which means no limit. */\n limits: Record<LimitKeys<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 captureLimits: {\n ranges: {\n // A larger capacity fails as an invalid array allocation.\n breadcrumbs: [0, 1_000_000],\n errorDedupeMs: DURATION_RANGE,\n // A window of 0 ms starts a new window for every event, so no rate limit would apply.\n windowMs: POSITIVE_DURATION_RANGE,\n },\n limits: {\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 },\n },\n metadata: { ranges: {}, limits: {} },\n storage: { ranges: {}, limits: {}, choices: { backend: STORAGE_VALUES } },\n diagnostics: {\n ranges: { throttleMs: DURATION_RANGE },\n limits: {},\n custom: { records: resolveDiagnosticRecords },\n },\n correlation: {\n ranges: {},\n // 0 would end a session or a trace at once, so these start at 1, and null lifts them.\n limits: { sessionIdleMs: POSITIVE_DURATION_RANGE, traceMaxAgeMs: POSITIVE_DURATION_RANGE },\n },\n metrics: {\n ranges: { intervalMs: [1000, 600_000] },\n limits: {\n maxSeries: COUNT_RANGE,\n maxInstruments: COUNT_RANGE,\n maxHistogramBoundaries: COUNT_RANGE,\n },\n },\n buffering: {\n ranges: {\n // Two heads at least, or a full buffer keeps its first records but too few of the newest.\n // The maximum bounds the memory of a startup storm.\n maxHeldRecords: [2 * HOLD_BUFFER_HEAD_RECORDS, 10_000],\n },\n // A buffer that holds nothing would drop every record, so these start at 1.\n limits: { maxPendingRecords: POSITIVE_RANGE, maxPendingBytes: POSITIVE_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 },\n limits: {},\n choices: { priority: [\"low\", \"auto\", \"high\"] },\n },\n debugBuffer: {\n ranges: { maxRecords: [1, 10_000] },\n limits: { maxAgeMs: POSITIVE_DURATION_RANGE },\n },\n profiler: {\n ranges: { maxProbes: [1, PROFILER_PROBE_LIMIT] },\n limits: {},\n },\n replay: {\n ranges: {\n bufferMs: [5000, 600_000],\n maxBufferBytes: [100_000, 200_000_000],\n afterErrorMs: [0, 600_000],\n // A window of 0 ms starts a new window for every upload, so the limit would never apply.\n uploadWindowMs: POSITIVE_DURATION_RANGE,\n maxSegmentEvents: [1, 10_000],\n maxSegmentBytes: [10_000, 10_000_000],\n flushIntervalMs: [100, 60_000],\n maxQueueBytes: [100_000, 200_000_000],\n maxAttempts: [1, 10],\n },\n limits: { uploadsPerWindow: COUNT_RANGE },\n choices: { mode: [\"onError\"] },\n custom: {\n endpoint: resolveDestination,\n maskSelectors: keepKind(isStrings, \"a list of strings\"),\n blockSelectors: keepKind(isStrings, \"a list of strings\"),\n loader: keepKind(isFunctionOrNull, HOOK_EXPECTED, describeKind),\n onSegment: keepKind(isFunctionOrNull, HOOK_EXPECTED, describeKind),\n // A string can be a token, so the report gives only the type.\n headers: keepKind(isHeaders, \"an object of strings, a function or null\", describeKind),\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 \"fullUrls\",\n \"webSocket\",\n \"uncleanExit\",\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_LEVELS_EXPECTED = `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 LOG_TYPE_LIST_EXPECTED = `a list of log types: ${listOf(LOG_TYPE_VALUES)}`;\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, after null has removed it. */\ntype HeadersOption = NonNullable<ObservabilityConfig[\"headers\"]> | undefined;\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 * Describes only the type of a value. A hook or a URL key can hold a token as a string, and\n * a diagnostic can become a record, so its text must not appear.\n * @param value The value the consumer passed.\n * @returns The type, for example \"a string\".\n */\nfunction describeKind(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n\n if (Array.isArray(value)) {\n return \"a list\";\n }\n\n return typeof value === \"object\" ? \"an object\" : `a ${typeof 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 * @param describe Describes the value. A key whose text can hold a secret passes describeKind.\n */\nfunction reportInvalid(\n diagnostics: Diagnostics,\n key: string,\n expected: string,\n value: unknown,\n kept: string,\n describe: (value: unknown) => string = describeValue,\n): void {\n diagnostics.report(\n \"config.invalid\",\n `${key} must be ${expected}. The value is ${describe(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 // The value isn't printed, because a string can be a token put into the wrong key.\n diagnostics.report(\n \"config.invalid\",\n `${key} must be ${listOf(accepted)}. The library keeps \"${fallback}\".`,\n );\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 * Reads a limit that takes an integer in a range, or null for no limit.\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 limit. Null means no limit.\n * @param diagnostics Diagnostics reporter.\n * @returns The limit, or the fallback when the value isn't accepted.\n */\nfunction resolveLimit(\n key: string,\n value: unknown,\n range: Range,\n fallback: number | null,\n diagnostics: Diagnostics,\n): number | null {\n if (value === undefined) {\n return fallback;\n }\n\n if (value === null) {\n return null;\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)}, or null for no limit`;\n reportInvalid(diagnostics, key, expected, value, String(fallback));\n return fallback;\n}\n\n/**\n * Reads a hook. Undefined keeps the current hook and null removes it.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current hook.\n * @param diagnostics Diagnostics reporter.\n * @returns The hook, or undefined when there is none.\n */\nfunction resolveHook<T>(\n key: string,\n value: unknown,\n fallback: T | undefined,\n diagnostics: Diagnostics,\n): T | undefined {\n if (value === undefined) {\n return fallback;\n }\n\n if (value === null) {\n return undefined;\n }\n\n if (typeof value === \"function\") {\n return value as T;\n }\n\n reportInvalid(diagnostics, key, HOOK_EXPECTED, value, \"the current value\", describeKind);\n return fallback;\n}\n\n/**\n * Stands in for a redact value that isn't a function when no redact hook was set before. The\n * record builder drops each record while it's the hook, so a record the app meant to redact\n * never leaves the page.\n * @returns null, which drops the record.\n */\nexport const REFUSE_RECORDS = (): null => null;\n\n/**\n * Reads the redact hook. A value that isn't a function keeps the current hook, or fails closed\n * when there is none. Otherwise a typo such as `{ default: fn }` would send raw records.\n * @param value The value the consumer passed.\n * @param fallback The current hook.\n * @param diagnostics Diagnostics reporter.\n * @returns The hook, REFUSE_RECORDS, or undefined when there is none.\n */\nfunction resolveRedact(\n value: unknown,\n fallback: ResolvedConfig[\"redact\"],\n diagnostics: Diagnostics,\n): ResolvedConfig[\"redact\"] {\n if (value === undefined || value === null || typeof value === \"function\" || fallback) {\n return resolveHook(\"redact\", value, fallback, diagnostics);\n }\n\n diagnostics.report(\n \"config.invalid\",\n `redact must be ${HOOK_EXPECTED}. The value is ${describeKind(value)}. The library drops each record until redact is a function or null.`,\n );\n return REFUSE_RECORDS;\n}\n\n/**\n * Reads the processors. A list with one entry that isn't a function is refused as a whole,\n * because running the other processors without it could let a record through unmasked. With\n * no current list, the library drops each record instead.\n * @param value The value the consumer passed.\n * @param fallback The current processors.\n * @param diagnostics Diagnostics reporter.\n * @returns A copy of the new list, the current list, or a list that drops each record.\n */\nfunction resolveProcessors(\n value: unknown,\n fallback: ResolvedConfig[\"processors\"],\n diagnostics: Diagnostics,\n): ResolvedConfig[\"processors\"] {\n if (value === undefined) {\n return fallback;\n }\n\n if (isFunctions(value)) {\n return [...(value as ResolvedConfig[\"processors\"])];\n }\n\n if (fallback.length > 0) {\n reportInvalid(\n diagnostics,\n \"processors\",\n \"a list of functions\",\n value,\n \"the current list\",\n describeKind,\n );\n return fallback;\n }\n\n // No list to keep, and the app meant to process each record, so fail closed.\n diagnostics.report(\n \"config.invalid\",\n `processors must be a list of functions. The value is ${describeKind(value)}. The library drops each record until processors is a list of functions or [].`,\n );\n return [REFUSE_RECORDS];\n}\n\n/**\n * Reads a string 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 string.\n */\nfunction resolveString(\n key: string,\n value: unknown,\n fallback: string,\n diagnostics: Diagnostics,\n): string {\n if (value === undefined) {\n return fallback;\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n reportInvalid(diagnostics, key, \"a string\", value, \"the current value\");\n return fallback;\n}\n\n/**\n * Reads a sampling rate from 0 to 1.\n * @param key Config key.\n * @param value The value the consumer passed.\n * @param fallback The current rate.\n * @param diagnostics Diagnostics reporter.\n * @returns The rate, or the fallback when the value isn't accepted.\n */\nfunction resolveRate(\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 (isRate(value)) {\n return value;\n }\n\n diagnostics.report(\n \"config.invalid\",\n `${key} must be 0..1. The value is ${describeValue(value)}. The library keeps ${String(fallback)}.`,\n );\n return fallback;\n}\n\n/**\n * Reads sampling.rates. A new map replaces the current one, as minLevels does, so a later call\n * can remove a namespace.\n * @param value The value the consumer passed.\n * @param fallback The current rates.\n * @param diagnostics Diagnostics reporter.\n * @returns The rate for each namespace prefix.\n */\nfunction resolveRates(\n value: unknown,\n fallback: Record<string, number>,\n diagnostics: Diagnostics,\n): Record<string, number> {\n if (value === undefined) {\n return fallback;\n }\n\n if (!isObject(value)) {\n reportInvalid(diagnostics, \"sampling.rates\", \"an object of rates\", value, \"the current value\");\n return fallback;\n }\n\n // A bad entry is left out, so the namespace falls back to a shorter prefix or defaultRate.\n // An undefined entry is the same as no entry.\n const rates: [string, number][] = [];\n for (const [ns, rate] of Object.entries(value)) {\n if (isRate(rate)) {\n rates.push([ns, rate]);\n } else if (rate !== undefined) {\n diagnostics.report(\n \"config.invalid\",\n `sampling.rates[\"${ns}\"] must be 0..1. The value is ${describeValue(rate)}. The library ignores this entry.`,\n );\n }\n }\n\n // fromEntries creates own properties, and it copies, so the app's object never changes.\n return Object.fromEntries(rates);\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 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 log type entry. An unknown type would never match a record, so it's rejected.\n * @param entry List entry.\n * @returns The log type, or undefined.\n */\nfunction toLogType(entry: unknown): LogType | undefined {\n return LOG_TYPE_VALUES.find((type) => type === entry);\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 after null, or the fallback for undefined or a bad value.\n */\nfunction resolveHeaders(\n value: unknown,\n fallback: HeadersOption,\n diagnostics: Diagnostics,\n): HeadersOption {\n if (value === undefined) {\n return fallback;\n }\n\n // null clears the headers. undefined keeps them, so an unset variable can't drop a token the\n // app still needs. With isolation on, configure() refuses the change and a logout rotates.\n if (value === null) {\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 keeps the current serializer.`,\n );\n return previous ?? 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: unknown, diagnostics: Diagnostics): ConsoleStyles {\n const valid: Record<string, string> = {};\n if (styles !== undefined && !isObject(styles)) {\n reportInvalid(\n diagnostics,\n \"consoleOutput.styles\",\n \"an object of CSS strings\",\n styles,\n \"the styles\",\n );\n return valid;\n }\n\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 consoleOutput.styles key \"${key}\". Check the spelling.`,\n );\n continue;\n }\n\n // undefined keeps the current style, as it does for every other key.\n if (value === undefined) {\n continue;\n }\n\n if (typeof value !== \"string\") {\n diagnostics.report(\n \"config.invalid\",\n `consoleOutput.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 consoleOutput 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 omitted or unknown level keeps the current one, also when it's off.\n */\nfunction resolveConsoleLevel(\n requested: unknown,\n previous: LogLevel | null,\n diagnostics: Diagnostics,\n): LogLevel | null {\n // An omitted level keeps the current one, so setting only the styles can't turn a console on.\n if (requested === undefined) {\n return previous;\n }\n\n const level = toLevel(requested);\n if (level !== undefined) {\n return level;\n }\n\n reportInvalid(\n diagnostics,\n \"consoleOutput.level\",\n LEVEL_EXPECTED,\n requested,\n \"the current console level\",\n );\n return previous;\n}\n\n/**\n * Normalizes the consoleOutput option into a level and a set of styles.\n * @param requested Consumer consoleOutput 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: ObservabilityConfig[\"consoleOutput\"],\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 \"consoleOutput\",\n LEVEL_EXPECTED,\n requested,\n \"the current console level\",\n );\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 \"consoleOutput 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.\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 defaultRate: resolveRate(\n \"sampling.defaultRate\",\n given.defaultRate,\n base.defaultRate,\n diagnostics,\n ),\n remoteMaxRate: resolveRate(\n \"sampling.remoteMaxRate\",\n given.remoteMaxRate,\n base.remoteMaxRate,\n diagnostics,\n ),\n rates: resolveRates(given.rates, base.rates, diagnostics),\n alwaysSampleTypes: resolveList(\n \"sampling.alwaysSampleTypes\",\n given.alwaysSampleTypes,\n base.alwaysSampleTypes,\n LOG_TYPE_LIST_EXPECTED,\n toLogType,\n diagnostics,\n ),\n alwaysSampleFrom: resolveLevel(\n \"sampling.alwaysSampleFrom\",\n given.alwaysSampleFrom,\n base.alwaysSampleFrom,\n diagnostics,\n ),\n errorCeiling: resolveLimit(\n \"sampling.errorCeiling\",\n given.errorCeiling,\n COUNT_RANGE,\n base.errorCeiling,\n diagnostics,\n ),\n // A window of 0 ms starts a new window for every record, so the ceiling would never apply.\n errorCeilingWindowMs: resolveInteger(\n \"sampling.errorCeilingWindowMs\",\n given.errorCeilingWindowMs,\n POSITIVE_DURATION_RANGE,\n base.errorCeilingWindowMs,\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 // A limit of 0 would stop every message, so each limit starts at 1 and null lifts it.\n return {\n sourcePolicy: resolveChoice(\n \"bus.sourcePolicy\",\n given.sourcePolicy,\n [\"registered\", \"trusted-origin\"],\n base.sourcePolicy,\n diagnostics,\n ),\n maxMessageBytes: resolveLimit(\n \"bus.maxMessageBytes\",\n given.maxMessageBytes,\n POSITIVE_RANGE,\n base.maxMessageBytes,\n diagnostics,\n ),\n maxRecordsPerMessage: resolveLimit(\n \"bus.maxRecordsPerMessage\",\n given.maxRecordsPerMessage,\n POSITIVE_RANGE,\n base.maxRecordsPerMessage,\n diagnostics,\n ),\n maxMessagesPerSecond: resolveLimit(\n \"bus.maxMessagesPerSecond\",\n given.maxMessagesPerSecond,\n POSITIVE_RANGE,\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 maxBatches: resolveInteger(\n \"retention.maxBatches\",\n given.maxBatches,\n MAX_BATCHES_RANGE,\n base.maxBatches,\n diagnostics,\n ),\n maxAgeMs: resolveLimit(\n \"retention.maxAgeMs\",\n given.maxAgeMs,\n RETENTION_AGE_RANGE,\n base.maxAgeMs,\n diagnostics,\n ),\n maxAttempts: resolveLimit(\n \"retention.maxAttempts\",\n given.maxAttempts,\n RETENTION_ATTEMPTS_RANGE,\n base.maxAttempts,\n diagnostics,\n ),\n };\n}\n\n/**\n * Reads a capture key that takes a boolean or an options object, where true means the defaults.\n * @param key Capture key, for example `longFrames`.\n * @param value The value the consumer passed.\n * @param base The current value.\n * @param diagnostics Diagnostics reporter.\n * @param fields Checks each field of an object. It gets the current object, or {} after a\n * boolean, so an omitted field keeps its current value.\n * @returns The boolean, the checked object, or the current value for a bad value.\n */\nfunction resolveCaptureOptions<T extends object>(\n key: string,\n value: unknown,\n base: boolean | T,\n diagnostics: Diagnostics,\n fields: (given: Record<string, unknown>, previous: Partial<T>) => T,\n): boolean | T {\n if (value === undefined) {\n return base;\n }\n\n if (typeof value === \"boolean\") {\n return value;\n }\n\n if (!isObject(value)) {\n diagnostics.report(\"config.invalid\", `capture.${key} must be a boolean or an options object.`);\n return base;\n }\n\n const resolved = fields(value, typeof base === \"object\" ? base : {});\n\n // The resolved object has each known option, so a typo such as `threshold` isn't silent.\n for (const name of Object.keys(value)) {\n if (!hasOwn(resolved, name)) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the unknown config key \"capture.${key}.${name}\". Check the spelling.`,\n );\n }\n }\n\n return resolved;\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 urlTransform: resolveHook(\n \"capture.urlTransform\",\n given.urlTransform,\n base.urlTransform,\n diagnostics,\n ),\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: resolveCaptureOptions(\n \"resourceTiming\",\n given.resourceTiming,\n base.resourceTiming,\n diagnostics,\n (value, previous) => ({\n slowMs: resolveNonNegative(\n \"capture.resourceTiming.slowMs\",\n value.slowMs,\n previous.slowMs ?? RESOURCE_SLOW_MS,\n diagnostics,\n ),\n }),\n ),\n interactions: resolveCaptureOptions(\n \"interactions\",\n given.interactions,\n base.interactions,\n diagnostics,\n (value, previous) => resolveInteractions(value, previous, diagnostics),\n ),\n console: resolveCaptureOptions(\n \"console\",\n given.console,\n base.console,\n diagnostics,\n (value, previous) => ({\n levels: resolveList(\n \"capture.console.levels\",\n value.levels,\n previous.levels ?? [\"error\", \"warn\"],\n CONSOLE_LEVELS_EXPECTED,\n toConsoleMethod,\n diagnostics,\n ),\n }),\n ),\n longFrames: resolveCaptureOptions(\n \"longFrames\",\n given.longFrames,\n base.longFrames,\n diagnostics,\n (value, previous) => ({\n thresholdMs: resolveNonNegative(\n \"capture.longFrames.thresholdMs\",\n value.thresholdMs,\n previous.thresholdMs ?? LONG_FRAME_THRESHOLD_MS,\n diagnostics,\n ),\n }),\n ),\n userTiming: resolveCaptureOptions(\n \"userTiming\",\n given.userTiming,\n base.userTiming,\n diagnostics,\n (value, previous) => ({\n include: resolveList(\n \"capture.userTiming.include\",\n value.include,\n previous.include ?? [],\n PATTERN_LIST_EXPECTED,\n toPattern,\n diagnostics,\n ),\n }),\n ),\n webVitals: resolveCaptureOptions(\n \"webVitals\",\n given.webVitals,\n base.webVitals,\n diagnostics,\n (value, previous) => ({\n loader: resolveHook(\"capture.webVitals.loader\", value.loader, previous.loader, diagnostics),\n }),\n ),\n ignoreUrls: resolveList(\n \"capture.ignoreUrls\",\n given.ignoreUrls,\n base.ignoreUrls,\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/**\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 previous The current settings, or {} when the capture was a boolean.\n * @param diagnostics Diagnostics reporter.\n * @returns The valid settings, with invalid values replaced by the current ones.\n */\nfunction resolveInteractions(\n value: Record<string, unknown>,\n previous: InteractionOptions,\n diagnostics: Diagnostics,\n): InteractionOptions {\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\") {\n throw new Error(\"Invalid selector\");\n }\n if (typeof document !== \"undefined\") {\n document.createElement(\"div\").matches(ignoreSelector);\n }\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 null to turn the endpoint off.\n */\nfunction resolveSignalEndpoint(\n key: keyof typeof SIGNAL_OFF,\n value: unknown,\n fallback: string | null,\n serializer: SerializerChoice,\n diagnostics: Diagnostics,\n): string | null {\n const url = resolveDestination(key, value, fallback, diagnostics) as string | null;\n\n // A custom or ECS serializer can't encode a metrics or traces request.\n if (url !== null && serializer !== SERIALIZER_NAME_OTLP) {\n diagnostics.report(\n \"config.invalid\",\n `${key} needs serializer \"${SERIALIZER_NAME_OTLP}\". ${SIGNAL_OFF[key]}`,\n );\n return null;\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 range for each key that also takes null. */\n limits: 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 limit = rules.limits[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 (limit) {\n resolved = resolveLimit(\n `${name}.${key}`,\n value,\n limit,\n fallback as number | null,\n diagnostics,\n );\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 * Returns the input without a section that isn't an object, and reports each one. Otherwise\n * the library would ignore a section such as `capture: null` with no report.\n * @param input Partial consumer configuration options.\n * @param diagnostics Diagnostics reporter.\n * @returns The input, with every bad section left out so its current values stay.\n */\nfunction checkSections(\n input: Partial<ObservabilityConfig>,\n diagnostics: Diagnostics,\n): Partial<ObservabilityConfig> {\n let checked = input;\n\n for (const section of CONFIG_SECTIONS) {\n const value: unknown = input[section];\n if (value !== undefined && !isObject(value)) {\n reportInvalid(diagnostics, section, \"an object\", value, \"the current values\");\n checked = { ...checked, [section]: undefined };\n }\n }\n\n return checked;\n}\n\n/**\n * Reports each pair of settings where one of them does nothing, so the app learns why. The\n * values stay. Only a call that sets one of the pair reports it, so an unrelated later call\n * stays quiet.\n * @param input The options of this configure() call, after checkSections().\n * @param config The resolved config.\n * @param diagnostics Diagnostics reporter.\n */\nfunction reportIneffective(\n input: Partial<ObservabilityConfig>,\n config: ResolvedConfig,\n diagnostics: Diagnostics,\n): void {\n const { capture, sampling } = config;\n const noEffect = (key: string, condition: string): void => {\n diagnostics.report(\"config.invalid\", `${key} has no effect ${condition}. The value stays.`);\n };\n\n const setsTransport = input.transport !== undefined || input.transportWorker !== undefined;\n if (setsTransport && config.transport && config.transportWorker) {\n noEffect(\"transportWorker\", \"with transport\");\n }\n\n const setsExit = input.transport !== undefined || input.transportOnExit !== undefined;\n if (setsExit && config.transportOnExit && !config.transport) {\n noEffect(\"transportOnExit\", \"without transport\");\n }\n\n const setsToggles =\n input.capture?.remoteToggles !== undefined || input.sampling?.remote !== undefined;\n if (setsToggles && capture.remoteToggles.length > 0 && !sampling.remote) {\n noEffect(\"capture.remoteToggles\", \"without sampling.remote\");\n }\n\n // A remote rule can still turn on fetch or xhr, and then the targets apply.\n const requests =\n capture.fetch ||\n capture.xhr ||\n capture.remoteToggles.includes(\"fetch\") ||\n capture.remoteToggles.includes(\"xhr\");\n const setsTargets =\n input.capture?.propagateTraceHeaderTo !== undefined ||\n input.capture?.fetch !== undefined ||\n input.capture?.xhr !== undefined;\n if (setsTargets && capture.propagateTraceHeaderTo.length > 0 && !requests) {\n noEffect(\"capture.propagateTraceHeaderTo\", \"without capture.fetch or capture.xhr\");\n }\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 const given = checkSections(input, diagnostics);\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, given[key], base[key], POLICY_RULES[key], diagnostics),\n ]),\n ) as Pick<ResolvedConfig, PolicySection>;\n // Every key is read on its own. Spreading the input would let undefined remove a hook.\n const merged: ResolvedConfig = {\n ...base,\n ...policies,\n\n lockConfiguration: resolveBoolean(\n \"lockConfiguration\",\n given.lockConfiguration,\n base.lockConfiguration,\n diagnostics,\n ),\n loggerCache: {\n // 0 turns the cache off, and null lifts the limit.\n maxEntries: resolveLimit(\n \"loggerCache.maxEntries\",\n given.loggerCache?.maxEntries,\n COUNT_RANGE,\n base.loggerCache.maxEntries,\n diagnostics,\n ),\n },\n securityContext: {\n // An empty id keeps the current one, and the runtime creates one at startup.\n id:\n resolveString(\n \"securityContext.id\",\n given.securityContext?.id,\n base.securityContext.id,\n diagnostics,\n ) || base.securityContext.id,\n isolation: resolveBoolean(\n \"securityContext.isolation\",\n given.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: resolveEndpoint(given.endpoint, base.endpoint, diagnostics) as string | null,\n serviceName: resolveString(\"serviceName\", given.serviceName, base.serviceName, diagnostics),\n serviceVersion: resolveString(\n \"serviceVersion\",\n given.serviceVersion,\n base.serviceVersion,\n diagnostics,\n ),\n environment: resolveString(\"environment\", given.environment, base.environment, diagnostics),\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\", given.enabled, base.enabled, diagnostics),\n payloadMode: resolveChoice(\n \"payloadMode\",\n given.payloadMode,\n [\"copy\", \"defer\"] as const,\n base.payloadMode,\n diagnostics,\n ),\n minLevel: resolveLevel(\"minLevel\", given.minLevel, base.minLevel, diagnostics),\n minLevels: resolveMinLevels(given.minLevels, base.minLevels, diagnostics),\n processors: resolveProcessors(given.processors, base.processors, diagnostics),\n compression: resolveChoice(\n \"compression\",\n given.compression,\n COMPRESSION_VALUES,\n base.compression,\n diagnostics,\n ),\n credentials: resolveChoice(\n \"credentials\",\n given.credentials,\n CREDENTIALS_VALUES,\n base.credentials,\n diagnostics,\n ),\n headers: resolveHeaders(given.headers, base.headers, diagnostics),\n identity: resolveChoice(\n \"identity\",\n given.identity,\n IDENTITY_VALUES,\n base.identity,\n diagnostics,\n ),\n // A name stays a name, because the transport picks the implementation.\n serializer: resolveSerializer(given.serializer, previous?.serializer, diagnostics),\n consoleOutput: resolveConsole(given.consoleOutput, base.consoleOutput, diagnostics),\n sampling: resolveSampling(given.sampling, base.sampling, diagnostics),\n bus: resolveBus(given.bus, base.bus, diagnostics),\n batching: resolveRanges(\n \"batching\",\n given.batching,\n base.batching,\n BATCHING_RANGES,\n diagnostics,\n ),\n retention: resolveRetention(given.retention, base.retention, diagnostics),\n limits: resolveRanges(\"limits\", given.limits, base.limits, LIMIT_RANGES, diagnostics),\n journey: resolveJourney(given.journey, base.journey, diagnostics),\n capture: resolveCapture(given.capture, base.capture, diagnostics),\n // Without a transport function, the pipeline drops every batch, so a bad value keeps the\n // current one.\n transport: resolveHook(\"transport\", given.transport, base.transport, diagnostics),\n transportOnExit: resolveHook(\n \"transportOnExit\",\n given.transportOnExit,\n base.transportOnExit,\n diagnostics,\n ),\n transportWorker: resolveHook(\n \"transportWorker\",\n given.transportWorker,\n base.transportWorker,\n diagnostics,\n ),\n otelLoader: resolveHook(\"otelLoader\", given.otelLoader, base.otelLoader, diagnostics),\n contextProvider: resolveHook(\n \"contextProvider\",\n given.contextProvider,\n base.contextProvider,\n diagnostics,\n ),\n redact: resolveRedact(given.redact, base.redact, diagnostics),\n onDiagnostic: resolveHook(\"onDiagnostic\", given.onDiagnostic, base.onDiagnostic, diagnostics),\n onDrop: resolveHook(\"onDrop\", given.onDrop, base.onDrop, diagnostics),\n };\n\n for (const key of [\"metricsEndpoint\", \"tracesEndpoint\"] as const) {\n merged[key] = resolveSignalEndpoint(key, given[key], base[key], merged.serializer, diagnostics);\n }\n\n // null selects console-only mode. \"\" is the default when no call has set an endpoint.\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 }\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] !== null && 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 // 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 reportIneffective(given, merged, diagnostics);\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"],"mappings":"A,+EA2DA,IAAMgB,EAAc,OAAO,KAAKhB,EAAAA,EAAW,EAGrCiB,EAAqB,CAAC,OAAQ,MAAM,EACpCC,EAAqB,CAAC,OAAQ,cAAe,SAAS,EACtDC,EAAiB,CAAC,OAAQ,YAAa,eAAgB,SAAU,MAAM,EACvEC,EAAkB,CAAC,UAAW,QAAQ,EACtCC,EAAkB,CAAC,OAAQ,SAAU,YAAa,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ACF,EACA,iBAAkBwD,EAChB,4BACAT,EAAM,iBACNK,EAAK,iBACLpD,CACF,EACA,aAAcmC,EACZ,wBACAY,EAAM,aACNnE,EACAwE,EAAK,aACLpD,CACF,EAEA,qBAAsB+B,EACpB,gCACAgB,EAAM,qBACNpE,EACAyE,EAAK,qBACLpD,CACF,EACA,OAAQ6B,EAAe,kBAAmBkB,EAAM,OAAQK,EAAK,OAAQpD,CAAW,CAClF,CACF,CASA,SAASuF,GACP,EACA,EACA,EACY,CACZ,IAAMxC,EAAQC,GAAS,CAAC,EAGxB,MAAO,CACL,aAActB,EACZ,mBACAqB,EAAM,aACN,CAAC,aAAc,gBAAgB,EAC/BK,EAAK,aACLpD,CACF,EACA,gBAAiBmC,EACf,sBACAY,EAAM,gBACNlE,EACAuE,EAAK,gBACLpD,CACF,EACA,qBAAsBmC,EACpB,2BACAY,EAAM,qBACNlE,EACAuE,EAAK,qBACLpD,CACF,EACA,qBAAsBmC,EACpB,2BACAY,EAAM,qBACNlE,EACAuE,EAAK,qBACLpD,CACF,EACA,KAAM0B,EAAc,WAAYqB,EAAM,KAAMhF,EAAiBqF,EAAK,KAAMpD,CAAW,EAEnF,eAAgB6D,EACd,qBACAd,EAAM,eACNK,EAAK,eACLhC,GACAmD,GACAvE,CACF,EACA,YAAa0B,EACX,kBACAqB,EAAM,YACN/E,EACAoF,EAAK,YACLpD,CACF,CACF,CACF,CASA,SAASwF,GACP,EACA,EACA,EACgB,CAChB,IAAMzC,EAAQC,GAAS,CAAC,EAExB,MAAO,CACL,MAAOtB,EACL,gBACAqB,EAAM,MACN9E,EACAmF,EAAK,MACLpD,CACF,EACA,SAAU+B,EACR,mBACAgB,EAAM,SACNtE,GACA2E,EAAK,SACLpD,CACF,CACF,CACF,CASA,SAASyF,GACP,EACA,EACA,EACkB,CAClB,IAAM1C,EAAQC,GAAS,CAAC,EAExB,MAAO,CACL,WAAYjB,EACV,uBACAgB,EAAM,WACN1E,EACA+E,EAAK,WACLpD,CACF,EACA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