pcm-agents 0.6.11 → 0.6.13

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 (292) hide show
  1. package/dist/cjs/error-event-J_ZWIqWF.js +33 -0
  2. package/dist/cjs/error-event-J_ZWIqWF.js.map +1 -0
  3. package/dist/cjs/{index-CvEfNyEj.js → index-CRlt8Nv6.js} +53 -3
  4. package/dist/cjs/index-CRlt8Nv6.js.map +1 -0
  5. package/dist/cjs/index-WNdOTXnX.js +11068 -0
  6. package/dist/cjs/index-WNdOTXnX.js.map +1 -0
  7. package/dist/cjs/index.cjs.js +2 -2
  8. package/dist/cjs/loader.cjs.js +3 -5
  9. package/dist/cjs/loader.cjs.js.map +1 -1
  10. package/dist/cjs/message.service-DGUsA-FY.js +135 -0
  11. package/dist/cjs/message.service-DGUsA-FY.js.map +1 -0
  12. package/dist/cjs/{pcm-1zhanshi-mnms-modal_17.cjs.entry.js → pcm-1zhanshi-mnms-modal_21.cjs.entry.js} +3276 -216
  13. package/dist/cjs/pcm-1zhanshi-mnms-modal_21.cjs.entry.js.map +1 -0
  14. package/dist/cjs/pcm-agents.cjs.js +4 -6
  15. package/dist/cjs/pcm-agents.cjs.js.map +1 -1
  16. package/dist/cjs/pcm-message.cjs.entry.js +3 -3
  17. package/dist/cjs/pcm-message.cjs.entry.js.map +1 -1
  18. package/dist/cjs/pcm-message.entry.cjs.js.map +1 -1
  19. package/dist/cjs/pcm-mnms-video-modal.cjs.entry.js +8 -8
  20. package/dist/cjs/pcm-mnms-video-modal.cjs.entry.js.map +1 -1
  21. package/dist/cjs/pcm-mnms-video-modal.entry.cjs.js.map +1 -1
  22. package/dist/cjs/pcm-mnms-zp-modal.cjs.entry.js +29 -86
  23. package/dist/cjs/pcm-mnms-zp-modal.cjs.entry.js.map +1 -1
  24. package/dist/cjs/pcm-mnms-zp-modal.entry.cjs.js.map +1 -1
  25. package/dist/cjs/{sentry-reporter-BWFtw_aT.js → sentry-reporter-tpI4WdkE.js} +12 -40
  26. package/dist/cjs/sentry-reporter-tpI4WdkE.js.map +1 -0
  27. package/dist/collection/collection-manifest.json +5 -1
  28. package/dist/collection/components/pcm-1zhanshi-mnms-modal/pcm-1zhanshi-mnms-modal.js.map +1 -1
  29. package/dist/collection/components/pcm-app-chat-modal/pcm-app-chat-modal.css +986 -986
  30. package/dist/collection/components/pcm-app-chat-modal/pcm-app-chat-modal.js +7 -9
  31. package/dist/collection/components/pcm-app-chat-modal/pcm-app-chat-modal.js.map +1 -1
  32. package/dist/collection/components/pcm-button/pcm-button.css +199 -199
  33. package/dist/collection/components/pcm-button/pcm-button.js +6 -6
  34. package/dist/collection/components/pcm-button/pcm-button.js.map +1 -1
  35. package/dist/collection/components/pcm-card/pcm-card.css +259 -259
  36. package/dist/collection/components/pcm-card/pcm-card.js +1 -1
  37. package/dist/collection/components/pcm-card/pcm-card.js.map +1 -1
  38. package/dist/collection/components/pcm-chat-message/pcm-chat-message.css +554 -554
  39. package/dist/collection/components/pcm-chat-message/pcm-chat-message.js +3 -3
  40. package/dist/collection/components/pcm-chat-message/pcm-chat-message.js.map +1 -1
  41. package/dist/collection/components/pcm-drawer/pcm-drawer.css +102 -102
  42. package/dist/collection/components/pcm-drawer/pcm-drawer.js +1 -1
  43. package/dist/collection/components/pcm-drawer/pcm-drawer.js.map +1 -1
  44. package/dist/collection/components/pcm-hr-chat-modal/pcm-hr-chat-modal.css +854 -854
  45. package/dist/collection/components/pcm-hr-chat-modal/pcm-hr-chat-modal.js +5 -7
  46. package/dist/collection/components/pcm-hr-chat-modal/pcm-hr-chat-modal.js.map +1 -1
  47. package/dist/collection/components/pcm-htws-modal/pcm-htws-modal.css +95 -95
  48. package/dist/collection/components/pcm-htws-modal/pcm-htws-modal.js +1 -1
  49. package/dist/collection/components/pcm-htws-modal/pcm-htws-modal.js.map +1 -1
  50. package/dist/collection/components/pcm-hyzj-modal/pcm-hyzj-modal.js +2 -2
  51. package/dist/collection/components/pcm-hyzj-modal/pcm-hyzj-modal.js.map +1 -1
  52. package/dist/collection/components/pcm-jd-modal/pcm-jd-modal.css +312 -312
  53. package/dist/collection/components/pcm-jd-modal/pcm-jd-modal.js +1 -1
  54. package/dist/collection/components/pcm-jd-modal/pcm-jd-modal.js.map +1 -1
  55. package/dist/collection/components/pcm-jlpp-modal/pcm-jlpp-modal.js +2 -2
  56. package/dist/collection/components/pcm-jlpp-modal/pcm-jlpp-modal.js.map +1 -1
  57. package/dist/collection/components/pcm-message/pcm-message.css +64 -64
  58. package/dist/collection/components/pcm-message/pcm-message.js +2 -2
  59. package/dist/collection/components/pcm-message/pcm-message.js.map +1 -1
  60. package/dist/collection/components/pcm-mnct-modal/pcm-mnct-modal.css +1 -1
  61. package/dist/collection/components/pcm-mnct-modal/pcm-mnct-modal.js +2 -2
  62. package/dist/collection/components/pcm-mnct-modal/pcm-mnct-modal.js.map +1 -1
  63. package/dist/collection/components/pcm-mnms-modal/pcm-mnms-modal.js +67 -84
  64. package/dist/collection/components/pcm-mnms-modal/pcm-mnms-modal.js.map +1 -1
  65. package/dist/collection/components/pcm-mnms-video-modal/pcm-mnms-video-modal.js +2 -2
  66. package/dist/collection/components/pcm-mnms-video-modal/pcm-mnms-video-modal.js.map +1 -1
  67. package/dist/collection/components/pcm-mnms-zp-modal/pcm-mnms-zp-modal.js +67 -84
  68. package/dist/collection/components/pcm-mnms-zp-modal/pcm-mnms-zp-modal.js.map +1 -1
  69. package/dist/collection/components/pcm-mobile-input-btn/pcm-mobile-input-btn.css +140 -0
  70. package/dist/collection/components/pcm-mobile-input-btn/pcm-mobile-input-btn.js +307 -0
  71. package/dist/collection/components/pcm-mobile-input-btn/pcm-mobile-input-btn.js.map +1 -0
  72. package/dist/collection/components/pcm-mobile-input-btn/uploadNumberSDK.js +25 -0
  73. package/dist/collection/components/pcm-mobile-input-btn/uploadNumberSDK.js.map +1 -0
  74. package/dist/collection/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.css +127 -0
  75. package/dist/collection/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.js +350 -0
  76. package/dist/collection/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.js.map +1 -0
  77. package/dist/collection/components/pcm-mobile-upload-btn/uploadNumberSDK.js +25 -0
  78. package/dist/collection/components/pcm-mobile-upload-btn/uploadNumberSDK.js.map +1 -0
  79. package/dist/collection/components/pcm-msbg-modal/pcm-msbg-modal.js +2 -2
  80. package/dist/collection/components/pcm-msbg-modal/pcm-msbg-modal.js.map +1 -1
  81. package/dist/collection/components/pcm-qgqjl-modal/pcm-qgqjl-modal.css +1 -1
  82. package/dist/collection/components/pcm-qgqjl-modal/pcm-qgqjl-modal.js +2 -2
  83. package/dist/collection/components/pcm-qgqjl-modal/pcm-qgqjl-modal.js.map +1 -1
  84. package/dist/collection/components/pcm-time-count-down/pcm-time-count-down.css +0 -0
  85. package/dist/collection/components/pcm-time-count-down/pcm-time-count-down.js +106 -0
  86. package/dist/collection/components/pcm-time-count-down/pcm-time-count-down.js.map +1 -0
  87. package/dist/collection/components/pcm-upload/pcm-upload.css +0 -0
  88. package/dist/collection/components/pcm-upload/pcm-upload.js +408 -0
  89. package/dist/collection/components/pcm-upload/pcm-upload.js.map +1 -0
  90. package/dist/collection/components/pcm-zsk-chat-modal/pcm-zsk-chat-modal.css +969 -969
  91. package/dist/collection/components/pcm-zsk-chat-modal/pcm-zsk-chat-modal.js +3 -5
  92. package/dist/collection/components/pcm-zsk-chat-modal/pcm-zsk-chat-modal.js.map +1 -1
  93. package/dist/collection/components/pcm-zygh-modal/pcm-zygh-modal.css +68 -68
  94. package/dist/collection/components/pcm-zygh-modal/pcm-zygh-modal.js +4 -4
  95. package/dist/collection/components/pcm-zygh-modal/pcm-zygh-modal.js.map +1 -1
  96. package/dist/collection/global/global.css +401 -398
  97. package/dist/collection/global/markdown.css +1233 -1233
  98. package/dist/collection/global/message.js.map +1 -1
  99. package/dist/collection/index.js.map +1 -1
  100. package/dist/collection/interfaces/chat.js.map +1 -1
  101. package/dist/collection/interfaces/events.js.map +1 -1
  102. package/dist/collection/services/message.service.js.map +1 -1
  103. package/dist/collection/utils/env.js +3 -0
  104. package/dist/collection/utils/env.js.map +1 -1
  105. package/dist/collection/utils/error-event.js.map +1 -1
  106. package/dist/collection/utils/init.js.map +1 -1
  107. package/dist/collection/utils/sentry-reporter.js.map +1 -1
  108. package/dist/collection/utils/utils.js +48 -24
  109. package/dist/collection/utils/utils.js.map +1 -1
  110. package/dist/components/index.js +3 -5482
  111. package/dist/components/index.js.map +1 -1
  112. package/dist/components/{p-AYWZDCn8.js → p-B0WOTw9J.js} +51 -4
  113. package/dist/components/p-B0WOTw9J.js.map +1 -0
  114. package/dist/components/{p-DUQ46MUh.js → p-BGXbWUJg.js} +3 -3
  115. package/dist/components/{p-DUQ46MUh.js.map → p-BGXbWUJg.js.map} +1 -1
  116. package/dist/{esm/sentry-reporter-BFBS363a.js → components/p-BW3r6Lrf.js} +5 -32
  117. package/dist/components/p-BW3r6Lrf.js.map +1 -0
  118. package/dist/{esm/app-globals-Chti62re.js → components/p-BdiUKin5.js} +9619 -4296
  119. package/dist/components/p-BdiUKin5.js.map +1 -0
  120. package/dist/components/{p-FjtoYPVY.js → p-BywzltXy.js} +10 -9
  121. package/dist/components/p-BywzltXy.js.map +1 -0
  122. package/dist/components/p-C2OsjtRx.js +208 -0
  123. package/dist/components/p-C2OsjtRx.js.map +1 -0
  124. package/dist/components/{p-D2Z8casl.js → p-CuIvbaWY.js} +5 -5
  125. package/dist/components/p-CuIvbaWY.js.map +1 -0
  126. package/dist/components/p-D0ZMoyH8.js +251 -0
  127. package/dist/components/p-D0ZMoyH8.js.map +1 -0
  128. package/dist/components/{p-CjbFHLT7.js → p-De3VHEUn.js} +7 -71
  129. package/dist/components/p-De3VHEUn.js.map +1 -0
  130. package/dist/components/p-Dv8qvK0w.js +2646 -0
  131. package/dist/components/p-Dv8qvK0w.js.map +1 -0
  132. package/dist/components/p-RD3mwuBX.js +226 -0
  133. package/dist/components/p-RD3mwuBX.js.map +1 -0
  134. package/dist/components/p-njngFX_n.js +80 -0
  135. package/dist/components/p-njngFX_n.js.map +1 -0
  136. package/dist/components/pcm-1zhanshi-mnms-modal.js +7 -7
  137. package/dist/components/pcm-1zhanshi-mnms-modal.js.map +1 -1
  138. package/dist/components/pcm-app-chat-modal.js +1 -1
  139. package/dist/components/pcm-button.js +2 -2
  140. package/dist/components/pcm-button.js.map +1 -1
  141. package/dist/components/pcm-card.js +3 -3
  142. package/dist/components/pcm-card.js.map +1 -1
  143. package/dist/components/pcm-chat-message.js +1 -1
  144. package/dist/components/pcm-drawer.js +1 -1
  145. package/dist/components/pcm-hr-chat-modal.js +5 -4
  146. package/dist/components/pcm-hr-chat-modal.js.map +1 -1
  147. package/dist/components/pcm-htws-modal.js +8 -7
  148. package/dist/components/pcm-htws-modal.js.map +1 -1
  149. package/dist/components/pcm-hyzj-modal.js +8 -7
  150. package/dist/components/pcm-hyzj-modal.js.map +1 -1
  151. package/dist/components/pcm-jd-modal.js +8 -7
  152. package/dist/components/pcm-jd-modal.js.map +1 -1
  153. package/dist/components/pcm-jlpp-modal.js +8 -7
  154. package/dist/components/pcm-jlpp-modal.js.map +1 -1
  155. package/dist/components/pcm-message.js +3 -3
  156. package/dist/components/pcm-message.js.map +1 -1
  157. package/dist/components/pcm-mnct-modal.js +8 -7
  158. package/dist/components/pcm-mnct-modal.js.map +1 -1
  159. package/dist/components/pcm-mnms-modal.js +60 -90
  160. package/dist/components/pcm-mnms-modal.js.map +1 -1
  161. package/dist/components/pcm-mnms-video-modal.js +8 -7
  162. package/dist/components/pcm-mnms-video-modal.js.map +1 -1
  163. package/dist/components/pcm-mnms-zp-modal.js +60 -90
  164. package/dist/components/pcm-mnms-zp-modal.js.map +1 -1
  165. package/dist/components/pcm-mobile-input-btn.d.ts +11 -0
  166. package/dist/components/pcm-mobile-input-btn.js +9 -0
  167. package/dist/components/pcm-mobile-input-btn.js.map +1 -0
  168. package/dist/components/pcm-mobile-upload-btn.d.ts +11 -0
  169. package/dist/components/pcm-mobile-upload-btn.js +9 -0
  170. package/dist/components/pcm-mobile-upload-btn.js.map +1 -0
  171. package/dist/components/pcm-msbg-modal.js +8 -7
  172. package/dist/components/pcm-msbg-modal.js.map +1 -1
  173. package/dist/components/pcm-qgqjl-modal.js +8 -7
  174. package/dist/components/pcm-qgqjl-modal.js.map +1 -1
  175. package/dist/components/pcm-time-count-down.d.ts +11 -0
  176. package/dist/components/pcm-time-count-down.js +9 -0
  177. package/dist/components/pcm-time-count-down.js.map +1 -0
  178. package/dist/components/pcm-upload.d.ts +11 -0
  179. package/dist/components/pcm-upload.js +9 -0
  180. package/dist/components/pcm-upload.js.map +1 -0
  181. package/dist/components/pcm-zsk-chat-modal.js +4 -4
  182. package/dist/components/pcm-zsk-chat-modal.js.map +1 -1
  183. package/dist/components/pcm-zygh-modal.js +8 -7
  184. package/dist/components/pcm-zygh-modal.js.map +1 -1
  185. package/dist/esm/error-event-C0FYX2-Z.js +31 -0
  186. package/dist/esm/error-event-C0FYX2-Z.js.map +1 -0
  187. package/dist/esm/{index-GyOE8SlD.js → index-BnNqOUZf.js} +51 -4
  188. package/dist/esm/index-BnNqOUZf.js.map +1 -0
  189. package/dist/esm/index-BuVfV0zo.js +11035 -0
  190. package/dist/esm/index-BuVfV0zo.js.map +1 -0
  191. package/dist/esm/index.js +2 -2
  192. package/dist/esm/loader.js +3 -5
  193. package/dist/esm/loader.js.map +1 -1
  194. package/dist/esm/message.service-DXVhHj6-.js +133 -0
  195. package/dist/esm/message.service-DXVhHj6-.js.map +1 -0
  196. package/dist/esm/{pcm-1zhanshi-mnms-modal_17.entry.js → pcm-1zhanshi-mnms-modal_21.entry.js} +3225 -169
  197. package/dist/esm/pcm-1zhanshi-mnms-modal_21.entry.js.map +1 -0
  198. package/dist/esm/pcm-agents.js +4 -6
  199. package/dist/esm/pcm-agents.js.map +1 -1
  200. package/dist/esm/pcm-message.entry.js +3 -3
  201. package/dist/esm/pcm-message.entry.js.map +1 -1
  202. package/dist/esm/pcm-mnms-video-modal.entry.js +5 -5
  203. package/dist/esm/pcm-mnms-video-modal.entry.js.map +1 -1
  204. package/dist/esm/pcm-mnms-zp-modal.entry.js +28 -85
  205. package/dist/esm/pcm-mnms-zp-modal.entry.js.map +1 -1
  206. package/dist/esm/sentry-reporter-CYzy4_8O.js +70 -0
  207. package/dist/esm/sentry-reporter-CYzy4_8O.js.map +1 -0
  208. package/dist/pcm-agents/index.esm.js +1 -1
  209. package/dist/pcm-agents/loader.esm.js.map +1 -1
  210. package/dist/pcm-agents/p-18a06873.entry.js +2 -0
  211. package/dist/pcm-agents/p-18a06873.entry.js.map +1 -0
  212. package/dist/pcm-agents/p-47e2e1d0.entry.js +2 -0
  213. package/dist/pcm-agents/p-47e2e1d0.entry.js.map +1 -0
  214. package/dist/pcm-agents/{p-3608c0c6.entry.js → p-7a582f00.entry.js} +2 -2
  215. package/dist/pcm-agents/p-7a582f00.entry.js.map +1 -0
  216. package/dist/pcm-agents/p-BhFnI70g.js +2 -0
  217. package/dist/pcm-agents/p-BhFnI70g.js.map +1 -0
  218. package/dist/pcm-agents/p-BuVfV0zo.js +3 -0
  219. package/dist/pcm-agents/p-BuVfV0zo.js.map +1 -0
  220. package/dist/pcm-agents/p-C0FYX2-Z.js +2 -0
  221. package/dist/pcm-agents/p-C0FYX2-Z.js.map +1 -0
  222. package/dist/pcm-agents/p-DXVhHj6-.js +2 -0
  223. package/dist/pcm-agents/p-DXVhHj6-.js.map +1 -0
  224. package/dist/pcm-agents/p-DkeaAFic.js +2 -0
  225. package/dist/pcm-agents/p-DkeaAFic.js.map +1 -0
  226. package/dist/pcm-agents/p-f5f96853.entry.js +245 -0
  227. package/dist/pcm-agents/p-f5f96853.entry.js.map +1 -0
  228. package/dist/pcm-agents/pcm-agents.esm.js +1 -1
  229. package/dist/pcm-agents/pcm-agents.esm.js.map +1 -1
  230. package/dist/pcm-agents/pcm-message.entry.esm.js.map +1 -1
  231. package/dist/pcm-agents/pcm-mnms-video-modal.entry.esm.js.map +1 -1
  232. package/dist/pcm-agents/pcm-mnms-zp-modal.entry.esm.js.map +1 -1
  233. package/dist/store/auth.store.js.map +1 -1
  234. package/dist/store/config.store.js.map +1 -1
  235. package/dist/types/components/pcm-mnms-modal/pcm-mnms-modal.d.ts +9 -4
  236. package/dist/types/components/pcm-mnms-zp-modal/pcm-mnms-zp-modal.d.ts +9 -4
  237. package/dist/types/components/pcm-mobile-input-btn/pcm-mobile-input-btn.d.ts +36 -0
  238. package/dist/types/components/pcm-mobile-input-btn/uploadNumberSDK.d.ts +9 -0
  239. package/dist/types/components/pcm-mobile-upload-btn/pcm-mobile-upload-btn.d.ts +44 -0
  240. package/dist/types/components/pcm-mobile-upload-btn/uploadNumberSDK.d.ts +9 -0
  241. package/dist/types/components/pcm-time-count-down/pcm-time-count-down.d.ts +15 -0
  242. package/dist/types/components/pcm-upload/pcm-upload.d.ts +54 -0
  243. package/dist/types/components/pcm-upload/type.d.ts +4 -0
  244. package/dist/types/components.d.ts +798 -30
  245. package/dist/types/stencil-public-runtime.d.ts +1 -1
  246. package/dist/types/utils/env.d.ts +2 -0
  247. package/dist/types/utils/utils.d.ts +30 -12
  248. package/package.json +70 -69
  249. package/dist/cjs/app-globals-BIO4q6tX.js +0 -5487
  250. package/dist/cjs/app-globals-BIO4q6tX.js.map +0 -1
  251. package/dist/cjs/exports-Dc-pQh4A.js +0 -4087
  252. package/dist/cjs/exports-Dc-pQh4A.js.map +0 -1
  253. package/dist/cjs/index-C_qhED9Z.js +0 -1538
  254. package/dist/cjs/index-C_qhED9Z.js.map +0 -1
  255. package/dist/cjs/index-CvEfNyEj.js.map +0 -1
  256. package/dist/cjs/pcm-1zhanshi-mnms-modal_17.cjs.entry.js.map +0 -1
  257. package/dist/cjs/sentry-reporter-BWFtw_aT.js.map +0 -1
  258. package/dist/components/p-75J0r72D.js +0 -4017
  259. package/dist/components/p-75J0r72D.js.map +0 -1
  260. package/dist/components/p-AYWZDCn8.js.map +0 -1
  261. package/dist/components/p-CR7WLzmM.js +0 -1303
  262. package/dist/components/p-CR7WLzmM.js.map +0 -1
  263. package/dist/components/p-CjbFHLT7.js.map +0 -1
  264. package/dist/components/p-D2Z8casl.js.map +0 -1
  265. package/dist/components/p-FjtoYPVY.js.map +0 -1
  266. package/dist/esm/app-globals-Chti62re.js.map +0 -1
  267. package/dist/esm/exports-Bs-zO1WZ.js +0 -4017
  268. package/dist/esm/exports-Bs-zO1WZ.js.map +0 -1
  269. package/dist/esm/index-Bq0K-WqZ.js +0 -1528
  270. package/dist/esm/index-Bq0K-WqZ.js.map +0 -1
  271. package/dist/esm/index-GyOE8SlD.js.map +0 -1
  272. package/dist/esm/pcm-1zhanshi-mnms-modal_17.entry.js.map +0 -1
  273. package/dist/esm/sentry-reporter-BFBS363a.js.map +0 -1
  274. package/dist/pcm-agents/p-2Gpw8rvH.js +0 -2
  275. package/dist/pcm-agents/p-2Gpw8rvH.js.map +0 -1
  276. package/dist/pcm-agents/p-3608c0c6.entry.js.map +0 -1
  277. package/dist/pcm-agents/p-60d7a0b0.entry.js +0 -2
  278. package/dist/pcm-agents/p-60d7a0b0.entry.js.map +0 -1
  279. package/dist/pcm-agents/p-9e6efc2d.entry.js +0 -2
  280. package/dist/pcm-agents/p-9e6efc2d.entry.js.map +0 -1
  281. package/dist/pcm-agents/p-BUV0S8Cc.js +0 -2
  282. package/dist/pcm-agents/p-BUV0S8Cc.js.map +0 -1
  283. package/dist/pcm-agents/p-Bq0K-WqZ.js +0 -3
  284. package/dist/pcm-agents/p-Bq0K-WqZ.js.map +0 -1
  285. package/dist/pcm-agents/p-Bs-zO1WZ.js +0 -2
  286. package/dist/pcm-agents/p-Bs-zO1WZ.js.map +0 -1
  287. package/dist/pcm-agents/p-CeRTfvY9.js +0 -2
  288. package/dist/pcm-agents/p-CeRTfvY9.js.map +0 -1
  289. package/dist/pcm-agents/p-e6c87a78.entry.js +0 -2
  290. package/dist/pcm-agents/p-e6c87a78.entry.js.map +0 -1
  291. /package/dist/types/{code/agents-sdk → Users/debugksir/Documents/pcm/sdk}/packages/pcm-agents/.stencil/store/auth.store.d.ts +0 -0
  292. /package/dist/types/{code/agents-sdk → Users/debugksir/Documents/pcm/sdk}/packages/pcm-agents/.stencil/store/config.store.d.ts +0 -0
@@ -1,4087 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
5
- *
6
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
7
- */
8
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
9
-
10
- // This is a magic string replaced by rollup
11
-
12
- const SDK_VERSION = "9.22.0" ;
13
-
14
- /** Internal global with common properties and Sentry extensions */
15
-
16
- /** Get's the global object for the current JavaScript runtime */
17
- const GLOBAL_OBJ = globalThis ;
18
-
19
- /**
20
- * An object that contains globally accessible properties and maintains a scope stack.
21
- * @hidden
22
- */
23
-
24
- /**
25
- * Returns the global shim registry.
26
- *
27
- * FIXME: This function is problematic, because despite always returning a valid Carrier,
28
- * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check
29
- * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.
30
- **/
31
- function getMainCarrier() {
32
- // This ensures a Sentry carrier exists
33
- getSentryCarrier(GLOBAL_OBJ);
34
- return GLOBAL_OBJ;
35
- }
36
-
37
- /** Will either get the existing sentry carrier, or create a new one. */
38
- function getSentryCarrier(carrier) {
39
- const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});
40
-
41
- // For now: First SDK that sets the .version property wins
42
- __SENTRY__.version = __SENTRY__.version || SDK_VERSION;
43
-
44
- // Intentionally populating and returning the version of "this" SDK instance
45
- // rather than what's set in .version so that "this" SDK always gets its carrier
46
- return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});
47
- }
48
-
49
- /**
50
- * Returns a global singleton contained in the global `__SENTRY__[]` object.
51
- *
52
- * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory
53
- * function and added to the `__SENTRY__` object.
54
- *
55
- * @param name name of the global singleton on __SENTRY__
56
- * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`
57
- * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value
58
- * @returns the singleton
59
- */
60
- function getGlobalSingleton(
61
- name,
62
- creator,
63
- obj = GLOBAL_OBJ,
64
- ) {
65
- const __SENTRY__ = (obj.__SENTRY__ = obj.__SENTRY__ || {});
66
- const carrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});
67
- // Note: We do not want to set `carrier.version` here, as this may be called before any `init` is called, e.g. for the default scopes
68
- return carrier[name] || (carrier[name] = creator());
69
- }
70
-
71
- // eslint-disable-next-line @typescript-eslint/unbound-method
72
- const objectToString = Object.prototype.toString;
73
-
74
- /**
75
- * Checks whether given value's type is one of a few Error or Error-like
76
- * {@link isError}.
77
- *
78
- * @param wat A value to be checked.
79
- * @returns A boolean representing the result.
80
- */
81
- function isError(wat) {
82
- switch (objectToString.call(wat)) {
83
- case '[object Error]':
84
- case '[object Exception]':
85
- case '[object DOMException]':
86
- case '[object WebAssembly.Exception]':
87
- return true;
88
- default:
89
- return isInstanceOf(wat, Error);
90
- }
91
- }
92
- /**
93
- * Checks whether given value is an instance of the given built-in class.
94
- *
95
- * @param wat The value to be checked
96
- * @param className
97
- * @returns A boolean representing the result.
98
- */
99
- function isBuiltin(wat, className) {
100
- return objectToString.call(wat) === `[object ${className}]`;
101
- }
102
-
103
- /**
104
- * Checks whether given value's type is ErrorEvent
105
- * {@link isErrorEvent}.
106
- *
107
- * @param wat A value to be checked.
108
- * @returns A boolean representing the result.
109
- */
110
- function isErrorEvent(wat) {
111
- return isBuiltin(wat, 'ErrorEvent');
112
- }
113
-
114
- /**
115
- * Checks whether given value's type is DOMError
116
- * {@link isDOMError}.
117
- *
118
- * @param wat A value to be checked.
119
- * @returns A boolean representing the result.
120
- */
121
- function isDOMError(wat) {
122
- return isBuiltin(wat, 'DOMError');
123
- }
124
-
125
- /**
126
- * Checks whether given value's type is DOMException
127
- * {@link isDOMException}.
128
- *
129
- * @param wat A value to be checked.
130
- * @returns A boolean representing the result.
131
- */
132
- function isDOMException(wat) {
133
- return isBuiltin(wat, 'DOMException');
134
- }
135
-
136
- /**
137
- * Checks whether given value's type is a string
138
- * {@link isString}.
139
- *
140
- * @param wat A value to be checked.
141
- * @returns A boolean representing the result.
142
- */
143
- function isString(wat) {
144
- return isBuiltin(wat, 'String');
145
- }
146
-
147
- /**
148
- * Checks whether given string is parameterized
149
- * {@link isParameterizedString}.
150
- *
151
- * @param wat A value to be checked.
152
- * @returns A boolean representing the result.
153
- */
154
- function isParameterizedString(wat) {
155
- return (
156
- typeof wat === 'object' &&
157
- wat !== null &&
158
- '__sentry_template_string__' in wat &&
159
- '__sentry_template_values__' in wat
160
- );
161
- }
162
-
163
- /**
164
- * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)
165
- * {@link isPrimitive}.
166
- *
167
- * @param wat A value to be checked.
168
- * @returns A boolean representing the result.
169
- */
170
- function isPrimitive(wat) {
171
- return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');
172
- }
173
-
174
- /**
175
- * Checks whether given value's type is an object literal, or a class instance.
176
- * {@link isPlainObject}.
177
- *
178
- * @param wat A value to be checked.
179
- * @returns A boolean representing the result.
180
- */
181
- function isPlainObject(wat) {
182
- return isBuiltin(wat, 'Object');
183
- }
184
-
185
- /**
186
- * Checks whether given value's type is an Event instance
187
- * {@link isEvent}.
188
- *
189
- * @param wat A value to be checked.
190
- * @returns A boolean representing the result.
191
- */
192
- function isEvent(wat) {
193
- return typeof Event !== 'undefined' && isInstanceOf(wat, Event);
194
- }
195
-
196
- /**
197
- * Checks whether given value's type is an Element instance
198
- * {@link isElement}.
199
- *
200
- * @param wat A value to be checked.
201
- * @returns A boolean representing the result.
202
- */
203
- function isElement(wat) {
204
- return typeof Element !== 'undefined' && isInstanceOf(wat, Element);
205
- }
206
-
207
- /**
208
- * Checks whether given value's type is an regexp
209
- * {@link isRegExp}.
210
- *
211
- * @param wat A value to be checked.
212
- * @returns A boolean representing the result.
213
- */
214
- function isRegExp(wat) {
215
- return isBuiltin(wat, 'RegExp');
216
- }
217
-
218
- /**
219
- * Checks whether given value has a then function.
220
- * @param wat A value to be checked.
221
- */
222
- function isThenable(wat) {
223
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
224
- return Boolean(wat?.then && typeof wat.then === 'function');
225
- }
226
-
227
- /**
228
- * Checks whether given value's type is a SyntheticEvent
229
- * {@link isSyntheticEvent}.
230
- *
231
- * @param wat A value to be checked.
232
- * @returns A boolean representing the result.
233
- */
234
- function isSyntheticEvent(wat) {
235
- return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;
236
- }
237
-
238
- /**
239
- * Checks whether given value's type is an instance of provided constructor.
240
- * {@link isInstanceOf}.
241
- *
242
- * @param wat A value to be checked.
243
- * @param base A constructor to be used in a check.
244
- * @returns A boolean representing the result.
245
- */
246
- function isInstanceOf(wat, base) {
247
- try {
248
- return wat instanceof base;
249
- } catch (_e) {
250
- return false;
251
- }
252
- }
253
-
254
- /**
255
- * Checks whether given value's type is a Vue ViewModel.
256
- *
257
- * @param wat A value to be checked.
258
- * @returns A boolean representing the result.
259
- */
260
- function isVueViewModel(wat) {
261
- // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.
262
- return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));
263
- }
264
-
265
- /**
266
- * Checks whether the given parameter is a Standard Web API Request instance.
267
- *
268
- * Returns false if Request is not available in the current runtime.
269
- */
270
- function isRequest(request) {
271
- return typeof Request !== 'undefined' && isInstanceOf(request, Request);
272
- }
273
-
274
- const WINDOW = GLOBAL_OBJ ;
275
-
276
- const DEFAULT_MAX_STRING_LENGTH = 80;
277
-
278
- /**
279
- * Given a child DOM element, returns a query-selector statement describing that
280
- * and its ancestors
281
- * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
282
- * @returns generated DOM path
283
- */
284
- function htmlTreeAsString(
285
- elem,
286
- options = {},
287
- ) {
288
- if (!elem) {
289
- return '<unknown>';
290
- }
291
-
292
- // try/catch both:
293
- // - accessing event.target (see getsentry/raven-js#838, #768)
294
- // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly
295
- // - can throw an exception in some circumstances.
296
- try {
297
- let currentElem = elem ;
298
- const MAX_TRAVERSE_HEIGHT = 5;
299
- const out = [];
300
- let height = 0;
301
- let len = 0;
302
- const separator = ' > ';
303
- const sepLength = separator.length;
304
- let nextStr;
305
- const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
306
- const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;
307
-
308
- while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
309
- nextStr = _htmlElementAsString(currentElem, keyAttrs);
310
- // bail out if
311
- // - nextStr is the 'html' element
312
- // - the length of the string that would be created exceeds maxStringLength
313
- // (ignore this limit if we are on the first iteration)
314
- if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {
315
- break;
316
- }
317
-
318
- out.push(nextStr);
319
-
320
- len += nextStr.length;
321
- currentElem = currentElem.parentNode;
322
- }
323
-
324
- return out.reverse().join(separator);
325
- } catch (_oO) {
326
- return '<unknown>';
327
- }
328
- }
329
-
330
- /**
331
- * Returns a simple, query-selector representation of a DOM element
332
- * e.g. [HTMLElement] => input#foo.btn[name=baz]
333
- * @returns generated DOM path
334
- */
335
- function _htmlElementAsString(el, keyAttrs) {
336
- const elem = el
337
-
338
- ;
339
-
340
- const out = [];
341
-
342
- if (!elem?.tagName) {
343
- return '';
344
- }
345
-
346
- // @ts-expect-error WINDOW has HTMLElement
347
- if (WINDOW.HTMLElement) {
348
- // If using the component name annotation plugin, this value may be available on the DOM node
349
- if (elem instanceof HTMLElement && elem.dataset) {
350
- if (elem.dataset['sentryComponent']) {
351
- return elem.dataset['sentryComponent'];
352
- }
353
- if (elem.dataset['sentryElement']) {
354
- return elem.dataset['sentryElement'];
355
- }
356
- }
357
- }
358
-
359
- out.push(elem.tagName.toLowerCase());
360
-
361
- // Pairs of attribute keys defined in `serializeAttribute` and their values on element.
362
- const keyAttrPairs = keyAttrs?.length
363
- ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])
364
- : null;
365
-
366
- if (keyAttrPairs?.length) {
367
- keyAttrPairs.forEach(keyAttrPair => {
368
- out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
369
- });
370
- } else {
371
- if (elem.id) {
372
- out.push(`#${elem.id}`);
373
- }
374
-
375
- const className = elem.className;
376
- if (className && isString(className)) {
377
- const classes = className.split(/\s+/);
378
- for (const c of classes) {
379
- out.push(`.${c}`);
380
- }
381
- }
382
- }
383
- const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];
384
- for (const k of allowedAttrs) {
385
- const attr = elem.getAttribute(k);
386
- if (attr) {
387
- out.push(`[${k}="${attr}"]`);
388
- }
389
- }
390
-
391
- return out.join('');
392
- }
393
-
394
- /**
395
- * A safe form of location.href
396
- */
397
- function getLocationHref() {
398
- try {
399
- return WINDOW.document.location.href;
400
- } catch (oO) {
401
- return '';
402
- }
403
- }
404
-
405
- /**
406
- * Given a DOM element, traverses up the tree until it finds the first ancestor node
407
- * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking
408
- * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed.
409
- *
410
- * @returns a string representation of the component for the provided DOM element, or `null` if not found
411
- */
412
- function getComponentName(elem) {
413
- // @ts-expect-error WINDOW has HTMLElement
414
- if (!WINDOW.HTMLElement) {
415
- return null;
416
- }
417
-
418
- let currentElem = elem ;
419
- const MAX_TRAVERSE_HEIGHT = 5;
420
- for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {
421
- if (!currentElem) {
422
- return null;
423
- }
424
-
425
- if (currentElem instanceof HTMLElement) {
426
- if (currentElem.dataset['sentryComponent']) {
427
- return currentElem.dataset['sentryComponent'];
428
- }
429
- if (currentElem.dataset['sentryElement']) {
430
- return currentElem.dataset['sentryElement'];
431
- }
432
- }
433
-
434
- currentElem = currentElem.parentNode;
435
- }
436
-
437
- return null;
438
- }
439
-
440
- /** Prefix for logging strings */
441
- const PREFIX = 'Sentry Logger ';
442
-
443
- const CONSOLE_LEVELS = [
444
- 'debug',
445
- 'info',
446
- 'warn',
447
- 'error',
448
- 'log',
449
- 'assert',
450
- 'trace',
451
- ] ;
452
-
453
- /** This may be mutated by the console instrumentation. */
454
- const originalConsoleMethods
455
-
456
- = {};
457
-
458
- /** A Sentry Logger instance. */
459
-
460
- /**
461
- * Temporarily disable sentry console instrumentations.
462
- *
463
- * @param callback The function to run against the original `console` messages
464
- * @returns The results of the callback
465
- */
466
- function consoleSandbox(callback) {
467
- if (!('console' in GLOBAL_OBJ)) {
468
- return callback();
469
- }
470
-
471
- const console = GLOBAL_OBJ.console ;
472
- const wrappedFuncs = {};
473
-
474
- const wrappedLevels = Object.keys(originalConsoleMethods) ;
475
-
476
- // Restore all wrapped console methods
477
- wrappedLevels.forEach(level => {
478
- const originalConsoleMethod = originalConsoleMethods[level] ;
479
- wrappedFuncs[level] = console[level] ;
480
- console[level] = originalConsoleMethod;
481
- });
482
-
483
- try {
484
- return callback();
485
- } finally {
486
- // Revert restoration to wrapped state
487
- wrappedLevels.forEach(level => {
488
- console[level] = wrappedFuncs[level] ;
489
- });
490
- }
491
- }
492
-
493
- function makeLogger() {
494
- let enabled = false;
495
- const logger = {
496
- enable: () => {
497
- enabled = true;
498
- },
499
- disable: () => {
500
- enabled = false;
501
- },
502
- isEnabled: () => enabled,
503
- };
504
-
505
- if (DEBUG_BUILD) {
506
- CONSOLE_LEVELS.forEach(name => {
507
- logger[name] = (...args) => {
508
- if (enabled) {
509
- consoleSandbox(() => {
510
- GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);
511
- });
512
- }
513
- };
514
- });
515
- } else {
516
- CONSOLE_LEVELS.forEach(name => {
517
- logger[name] = () => undefined;
518
- });
519
- }
520
-
521
- return logger ;
522
- }
523
-
524
- /**
525
- * This is a logger singleton which either logs things or no-ops if logging is not enabled.
526
- * The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK.
527
- */
528
- const logger = getGlobalSingleton('logger', makeLogger);
529
-
530
- /**
531
- * Truncates given string to the maximum characters count
532
- *
533
- * @param str An object that contains serializable values
534
- * @param max Maximum number of characters in truncated string (0 = unlimited)
535
- * @returns string Encoded
536
- */
537
- function truncate(str, max = 0) {
538
- if (typeof str !== 'string' || max === 0) {
539
- return str;
540
- }
541
- return str.length <= max ? str : `${str.slice(0, max)}...`;
542
- }
543
-
544
- /**
545
- * Join values in array
546
- * @param input array of values to be joined together
547
- * @param delimiter string to be placed in-between values
548
- * @returns Joined values
549
- */
550
- function safeJoin(input, delimiter) {
551
- if (!Array.isArray(input)) {
552
- return '';
553
- }
554
-
555
- const output = [];
556
- // eslint-disable-next-line @typescript-eslint/prefer-for-of
557
- for (let i = 0; i < input.length; i++) {
558
- const value = input[i];
559
- try {
560
- // This is a hack to fix a Vue3-specific bug that causes an infinite loop of
561
- // console warnings. This happens when a Vue template is rendered with
562
- // an undeclared variable, which we try to stringify, ultimately causing
563
- // Vue to issue another warning which repeats indefinitely.
564
- // see: https://github.com/getsentry/sentry-javascript/pull/8981
565
- if (isVueViewModel(value)) {
566
- output.push('[VueViewModel]');
567
- } else {
568
- output.push(String(value));
569
- }
570
- } catch (e) {
571
- output.push('[value cannot be serialized]');
572
- }
573
- }
574
-
575
- return output.join(delimiter);
576
- }
577
-
578
- /**
579
- * Checks if the given value matches a regex or string
580
- *
581
- * @param value The string to test
582
- * @param pattern Either a regex or a string against which `value` will be matched
583
- * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match
584
- * `pattern` if it contains `pattern`. Only applies to string-type patterns.
585
- */
586
- function isMatchingPattern(
587
- value,
588
- pattern,
589
- requireExactStringMatch = false,
590
- ) {
591
- if (!isString(value)) {
592
- return false;
593
- }
594
-
595
- if (isRegExp(pattern)) {
596
- return pattern.test(value);
597
- }
598
- if (isString(pattern)) {
599
- return requireExactStringMatch ? value === pattern : value.includes(pattern);
600
- }
601
-
602
- return false;
603
- }
604
-
605
- /**
606
- * Test the given string against an array of strings and regexes. By default, string matching is done on a
607
- * substring-inclusion basis rather than a strict equality basis
608
- *
609
- * @param testString The string to test
610
- * @param patterns The patterns against which to test the string
611
- * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to
612
- * count. If false, `testString` will match a string pattern if it contains that pattern.
613
- * @returns
614
- */
615
- function stringMatchesSomePattern(
616
- testString,
617
- patterns = [],
618
- requireExactStringMatch = false,
619
- ) {
620
- return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));
621
- }
622
-
623
- /**
624
- * Replace a method in an object with a wrapped version of itself.
625
- *
626
- * If the method on the passed object is not a function, the wrapper will not be applied.
627
- *
628
- * @param source An object that contains a method to be wrapped.
629
- * @param name The name of the method to be wrapped.
630
- * @param replacementFactory A higher-order function that takes the original version of the given method and returns a
631
- * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to
632
- * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other
633
- * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.
634
- * @returns void
635
- */
636
- function fill(source, name, replacementFactory) {
637
- if (!(name in source)) {
638
- return;
639
- }
640
-
641
- // explicitly casting to unknown because we don't know the type of the method initially at all
642
- const original = source[name] ;
643
-
644
- if (typeof original !== 'function') {
645
- return;
646
- }
647
-
648
- const wrapped = replacementFactory(original) ;
649
-
650
- // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work
651
- // otherwise it'll throw "TypeError: Object.defineProperties called on non-object"
652
- if (typeof wrapped === 'function') {
653
- markFunctionWrapped(wrapped, original);
654
- }
655
-
656
- try {
657
- source[name] = wrapped;
658
- } catch {
659
- DEBUG_BUILD && logger.log(`Failed to replace method "${name}" in object`, source);
660
- }
661
- }
662
-
663
- /**
664
- * Defines a non-enumerable property on the given object.
665
- *
666
- * @param obj The object on which to set the property
667
- * @param name The name of the property to be set
668
- * @param value The value to which to set the property
669
- */
670
- function addNonEnumerableProperty(obj, name, value) {
671
- try {
672
- Object.defineProperty(obj, name, {
673
- // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
674
- value: value,
675
- writable: true,
676
- configurable: true,
677
- });
678
- } catch (o_O) {
679
- DEBUG_BUILD && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj);
680
- }
681
- }
682
-
683
- /**
684
- * Remembers the original function on the wrapped function and
685
- * patches up the prototype.
686
- *
687
- * @param wrapped the wrapper function
688
- * @param original the original function that gets wrapped
689
- */
690
- function markFunctionWrapped(wrapped, original) {
691
- try {
692
- const proto = original.prototype || {};
693
- wrapped.prototype = original.prototype = proto;
694
- addNonEnumerableProperty(wrapped, '__sentry_original__', original);
695
- } catch (o_O) {} // eslint-disable-line no-empty
696
- }
697
-
698
- /**
699
- * This extracts the original function if available. See
700
- * `markFunctionWrapped` for more information.
701
- *
702
- * @param func the function to unwrap
703
- * @returns the unwrapped version of the function if available.
704
- */
705
- // eslint-disable-next-line @typescript-eslint/ban-types
706
- function getOriginalFunction(func) {
707
- return func.__sentry_original__;
708
- }
709
-
710
- /**
711
- * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
712
- * non-enumerable properties attached.
713
- *
714
- * @param value Initial source that we have to transform in order for it to be usable by the serializer
715
- * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
716
- * an Error.
717
- */
718
- function convertToPlainObject(value)
719
-
720
- {
721
- if (isError(value)) {
722
- return {
723
- message: value.message,
724
- name: value.name,
725
- stack: value.stack,
726
- ...getOwnProperties(value),
727
- };
728
- } else if (isEvent(value)) {
729
- const newObj
730
-
731
- = {
732
- type: value.type,
733
- target: serializeEventTarget(value.target),
734
- currentTarget: serializeEventTarget(value.currentTarget),
735
- ...getOwnProperties(value),
736
- };
737
-
738
- if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
739
- newObj.detail = value.detail;
740
- }
741
-
742
- return newObj;
743
- } else {
744
- return value;
745
- }
746
- }
747
-
748
- /** Creates a string representation of the target of an `Event` object */
749
- function serializeEventTarget(target) {
750
- try {
751
- return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
752
- } catch (_oO) {
753
- return '<unknown>';
754
- }
755
- }
756
-
757
- /** Filters out all but an object's own properties */
758
- function getOwnProperties(obj) {
759
- if (typeof obj === 'object' && obj !== null) {
760
- const extractedProps = {};
761
- for (const property in obj) {
762
- if (Object.prototype.hasOwnProperty.call(obj, property)) {
763
- extractedProps[property] = (obj )[property];
764
- }
765
- }
766
- return extractedProps;
767
- } else {
768
- return {};
769
- }
770
- }
771
-
772
- /**
773
- * Given any captured exception, extract its keys and create a sorted
774
- * and truncated list that will be used inside the event message.
775
- * eg. `Non-error exception captured with keys: foo, bar, baz`
776
- */
777
- function extractExceptionKeysForMessage(exception, maxLength = 40) {
778
- const keys = Object.keys(convertToPlainObject(exception));
779
- keys.sort();
780
-
781
- const firstKey = keys[0];
782
-
783
- if (!firstKey) {
784
- return '[object has no keys]';
785
- }
786
-
787
- if (firstKey.length >= maxLength) {
788
- return truncate(firstKey, maxLength);
789
- }
790
-
791
- for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
792
- const serialized = keys.slice(0, includedKeys).join(', ');
793
- if (serialized.length > maxLength) {
794
- continue;
795
- }
796
- if (includedKeys === keys.length) {
797
- return serialized;
798
- }
799
- return truncate(serialized, maxLength);
800
- }
801
-
802
- return '';
803
- }
804
-
805
- function getCrypto() {
806
- const gbl = GLOBAL_OBJ ;
807
- return gbl.crypto || gbl.msCrypto;
808
- }
809
-
810
- /**
811
- * UUID4 generator
812
- * @param crypto Object that provides the crypto API.
813
- * @returns string Generated UUID4.
814
- */
815
- function uuid4(crypto = getCrypto()) {
816
- let getRandomByte = () => Math.random() * 16;
817
- try {
818
- if (crypto?.randomUUID) {
819
- return crypto.randomUUID().replace(/-/g, '');
820
- }
821
- if (crypto?.getRandomValues) {
822
- getRandomByte = () => {
823
- // crypto.getRandomValues might return undefined instead of the typed array
824
- // in old Chromium versions (e.g. 23.0.1235.0 (151422))
825
- // However, `typedArray` is still filled in-place.
826
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray
827
- const typedArray = new Uint8Array(1);
828
- crypto.getRandomValues(typedArray);
829
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
830
- return typedArray[0];
831
- };
832
- }
833
- } catch (_) {
834
- // some runtimes can crash invoking crypto
835
- // https://github.com/getsentry/sentry-javascript/issues/8935
836
- }
837
-
838
- // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
839
- // Concatenating the following numbers as strings results in '10000000100040008000100000000000'
840
- return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>
841
- // eslint-disable-next-line no-bitwise
842
- ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),
843
- );
844
- }
845
-
846
- function getFirstException(event) {
847
- return event.exception?.values?.[0];
848
- }
849
-
850
- /**
851
- * Extracts either message or type+value from an event that can be used for user-facing logs
852
- * @returns event's description
853
- */
854
- function getEventDescription(event) {
855
- const { message, event_id: eventId } = event;
856
- if (message) {
857
- return message;
858
- }
859
-
860
- const firstException = getFirstException(event);
861
- if (firstException) {
862
- if (firstException.type && firstException.value) {
863
- return `${firstException.type}: ${firstException.value}`;
864
- }
865
- return firstException.type || firstException.value || eventId || '<unknown>';
866
- }
867
- return eventId || '<unknown>';
868
- }
869
-
870
- /**
871
- * Adds exception values, type and value to an synthetic Exception.
872
- * @param event The event to modify.
873
- * @param value Value of the exception.
874
- * @param type Type of the exception.
875
- * @hidden
876
- */
877
- function addExceptionTypeValue(event, value, type) {
878
- const exception = (event.exception = event.exception || {});
879
- const values = (exception.values = exception.values || []);
880
- const firstException = (values[0] = values[0] || {});
881
- if (!firstException.value) {
882
- firstException.value = value || '';
883
- }
884
- if (!firstException.type) {
885
- firstException.type = 'Error';
886
- }
887
- }
888
-
889
- /**
890
- * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
891
- *
892
- * @param event The event to modify.
893
- * @param newMechanism Mechanism data to add to the event.
894
- * @hidden
895
- */
896
- function addExceptionMechanism(event, newMechanism) {
897
- const firstException = getFirstException(event);
898
- if (!firstException) {
899
- return;
900
- }
901
-
902
- const defaultMechanism = { type: 'generic', handled: true };
903
- const currentMechanism = firstException.mechanism;
904
- firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
905
-
906
- if (newMechanism && 'data' in newMechanism) {
907
- const mergedData = { ...currentMechanism?.data, ...newMechanism.data };
908
- firstException.mechanism.data = mergedData;
909
- }
910
- }
911
-
912
- /**
913
- * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object
914
- * in question), and marks it captured if not.
915
- *
916
- * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and
917
- * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so
918
- * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because
919
- * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not
920
- * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This
921
- * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we
922
- * see it.
923
- *
924
- * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on
925
- * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent
926
- * object wrapper forms so that this check will always work. However, because we need to flag the exact object which
927
- * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification
928
- * must be done before the exception captured.
929
- *
930
- * @param A thrown exception to check or flag as having been seen
931
- * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
932
- */
933
- function checkOrSetAlreadyCaught(exception) {
934
- if (isAlreadyCaptured(exception)) {
935
- return true;
936
- }
937
-
938
- try {
939
- // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the
940
- // `ExtraErrorData` integration
941
- addNonEnumerableProperty(exception , '__sentry_captured__', true);
942
- } catch (err) {
943
- // `exception` is a primitive, so we can't mark it seen
944
- }
945
-
946
- return false;
947
- }
948
-
949
- function isAlreadyCaptured(exception) {
950
- try {
951
- return (exception ).__sentry_captured__;
952
- } catch {} // eslint-disable-line no-empty
953
- }
954
-
955
- const ONE_SECOND_IN_MS = 1000;
956
-
957
- /**
958
- * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}
959
- * for accessing a high-resolution monotonic clock.
960
- */
961
-
962
- /**
963
- * Returns a timestamp in seconds since the UNIX epoch using the Date API.
964
- */
965
- function dateTimestampInSeconds() {
966
- return Date.now() / ONE_SECOND_IN_MS;
967
- }
968
-
969
- /**
970
- * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not
971
- * support the API.
972
- *
973
- * Wrapping the native API works around differences in behavior from different browsers.
974
- */
975
- function createUnixTimestampInSecondsFunc() {
976
- const { performance } = GLOBAL_OBJ ;
977
- if (!performance?.now) {
978
- return dateTimestampInSeconds;
979
- }
980
-
981
- // Some browser and environments don't have a timeOrigin, so we fallback to
982
- // using Date.now() to compute the starting time.
983
- const approxStartingTimeOrigin = Date.now() - performance.now();
984
- const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;
985
-
986
- // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current
987
- // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.
988
- //
989
- // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the
990
- // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and
991
- // correct for this.
992
- // See: https://github.com/getsentry/sentry-javascript/issues/2590
993
- // See: https://github.com/mdn/content/issues/4713
994
- // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6
995
- return () => {
996
- return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;
997
- };
998
- }
999
-
1000
- /**
1001
- * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the
1002
- * availability of the Performance API.
1003
- *
1004
- * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is
1005
- * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The
1006
- * skew can grow to arbitrary amounts like days, weeks or months.
1007
- * See https://github.com/getsentry/sentry-javascript/issues/2590.
1008
- */
1009
- const timestampInSeconds = createUnixTimestampInSecondsFunc();
1010
-
1011
- /**
1012
- * Creates a new `Session` object by setting certain default parameters. If optional @param context
1013
- * is passed, the passed properties are applied to the session object.
1014
- *
1015
- * @param context (optional) additional properties to be applied to the returned session object
1016
- *
1017
- * @returns a new `Session` object
1018
- */
1019
- function makeSession(context) {
1020
- // Both timestamp and started are in seconds since the UNIX epoch.
1021
- const startingTime = timestampInSeconds();
1022
-
1023
- const session = {
1024
- sid: uuid4(),
1025
- init: true,
1026
- timestamp: startingTime,
1027
- started: startingTime,
1028
- duration: 0,
1029
- status: 'ok',
1030
- errors: 0,
1031
- ignoreDuration: false,
1032
- toJSON: () => sessionToJSON(session),
1033
- };
1034
-
1035
- if (context) {
1036
- updateSession(session, context);
1037
- }
1038
-
1039
- return session;
1040
- }
1041
-
1042
- /**
1043
- * Updates a session object with the properties passed in the context.
1044
- *
1045
- * Note that this function mutates the passed object and returns void.
1046
- * (Had to do this instead of returning a new and updated session because closing and sending a session
1047
- * makes an update to the session after it was passed to the sending logic.
1048
- * @see Client.captureSession )
1049
- *
1050
- * @param session the `Session` to update
1051
- * @param context the `SessionContext` holding the properties that should be updated in @param session
1052
- */
1053
- // eslint-disable-next-line complexity
1054
- function updateSession(session, context = {}) {
1055
- if (context.user) {
1056
- if (!session.ipAddress && context.user.ip_address) {
1057
- session.ipAddress = context.user.ip_address;
1058
- }
1059
-
1060
- if (!session.did && !context.did) {
1061
- session.did = context.user.id || context.user.email || context.user.username;
1062
- }
1063
- }
1064
-
1065
- session.timestamp = context.timestamp || timestampInSeconds();
1066
-
1067
- if (context.abnormal_mechanism) {
1068
- session.abnormal_mechanism = context.abnormal_mechanism;
1069
- }
1070
-
1071
- if (context.ignoreDuration) {
1072
- session.ignoreDuration = context.ignoreDuration;
1073
- }
1074
- if (context.sid) {
1075
- // Good enough uuid validation. — Kamil
1076
- session.sid = context.sid.length === 32 ? context.sid : uuid4();
1077
- }
1078
- if (context.init !== undefined) {
1079
- session.init = context.init;
1080
- }
1081
- if (!session.did && context.did) {
1082
- session.did = `${context.did}`;
1083
- }
1084
- if (typeof context.started === 'number') {
1085
- session.started = context.started;
1086
- }
1087
- if (session.ignoreDuration) {
1088
- session.duration = undefined;
1089
- } else if (typeof context.duration === 'number') {
1090
- session.duration = context.duration;
1091
- } else {
1092
- const duration = session.timestamp - session.started;
1093
- session.duration = duration >= 0 ? duration : 0;
1094
- }
1095
- if (context.release) {
1096
- session.release = context.release;
1097
- }
1098
- if (context.environment) {
1099
- session.environment = context.environment;
1100
- }
1101
- if (!session.ipAddress && context.ipAddress) {
1102
- session.ipAddress = context.ipAddress;
1103
- }
1104
- if (!session.userAgent && context.userAgent) {
1105
- session.userAgent = context.userAgent;
1106
- }
1107
- if (typeof context.errors === 'number') {
1108
- session.errors = context.errors;
1109
- }
1110
- if (context.status) {
1111
- session.status = context.status;
1112
- }
1113
- }
1114
-
1115
- /**
1116
- * Closes a session by setting its status and updating the session object with it.
1117
- * Internally calls `updateSession` to update the passed session object.
1118
- *
1119
- * Note that this function mutates the passed session (@see updateSession for explanation).
1120
- *
1121
- * @param session the `Session` object to be closed
1122
- * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,
1123
- * this function will keep the previously set status, unless it was `'ok'` in which case
1124
- * it is changed to `'exited'`.
1125
- */
1126
- function closeSession(session, status) {
1127
- let context = {};
1128
- if (session.status === 'ok') {
1129
- context = { status: 'exited' };
1130
- }
1131
-
1132
- updateSession(session, context);
1133
- }
1134
-
1135
- /**
1136
- * Serializes a passed session object to a JSON object with a slightly different structure.
1137
- * This is necessary because the Sentry backend requires a slightly different schema of a session
1138
- * than the one the JS SDKs use internally.
1139
- *
1140
- * @param session the session to be converted
1141
- *
1142
- * @returns a JSON object of the passed session
1143
- */
1144
- function sessionToJSON(session) {
1145
- return {
1146
- sid: `${session.sid}`,
1147
- init: session.init,
1148
- // Make sure that sec is converted to ms for date constructor
1149
- started: new Date(session.started * 1000).toISOString(),
1150
- timestamp: new Date(session.timestamp * 1000).toISOString(),
1151
- status: session.status,
1152
- errors: session.errors,
1153
- did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,
1154
- duration: session.duration,
1155
- abnormal_mechanism: session.abnormal_mechanism,
1156
- attrs: {
1157
- release: session.release,
1158
- environment: session.environment,
1159
- ip_address: session.ipAddress,
1160
- user_agent: session.userAgent,
1161
- },
1162
- };
1163
- }
1164
-
1165
- /**
1166
- * Shallow merge two objects.
1167
- * Does not mutate the passed in objects.
1168
- * Undefined/empty values in the merge object will overwrite existing values.
1169
- *
1170
- * By default, this merges 2 levels deep.
1171
- */
1172
- function merge(initialObj, mergeObj, levels = 2) {
1173
- // If the merge value is not an object, or we have no merge levels left,
1174
- // we just set the value to the merge value
1175
- if (!mergeObj || typeof mergeObj !== 'object' || levels <= 0) {
1176
- return mergeObj;
1177
- }
1178
-
1179
- // If the merge object is an empty object, and the initial object is not undefined, we return the initial object
1180
- if (initialObj && Object.keys(mergeObj).length === 0) {
1181
- return initialObj;
1182
- }
1183
-
1184
- // Clone object
1185
- const output = { ...initialObj };
1186
-
1187
- // Merge values into output, resursively
1188
- for (const key in mergeObj) {
1189
- if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {
1190
- output[key] = merge(output[key], mergeObj[key], levels - 1);
1191
- }
1192
- }
1193
-
1194
- return output;
1195
- }
1196
-
1197
- const SCOPE_SPAN_FIELD = '_sentrySpan';
1198
-
1199
- /**
1200
- * Set the active span for a given scope.
1201
- * NOTE: This should NOT be used directly, but is only used internally by the trace methods.
1202
- */
1203
- function _setSpanForScope(scope, span) {
1204
- if (span) {
1205
- addNonEnumerableProperty(scope , SCOPE_SPAN_FIELD, span);
1206
- } else {
1207
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1208
- delete (scope )[SCOPE_SPAN_FIELD];
1209
- }
1210
- }
1211
-
1212
- /**
1213
- * Get the active span for a given scope.
1214
- * NOTE: This should NOT be used directly, but is only used internally by the trace methods.
1215
- */
1216
- function _getSpanForScope(scope) {
1217
- return scope[SCOPE_SPAN_FIELD];
1218
- }
1219
-
1220
- /**
1221
- * Generate a random, valid trace ID.
1222
- */
1223
- function generateTraceId() {
1224
- return uuid4();
1225
- }
1226
-
1227
- /**
1228
- * Generate a random, valid span ID.
1229
- */
1230
- function generateSpanId() {
1231
- return uuid4().substring(16);
1232
- }
1233
-
1234
- /**
1235
- * Default value for maximum number of breadcrumbs added to an event.
1236
- */
1237
- const DEFAULT_MAX_BREADCRUMBS = 100;
1238
-
1239
- /**
1240
- * A context to be used for capturing an event.
1241
- * This can either be a Scope, or a partial ScopeContext,
1242
- * or a callback that receives the current scope and returns a new scope to use.
1243
- */
1244
-
1245
- /**
1246
- * Holds additional event information.
1247
- */
1248
- class Scope {
1249
- /** Flag if notifying is happening. */
1250
-
1251
- /** Callback for client to receive scope changes. */
1252
-
1253
- /** Callback list that will be called during event processing. */
1254
-
1255
- /** Array of breadcrumbs. */
1256
-
1257
- /** User */
1258
-
1259
- /** Tags */
1260
-
1261
- /** Extra */
1262
-
1263
- /** Contexts */
1264
-
1265
- /** Attachments */
1266
-
1267
- /** Propagation Context for distributed tracing */
1268
-
1269
- /**
1270
- * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get
1271
- * sent to Sentry
1272
- */
1273
-
1274
- /** Fingerprint */
1275
-
1276
- /** Severity */
1277
-
1278
- /**
1279
- * Transaction Name
1280
- *
1281
- * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.
1282
- * It's purpose is to assign a transaction to the scope that's added to non-transaction events.
1283
- */
1284
-
1285
- /** Session */
1286
-
1287
- /** The client on this scope */
1288
-
1289
- /** Contains the last event id of a captured event. */
1290
-
1291
- // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
1292
-
1293
- constructor() {
1294
- this._notifyingListeners = false;
1295
- this._scopeListeners = [];
1296
- this._eventProcessors = [];
1297
- this._breadcrumbs = [];
1298
- this._attachments = [];
1299
- this._user = {};
1300
- this._tags = {};
1301
- this._extra = {};
1302
- this._contexts = {};
1303
- this._sdkProcessingMetadata = {};
1304
- this._propagationContext = {
1305
- traceId: generateTraceId(),
1306
- sampleRand: Math.random(),
1307
- };
1308
- }
1309
-
1310
- /**
1311
- * Clone all data from this scope into a new scope.
1312
- */
1313
- clone() {
1314
- const newScope = new Scope();
1315
- newScope._breadcrumbs = [...this._breadcrumbs];
1316
- newScope._tags = { ...this._tags };
1317
- newScope._extra = { ...this._extra };
1318
- newScope._contexts = { ...this._contexts };
1319
- if (this._contexts.flags) {
1320
- // We need to copy the `values` array so insertions on a cloned scope
1321
- // won't affect the original array.
1322
- newScope._contexts.flags = {
1323
- values: [...this._contexts.flags.values],
1324
- };
1325
- }
1326
-
1327
- newScope._user = this._user;
1328
- newScope._level = this._level;
1329
- newScope._session = this._session;
1330
- newScope._transactionName = this._transactionName;
1331
- newScope._fingerprint = this._fingerprint;
1332
- newScope._eventProcessors = [...this._eventProcessors];
1333
- newScope._attachments = [...this._attachments];
1334
- newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };
1335
- newScope._propagationContext = { ...this._propagationContext };
1336
- newScope._client = this._client;
1337
- newScope._lastEventId = this._lastEventId;
1338
-
1339
- _setSpanForScope(newScope, _getSpanForScope(this));
1340
-
1341
- return newScope;
1342
- }
1343
-
1344
- /**
1345
- * Update the client assigned to this scope.
1346
- * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,
1347
- * as well as manually created scopes.
1348
- */
1349
- setClient(client) {
1350
- this._client = client;
1351
- }
1352
-
1353
- /**
1354
- * Set the ID of the last captured error event.
1355
- * This is generally only captured on the isolation scope.
1356
- */
1357
- setLastEventId(lastEventId) {
1358
- this._lastEventId = lastEventId;
1359
- }
1360
-
1361
- /**
1362
- * Get the client assigned to this scope.
1363
- */
1364
- getClient() {
1365
- return this._client ;
1366
- }
1367
-
1368
- /**
1369
- * Get the ID of the last captured error event.
1370
- * This is generally only available on the isolation scope.
1371
- */
1372
- lastEventId() {
1373
- return this._lastEventId;
1374
- }
1375
-
1376
- /**
1377
- * @inheritDoc
1378
- */
1379
- addScopeListener(callback) {
1380
- this._scopeListeners.push(callback);
1381
- }
1382
-
1383
- /**
1384
- * Add an event processor that will be called before an event is sent.
1385
- */
1386
- addEventProcessor(callback) {
1387
- this._eventProcessors.push(callback);
1388
- return this;
1389
- }
1390
-
1391
- /**
1392
- * Set the user for this scope.
1393
- * Set to `null` to unset the user.
1394
- */
1395
- setUser(user) {
1396
- // If null is passed we want to unset everything, but still define keys,
1397
- // so that later down in the pipeline any existing values are cleared.
1398
- this._user = user || {
1399
- email: undefined,
1400
- id: undefined,
1401
- ip_address: undefined,
1402
- username: undefined,
1403
- };
1404
-
1405
- if (this._session) {
1406
- updateSession(this._session, { user });
1407
- }
1408
-
1409
- this._notifyScopeListeners();
1410
- return this;
1411
- }
1412
-
1413
- /**
1414
- * Get the user from this scope.
1415
- */
1416
- getUser() {
1417
- return this._user;
1418
- }
1419
-
1420
- /**
1421
- * Set an object that will be merged into existing tags on the scope,
1422
- * and will be sent as tags data with the event.
1423
- */
1424
- setTags(tags) {
1425
- this._tags = {
1426
- ...this._tags,
1427
- ...tags,
1428
- };
1429
- this._notifyScopeListeners();
1430
- return this;
1431
- }
1432
-
1433
- /**
1434
- * Set a single tag that will be sent as tags data with the event.
1435
- */
1436
- setTag(key, value) {
1437
- this._tags = { ...this._tags, [key]: value };
1438
- this._notifyScopeListeners();
1439
- return this;
1440
- }
1441
-
1442
- /**
1443
- * Set an object that will be merged into existing extra on the scope,
1444
- * and will be sent as extra data with the event.
1445
- */
1446
- setExtras(extras) {
1447
- this._extra = {
1448
- ...this._extra,
1449
- ...extras,
1450
- };
1451
- this._notifyScopeListeners();
1452
- return this;
1453
- }
1454
-
1455
- /**
1456
- * Set a single key:value extra entry that will be sent as extra data with the event.
1457
- */
1458
- setExtra(key, extra) {
1459
- this._extra = { ...this._extra, [key]: extra };
1460
- this._notifyScopeListeners();
1461
- return this;
1462
- }
1463
-
1464
- /**
1465
- * Sets the fingerprint on the scope to send with the events.
1466
- * @param {string[]} fingerprint Fingerprint to group events in Sentry.
1467
- */
1468
- setFingerprint(fingerprint) {
1469
- this._fingerprint = fingerprint;
1470
- this._notifyScopeListeners();
1471
- return this;
1472
- }
1473
-
1474
- /**
1475
- * Sets the level on the scope for future events.
1476
- */
1477
- setLevel(level) {
1478
- this._level = level;
1479
- this._notifyScopeListeners();
1480
- return this;
1481
- }
1482
-
1483
- /**
1484
- * Sets the transaction name on the scope so that the name of e.g. taken server route or
1485
- * the page location is attached to future events.
1486
- *
1487
- * IMPORTANT: Calling this function does NOT change the name of the currently active
1488
- * root span. If you want to change the name of the active root span, use
1489
- * `Sentry.updateSpanName(rootSpan, 'new name')` instead.
1490
- *
1491
- * By default, the SDK updates the scope's transaction name automatically on sensible
1492
- * occasions, such as a page navigation or when handling a new request on the server.
1493
- */
1494
- setTransactionName(name) {
1495
- this._transactionName = name;
1496
- this._notifyScopeListeners();
1497
- return this;
1498
- }
1499
-
1500
- /**
1501
- * Sets context data with the given name.
1502
- * Data passed as context will be normalized. You can also pass `null` to unset the context.
1503
- * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.
1504
- */
1505
- setContext(key, context) {
1506
- if (context === null) {
1507
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1508
- delete this._contexts[key];
1509
- } else {
1510
- this._contexts[key] = context;
1511
- }
1512
-
1513
- this._notifyScopeListeners();
1514
- return this;
1515
- }
1516
-
1517
- /**
1518
- * Set the session for the scope.
1519
- */
1520
- setSession(session) {
1521
- if (!session) {
1522
- delete this._session;
1523
- } else {
1524
- this._session = session;
1525
- }
1526
- this._notifyScopeListeners();
1527
- return this;
1528
- }
1529
-
1530
- /**
1531
- * Get the session from the scope.
1532
- */
1533
- getSession() {
1534
- return this._session;
1535
- }
1536
-
1537
- /**
1538
- * Updates the scope with provided data. Can work in three variations:
1539
- * - plain object containing updatable attributes
1540
- * - Scope instance that'll extract the attributes from
1541
- * - callback function that'll receive the current scope as an argument and allow for modifications
1542
- */
1543
- update(captureContext) {
1544
- if (!captureContext) {
1545
- return this;
1546
- }
1547
-
1548
- const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;
1549
-
1550
- const scopeInstance =
1551
- scopeToMerge instanceof Scope
1552
- ? scopeToMerge.getScopeData()
1553
- : isPlainObject(scopeToMerge)
1554
- ? (captureContext )
1555
- : undefined;
1556
-
1557
- const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};
1558
-
1559
- this._tags = { ...this._tags, ...tags };
1560
- this._extra = { ...this._extra, ...extra };
1561
- this._contexts = { ...this._contexts, ...contexts };
1562
-
1563
- if (user && Object.keys(user).length) {
1564
- this._user = user;
1565
- }
1566
-
1567
- if (level) {
1568
- this._level = level;
1569
- }
1570
-
1571
- if (fingerprint.length) {
1572
- this._fingerprint = fingerprint;
1573
- }
1574
-
1575
- if (propagationContext) {
1576
- this._propagationContext = propagationContext;
1577
- }
1578
-
1579
- return this;
1580
- }
1581
-
1582
- /**
1583
- * Clears the current scope and resets its properties.
1584
- * Note: The client will not be cleared.
1585
- */
1586
- clear() {
1587
- // client is not cleared here on purpose!
1588
- this._breadcrumbs = [];
1589
- this._tags = {};
1590
- this._extra = {};
1591
- this._user = {};
1592
- this._contexts = {};
1593
- this._level = undefined;
1594
- this._transactionName = undefined;
1595
- this._fingerprint = undefined;
1596
- this._session = undefined;
1597
- _setSpanForScope(this, undefined);
1598
- this._attachments = [];
1599
- this.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });
1600
-
1601
- this._notifyScopeListeners();
1602
- return this;
1603
- }
1604
-
1605
- /**
1606
- * Adds a breadcrumb to the scope.
1607
- * By default, the last 100 breadcrumbs are kept.
1608
- */
1609
- addBreadcrumb(breadcrumb, maxBreadcrumbs) {
1610
- const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;
1611
-
1612
- // No data has been changed, so don't notify scope listeners
1613
- if (maxCrumbs <= 0) {
1614
- return this;
1615
- }
1616
-
1617
- const mergedBreadcrumb = {
1618
- timestamp: dateTimestampInSeconds(),
1619
- ...breadcrumb,
1620
- // Breadcrumb messages can theoretically be infinitely large and they're held in memory so we truncate them not to leak (too much) memory
1621
- message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message,
1622
- };
1623
-
1624
- this._breadcrumbs.push(mergedBreadcrumb);
1625
- if (this._breadcrumbs.length > maxCrumbs) {
1626
- this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);
1627
- this._client?.recordDroppedEvent('buffer_overflow', 'log_item');
1628
- }
1629
-
1630
- this._notifyScopeListeners();
1631
-
1632
- return this;
1633
- }
1634
-
1635
- /**
1636
- * Get the last breadcrumb of the scope.
1637
- */
1638
- getLastBreadcrumb() {
1639
- return this._breadcrumbs[this._breadcrumbs.length - 1];
1640
- }
1641
-
1642
- /**
1643
- * Clear all breadcrumbs from the scope.
1644
- */
1645
- clearBreadcrumbs() {
1646
- this._breadcrumbs = [];
1647
- this._notifyScopeListeners();
1648
- return this;
1649
- }
1650
-
1651
- /**
1652
- * Add an attachment to the scope.
1653
- */
1654
- addAttachment(attachment) {
1655
- this._attachments.push(attachment);
1656
- return this;
1657
- }
1658
-
1659
- /**
1660
- * Clear all attachments from the scope.
1661
- */
1662
- clearAttachments() {
1663
- this._attachments = [];
1664
- return this;
1665
- }
1666
-
1667
- /**
1668
- * Get the data of this scope, which should be applied to an event during processing.
1669
- */
1670
- getScopeData() {
1671
- return {
1672
- breadcrumbs: this._breadcrumbs,
1673
- attachments: this._attachments,
1674
- contexts: this._contexts,
1675
- tags: this._tags,
1676
- extra: this._extra,
1677
- user: this._user,
1678
- level: this._level,
1679
- fingerprint: this._fingerprint || [],
1680
- eventProcessors: this._eventProcessors,
1681
- propagationContext: this._propagationContext,
1682
- sdkProcessingMetadata: this._sdkProcessingMetadata,
1683
- transactionName: this._transactionName,
1684
- span: _getSpanForScope(this),
1685
- };
1686
- }
1687
-
1688
- /**
1689
- * Add data which will be accessible during event processing but won't get sent to Sentry.
1690
- */
1691
- setSDKProcessingMetadata(newData) {
1692
- this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);
1693
- return this;
1694
- }
1695
-
1696
- /**
1697
- * Add propagation context to the scope, used for distributed tracing
1698
- */
1699
- setPropagationContext(context) {
1700
- this._propagationContext = context;
1701
- return this;
1702
- }
1703
-
1704
- /**
1705
- * Get propagation context from the scope, used for distributed tracing
1706
- */
1707
- getPropagationContext() {
1708
- return this._propagationContext;
1709
- }
1710
-
1711
- /**
1712
- * Capture an exception for this scope.
1713
- *
1714
- * @returns {string} The id of the captured Sentry event.
1715
- */
1716
- captureException(exception, hint) {
1717
- const eventId = hint?.event_id || uuid4();
1718
-
1719
- if (!this._client) {
1720
- logger.warn('No client configured on scope - will not capture exception!');
1721
- return eventId;
1722
- }
1723
-
1724
- const syntheticException = new Error('Sentry syntheticException');
1725
-
1726
- this._client.captureException(
1727
- exception,
1728
- {
1729
- originalException: exception,
1730
- syntheticException,
1731
- ...hint,
1732
- event_id: eventId,
1733
- },
1734
- this,
1735
- );
1736
-
1737
- return eventId;
1738
- }
1739
-
1740
- /**
1741
- * Capture a message for this scope.
1742
- *
1743
- * @returns {string} The id of the captured message.
1744
- */
1745
- captureMessage(message, level, hint) {
1746
- const eventId = hint?.event_id || uuid4();
1747
-
1748
- if (!this._client) {
1749
- logger.warn('No client configured on scope - will not capture message!');
1750
- return eventId;
1751
- }
1752
-
1753
- const syntheticException = new Error(message);
1754
-
1755
- this._client.captureMessage(
1756
- message,
1757
- level,
1758
- {
1759
- originalException: message,
1760
- syntheticException,
1761
- ...hint,
1762
- event_id: eventId,
1763
- },
1764
- this,
1765
- );
1766
-
1767
- return eventId;
1768
- }
1769
-
1770
- /**
1771
- * Capture a Sentry event for this scope.
1772
- *
1773
- * @returns {string} The id of the captured event.
1774
- */
1775
- captureEvent(event, hint) {
1776
- const eventId = hint?.event_id || uuid4();
1777
-
1778
- if (!this._client) {
1779
- logger.warn('No client configured on scope - will not capture event!');
1780
- return eventId;
1781
- }
1782
-
1783
- this._client.captureEvent(event, { ...hint, event_id: eventId }, this);
1784
-
1785
- return eventId;
1786
- }
1787
-
1788
- /**
1789
- * This will be called on every set call.
1790
- */
1791
- _notifyScopeListeners() {
1792
- // We need this check for this._notifyingListeners to be able to work on scope during updates
1793
- // If this check is not here we'll produce endless recursion when something is done with the scope
1794
- // during the callback.
1795
- if (!this._notifyingListeners) {
1796
- this._notifyingListeners = true;
1797
- this._scopeListeners.forEach(callback => {
1798
- callback(this);
1799
- });
1800
- this._notifyingListeners = false;
1801
- }
1802
- }
1803
- }
1804
-
1805
- /** Get the default current scope. */
1806
- function getDefaultCurrentScope() {
1807
- return getGlobalSingleton('defaultCurrentScope', () => new Scope());
1808
- }
1809
-
1810
- /** Get the default isolation scope. */
1811
- function getDefaultIsolationScope() {
1812
- return getGlobalSingleton('defaultIsolationScope', () => new Scope());
1813
- }
1814
-
1815
- /**
1816
- * This is an object that holds a stack of scopes.
1817
- */
1818
- class AsyncContextStack {
1819
-
1820
- constructor(scope, isolationScope) {
1821
- let assignedScope;
1822
- if (!scope) {
1823
- assignedScope = new Scope();
1824
- } else {
1825
- assignedScope = scope;
1826
- }
1827
-
1828
- let assignedIsolationScope;
1829
- if (!isolationScope) {
1830
- assignedIsolationScope = new Scope();
1831
- } else {
1832
- assignedIsolationScope = isolationScope;
1833
- }
1834
-
1835
- // scope stack for domains or the process
1836
- this._stack = [{ scope: assignedScope }];
1837
- this._isolationScope = assignedIsolationScope;
1838
- }
1839
-
1840
- /**
1841
- * Fork a scope for the stack.
1842
- */
1843
- withScope(callback) {
1844
- const scope = this._pushScope();
1845
-
1846
- let maybePromiseResult;
1847
- try {
1848
- maybePromiseResult = callback(scope);
1849
- } catch (e) {
1850
- this._popScope();
1851
- throw e;
1852
- }
1853
-
1854
- if (isThenable(maybePromiseResult)) {
1855
- // @ts-expect-error - isThenable returns the wrong type
1856
- return maybePromiseResult.then(
1857
- res => {
1858
- this._popScope();
1859
- return res;
1860
- },
1861
- e => {
1862
- this._popScope();
1863
- throw e;
1864
- },
1865
- );
1866
- }
1867
-
1868
- this._popScope();
1869
- return maybePromiseResult;
1870
- }
1871
-
1872
- /**
1873
- * Get the client of the stack.
1874
- */
1875
- getClient() {
1876
- return this.getStackTop().client ;
1877
- }
1878
-
1879
- /**
1880
- * Returns the scope of the top stack.
1881
- */
1882
- getScope() {
1883
- return this.getStackTop().scope;
1884
- }
1885
-
1886
- /**
1887
- * Get the isolation scope for the stack.
1888
- */
1889
- getIsolationScope() {
1890
- return this._isolationScope;
1891
- }
1892
-
1893
- /**
1894
- * Returns the topmost scope layer in the order domain > local > process.
1895
- */
1896
- getStackTop() {
1897
- return this._stack[this._stack.length - 1] ;
1898
- }
1899
-
1900
- /**
1901
- * Push a scope to the stack.
1902
- */
1903
- _pushScope() {
1904
- // We want to clone the content of prev scope
1905
- const scope = this.getScope().clone();
1906
- this._stack.push({
1907
- client: this.getClient(),
1908
- scope,
1909
- });
1910
- return scope;
1911
- }
1912
-
1913
- /**
1914
- * Pop a scope from the stack.
1915
- */
1916
- _popScope() {
1917
- if (this._stack.length <= 1) return false;
1918
- return !!this._stack.pop();
1919
- }
1920
- }
1921
-
1922
- /**
1923
- * Get the global async context stack.
1924
- * This will be removed during the v8 cycle and is only here to make migration easier.
1925
- */
1926
- function getAsyncContextStack() {
1927
- const registry = getMainCarrier();
1928
- const sentry = getSentryCarrier(registry);
1929
-
1930
- return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));
1931
- }
1932
-
1933
- function withScope$1(callback) {
1934
- return getAsyncContextStack().withScope(callback);
1935
- }
1936
-
1937
- function withSetScope(scope, callback) {
1938
- const stack = getAsyncContextStack() ;
1939
- return stack.withScope(() => {
1940
- stack.getStackTop().scope = scope;
1941
- return callback(scope);
1942
- });
1943
- }
1944
-
1945
- function withIsolationScope(callback) {
1946
- return getAsyncContextStack().withScope(() => {
1947
- return callback(getAsyncContextStack().getIsolationScope());
1948
- });
1949
- }
1950
-
1951
- /**
1952
- * Get the stack-based async context strategy.
1953
- */
1954
- function getStackAsyncContextStrategy() {
1955
- return {
1956
- withIsolationScope,
1957
- withScope: withScope$1,
1958
- withSetScope,
1959
- withSetIsolationScope: (_isolationScope, callback) => {
1960
- return withIsolationScope(callback);
1961
- },
1962
- getCurrentScope: () => getAsyncContextStack().getScope(),
1963
- getIsolationScope: () => getAsyncContextStack().getIsolationScope(),
1964
- };
1965
- }
1966
-
1967
- /**
1968
- * Get the current async context strategy.
1969
- * If none has been setup, the default will be used.
1970
- */
1971
- function getAsyncContextStrategy(carrier) {
1972
- const sentry = getSentryCarrier(carrier);
1973
-
1974
- if (sentry.acs) {
1975
- return sentry.acs;
1976
- }
1977
-
1978
- // Otherwise, use the default one (stack)
1979
- return getStackAsyncContextStrategy();
1980
- }
1981
-
1982
- /**
1983
- * Get the currently active scope.
1984
- */
1985
- function getCurrentScope() {
1986
- const carrier = getMainCarrier();
1987
- const acs = getAsyncContextStrategy(carrier);
1988
- return acs.getCurrentScope();
1989
- }
1990
-
1991
- /**
1992
- * Get the currently active isolation scope.
1993
- * The isolation scope is active for the current execution context.
1994
- */
1995
- function getIsolationScope() {
1996
- const carrier = getMainCarrier();
1997
- const acs = getAsyncContextStrategy(carrier);
1998
- return acs.getIsolationScope();
1999
- }
2000
-
2001
- /**
2002
- * Get the global scope.
2003
- * This scope is applied to _all_ events.
2004
- */
2005
- function getGlobalScope() {
2006
- return getGlobalSingleton('globalScope', () => new Scope());
2007
- }
2008
-
2009
- /**
2010
- * Creates a new scope with and executes the given operation within.
2011
- * The scope is automatically removed once the operation
2012
- * finishes or throws.
2013
- */
2014
-
2015
- /**
2016
- * Either creates a new active scope, or sets the given scope as active scope in the given callback.
2017
- */
2018
- function withScope(
2019
- ...rest
2020
- ) {
2021
- const carrier = getMainCarrier();
2022
- const acs = getAsyncContextStrategy(carrier);
2023
-
2024
- // If a scope is defined, we want to make this the active scope instead of the default one
2025
- if (rest.length === 2) {
2026
- const [scope, callback] = rest;
2027
-
2028
- if (!scope) {
2029
- return acs.withScope(callback);
2030
- }
2031
-
2032
- return acs.withSetScope(scope, callback);
2033
- }
2034
-
2035
- return acs.withScope(rest[0]);
2036
- }
2037
-
2038
- /**
2039
- * Get the currently active client.
2040
- */
2041
- function getClient() {
2042
- return getCurrentScope().getClient();
2043
- }
2044
-
2045
- /**
2046
- * Get a trace context for the given scope.
2047
- */
2048
- function getTraceContextFromScope(scope) {
2049
- const propagationContext = scope.getPropagationContext();
2050
-
2051
- const { traceId, parentSpanId, propagationSpanId } = propagationContext;
2052
-
2053
- const traceContext = {
2054
- trace_id: traceId,
2055
- span_id: propagationSpanId || generateSpanId(),
2056
- };
2057
-
2058
- if (parentSpanId) {
2059
- traceContext.parent_span_id = parentSpanId;
2060
- }
2061
-
2062
- return traceContext;
2063
- }
2064
-
2065
- /**
2066
- * Use this attribute to represent the source of a span.
2067
- * Should be one of: custom, url, route, view, component, task, unknown
2068
- *
2069
- */
2070
- const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';
2071
-
2072
- /**
2073
- * Attributes that holds the sample rate that was locally applied to a span.
2074
- * If this attribute is not defined, it means that the span inherited a sampling decision.
2075
- *
2076
- * NOTE: Is only defined on root spans.
2077
- */
2078
- const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';
2079
-
2080
- /**
2081
- * Attribute holding the sample rate of the previous trace.
2082
- * This is used to sample consistently across subsequent traces in the browser SDK.
2083
- *
2084
- * Note: Only defined on root spans, if opted into consistent sampling
2085
- */
2086
- const SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = 'sentry.previous_trace_sample_rate';
2087
-
2088
- /**
2089
- * Use this attribute to represent the operation of a span.
2090
- */
2091
- const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';
2092
-
2093
- /**
2094
- * Use this attribute to represent the origin of a span.
2095
- */
2096
- const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';
2097
-
2098
- /**
2099
- * The id of the profile that this span occurred in.
2100
- */
2101
- const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';
2102
-
2103
- const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';
2104
-
2105
- const SPAN_STATUS_UNSET = 0;
2106
- const SPAN_STATUS_OK = 1;
2107
-
2108
- const SCOPE_ON_START_SPAN_FIELD = '_sentryScope';
2109
- const ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';
2110
-
2111
- /**
2112
- * Grabs the scope and isolation scope off a span that were active when the span was started.
2113
- */
2114
- function getCapturedScopesOnSpan(span) {
2115
- return {
2116
- scope: (span )[SCOPE_ON_START_SPAN_FIELD],
2117
- isolationScope: (span )[ISOLATION_SCOPE_ON_START_SPAN_FIELD],
2118
- };
2119
- }
2120
-
2121
- const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';
2122
-
2123
- const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;
2124
-
2125
- /**
2126
- * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values
2127
- * from it.
2128
- *
2129
- * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.
2130
- * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.
2131
- */
2132
- function baggageHeaderToDynamicSamplingContext(
2133
- // Very liberal definition of what any incoming header might look like
2134
- baggageHeader,
2135
- ) {
2136
- const baggageObject = parseBaggageHeader(baggageHeader);
2137
-
2138
- if (!baggageObject) {
2139
- return undefined;
2140
- }
2141
-
2142
- // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object.
2143
- const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {
2144
- if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {
2145
- const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);
2146
- acc[nonPrefixedKey] = value;
2147
- }
2148
- return acc;
2149
- }, {});
2150
-
2151
- // Only return a dynamic sampling context object if there are keys in it.
2152
- // A keyless object means there were no sentry values on the header, which means that there is no DSC.
2153
- if (Object.keys(dynamicSamplingContext).length > 0) {
2154
- return dynamicSamplingContext ;
2155
- } else {
2156
- return undefined;
2157
- }
2158
- }
2159
-
2160
- /**
2161
- * Take a baggage header and parse it into an object.
2162
- */
2163
- function parseBaggageHeader(
2164
- baggageHeader,
2165
- ) {
2166
- if (!baggageHeader || (!isString(baggageHeader) && !Array.isArray(baggageHeader))) {
2167
- return undefined;
2168
- }
2169
-
2170
- if (Array.isArray(baggageHeader)) {
2171
- // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it
2172
- return baggageHeader.reduce((acc, curr) => {
2173
- const currBaggageObject = baggageHeaderToObject(curr);
2174
- Object.entries(currBaggageObject).forEach(([key, value]) => {
2175
- acc[key] = value;
2176
- });
2177
- return acc;
2178
- }, {});
2179
- }
2180
-
2181
- return baggageHeaderToObject(baggageHeader);
2182
- }
2183
-
2184
- /**
2185
- * Will parse a baggage header, which is a simple key-value map, into a flat object.
2186
- *
2187
- * @param baggageHeader The baggage header to parse.
2188
- * @returns a flat object containing all the key-value pairs from `baggageHeader`.
2189
- */
2190
- function baggageHeaderToObject(baggageHeader) {
2191
- return baggageHeader
2192
- .split(',')
2193
- .map(baggageEntry =>
2194
- baggageEntry.split('=').map(keyOrValue => {
2195
- try {
2196
- return decodeURIComponent(keyOrValue.trim());
2197
- } catch {
2198
- // We ignore errors here, e.g. if the value cannot be URL decoded.
2199
- // This will then be skipped in the next step
2200
- return;
2201
- }
2202
- }),
2203
- )
2204
- .reduce((acc, [key, value]) => {
2205
- if (key && value) {
2206
- acc[key] = value;
2207
- }
2208
- return acc;
2209
- }, {});
2210
- }
2211
-
2212
- const TRACE_FLAG_SAMPLED = 0x1;
2213
-
2214
- let hasShownSpanDropWarning = false;
2215
-
2216
- /**
2217
- * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.
2218
- */
2219
- function spanToTraceContext(span) {
2220
- const { spanId, traceId: trace_id, isRemote } = span.spanContext();
2221
-
2222
- // If the span is remote, we use a random/virtual span as span_id to the trace context,
2223
- // and the remote span as parent_span_id
2224
- const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;
2225
- const scope = getCapturedScopesOnSpan(span).scope;
2226
-
2227
- const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;
2228
-
2229
- return {
2230
- parent_span_id,
2231
- span_id,
2232
- trace_id,
2233
- };
2234
- }
2235
-
2236
- /**
2237
- * Converts the span links array to a flattened version to be sent within an envelope.
2238
- *
2239
- * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.
2240
- */
2241
- function convertSpanLinksForEnvelope(links) {
2242
- if (links && links.length > 0) {
2243
- return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({
2244
- span_id: spanId,
2245
- trace_id: traceId,
2246
- sampled: traceFlags === TRACE_FLAG_SAMPLED,
2247
- attributes,
2248
- ...restContext,
2249
- }));
2250
- } else {
2251
- return undefined;
2252
- }
2253
- }
2254
-
2255
- /**
2256
- * Convert a span time input into a timestamp in seconds.
2257
- */
2258
- function spanTimeInputToSeconds(input) {
2259
- if (typeof input === 'number') {
2260
- return ensureTimestampInSeconds(input);
2261
- }
2262
-
2263
- if (Array.isArray(input)) {
2264
- // See {@link HrTime} for the array-based time format
2265
- return input[0] + input[1] / 1e9;
2266
- }
2267
-
2268
- if (input instanceof Date) {
2269
- return ensureTimestampInSeconds(input.getTime());
2270
- }
2271
-
2272
- return timestampInSeconds();
2273
- }
2274
-
2275
- /**
2276
- * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.
2277
- */
2278
- function ensureTimestampInSeconds(timestamp) {
2279
- const isMs = timestamp > 9999999999;
2280
- return isMs ? timestamp / 1000 : timestamp;
2281
- }
2282
-
2283
- /**
2284
- * Convert a span to a JSON representation.
2285
- */
2286
- // Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).
2287
- // This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.
2288
- // And `spanToJSON` needs the Span class from `span.ts` to check here.
2289
- function spanToJSON(span) {
2290
- if (spanIsSentrySpan(span)) {
2291
- return span.getSpanJSON();
2292
- }
2293
-
2294
- const { spanId: span_id, traceId: trace_id } = span.spanContext();
2295
-
2296
- // Handle a span from @opentelemetry/sdk-base-trace's `Span` class
2297
- if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {
2298
- const { attributes, startTime, name, endTime, status, links } = span;
2299
-
2300
- // In preparation for the next major of OpenTelemetry, we want to support
2301
- // looking up the parent span id according to the new API
2302
- // In OTel v1, the parent span id is accessed as `parentSpanId`
2303
- // In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext`
2304
- const parentSpanId =
2305
- 'parentSpanId' in span
2306
- ? span.parentSpanId
2307
- : 'parentSpanContext' in span
2308
- ? (span.parentSpanContext )?.spanId
2309
- : undefined;
2310
-
2311
- return {
2312
- span_id,
2313
- trace_id,
2314
- data: attributes,
2315
- description: name,
2316
- parent_span_id: parentSpanId,
2317
- start_timestamp: spanTimeInputToSeconds(startTime),
2318
- // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
2319
- timestamp: spanTimeInputToSeconds(endTime) || undefined,
2320
- status: getStatusMessage(status),
2321
- op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],
2322
- origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ,
2323
- links: convertSpanLinksForEnvelope(links),
2324
- };
2325
- }
2326
-
2327
- // Finally, at least we have `spanContext()`....
2328
- // This should not actually happen in reality, but we need to handle it for type safety.
2329
- return {
2330
- span_id,
2331
- trace_id,
2332
- start_timestamp: 0,
2333
- data: {},
2334
- };
2335
- }
2336
-
2337
- function spanIsOpenTelemetrySdkTraceBaseSpan(span) {
2338
- const castSpan = span ;
2339
- return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;
2340
- }
2341
-
2342
- /** Exported only for tests. */
2343
-
2344
- /**
2345
- * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.
2346
- * :( So instead we approximate this by checking if it has the `getSpanJSON` method.
2347
- */
2348
- function spanIsSentrySpan(span) {
2349
- return typeof (span ).getSpanJSON === 'function';
2350
- }
2351
-
2352
- /**
2353
- * Returns true if a span is sampled.
2354
- * In most cases, you should just use `span.isRecording()` instead.
2355
- * However, this has a slightly different semantic, as it also returns false if the span is finished.
2356
- * So in the case where this distinction is important, use this method.
2357
- */
2358
- function spanIsSampled(span) {
2359
- // We align our trace flags with the ones OpenTelemetry use
2360
- // So we also check for sampled the same way they do.
2361
- const { traceFlags } = span.spanContext();
2362
- return traceFlags === TRACE_FLAG_SAMPLED;
2363
- }
2364
-
2365
- /** Get the status message to use for a JSON representation of a span. */
2366
- function getStatusMessage(status) {
2367
- if (!status || status.code === SPAN_STATUS_UNSET) {
2368
- return undefined;
2369
- }
2370
-
2371
- if (status.code === SPAN_STATUS_OK) {
2372
- return 'ok';
2373
- }
2374
-
2375
- return status.message || 'unknown_error';
2376
- }
2377
- const ROOT_SPAN_FIELD = '_sentryRootSpan';
2378
-
2379
- /**
2380
- * Returns the root span of a given span.
2381
- */
2382
- function getRootSpan(span) {
2383
- return span[ROOT_SPAN_FIELD] || span;
2384
- }
2385
-
2386
- /**
2387
- * Logs a warning once if `beforeSendSpan` is used to drop spans.
2388
- */
2389
- function showSpanDropWarning() {
2390
- if (!hasShownSpanDropWarning) {
2391
- consoleSandbox(() => {
2392
- // eslint-disable-next-line no-console
2393
- console.warn(
2394
- '[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.',
2395
- );
2396
- });
2397
- hasShownSpanDropWarning = true;
2398
- }
2399
- }
2400
-
2401
- const STACKTRACE_FRAME_LIMIT = 50;
2402
- const UNKNOWN_FUNCTION = '?';
2403
- // Used to sanitize webpack (error: *) wrapped stack errors
2404
- const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
2405
- const STRIP_FRAME_REGEXP = /captureMessage|captureException/;
2406
-
2407
- /**
2408
- * Creates a stack parser with the supplied line parsers
2409
- *
2410
- * StackFrames are returned in the correct order for Sentry Exception
2411
- * frames and with Sentry SDK internal frames removed from the top and bottom
2412
- *
2413
- */
2414
- function createStackParser(...parsers) {
2415
- const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);
2416
-
2417
- return (stack, skipFirstLines = 0, framesToPop = 0) => {
2418
- const frames = [];
2419
- const lines = stack.split('\n');
2420
-
2421
- for (let i = skipFirstLines; i < lines.length; i++) {
2422
- const line = lines[i] ;
2423
- // Ignore lines over 1kb as they are unlikely to be stack frames.
2424
- // Many of the regular expressions use backtracking which results in run time that increases exponentially with
2425
- // input size. Huge strings can result in hangs/Denial of Service:
2426
- // https://github.com/getsentry/sentry-javascript/issues/2286
2427
- if (line.length > 1024) {
2428
- continue;
2429
- }
2430
-
2431
- // https://github.com/getsentry/sentry-javascript/issues/5459
2432
- // Remove webpack (error: *) wrappers
2433
- const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
2434
-
2435
- // https://github.com/getsentry/sentry-javascript/issues/7813
2436
- // Skip Error: lines
2437
- if (cleanedLine.match(/\S*Error: /)) {
2438
- continue;
2439
- }
2440
-
2441
- for (const parser of sortedParsers) {
2442
- const frame = parser(cleanedLine);
2443
-
2444
- if (frame) {
2445
- frames.push(frame);
2446
- break;
2447
- }
2448
- }
2449
-
2450
- if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {
2451
- break;
2452
- }
2453
- }
2454
-
2455
- return stripSentryFramesAndReverse(frames.slice(framesToPop));
2456
- };
2457
- }
2458
-
2459
- /**
2460
- * Gets a stack parser implementation from Options.stackParser
2461
- * @see Options
2462
- *
2463
- * If options contains an array of line parsers, it is converted into a parser
2464
- */
2465
- function stackParserFromStackParserOptions(stackParser) {
2466
- if (Array.isArray(stackParser)) {
2467
- return createStackParser(...stackParser);
2468
- }
2469
- return stackParser;
2470
- }
2471
-
2472
- /**
2473
- * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.
2474
- * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the
2475
- * function that caused the crash is the last frame in the array.
2476
- * @hidden
2477
- */
2478
- function stripSentryFramesAndReverse(stack) {
2479
- if (!stack.length) {
2480
- return [];
2481
- }
2482
-
2483
- const localStack = Array.from(stack);
2484
-
2485
- // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)
2486
- if (/sentryWrapped/.test(getLastStackFrame(localStack).function || '')) {
2487
- localStack.pop();
2488
- }
2489
-
2490
- // Reversing in the middle of the procedure allows us to just pop the values off the stack
2491
- localStack.reverse();
2492
-
2493
- // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)
2494
- if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {
2495
- localStack.pop();
2496
-
2497
- // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`
2498
- // is produced within the scope itself, making it:
2499
- //
2500
- // Sentry.captureException()
2501
- // scope.captureException()
2502
- //
2503
- // instead of just the top `Sentry` call itself.
2504
- // This forces us to possibly strip an additional frame in the exact same was as above.
2505
- if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {
2506
- localStack.pop();
2507
- }
2508
- }
2509
-
2510
- return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({
2511
- ...frame,
2512
- filename: frame.filename || getLastStackFrame(localStack).filename,
2513
- function: frame.function || UNKNOWN_FUNCTION,
2514
- }));
2515
- }
2516
-
2517
- function getLastStackFrame(arr) {
2518
- return arr[arr.length - 1] || {};
2519
- }
2520
-
2521
- const defaultFunctionName = '<anonymous>';
2522
-
2523
- /**
2524
- * Safely extract function name from itself
2525
- */
2526
- function getFunctionName(fn) {
2527
- try {
2528
- if (!fn || typeof fn !== 'function') {
2529
- return defaultFunctionName;
2530
- }
2531
- return fn.name || defaultFunctionName;
2532
- } catch (e) {
2533
- // Just accessing custom props in some Selenium environments
2534
- // can cause a "Permission denied" exception (see raven-js#495).
2535
- return defaultFunctionName;
2536
- }
2537
- }
2538
-
2539
- /**
2540
- * Get's stack frames from an event without needing to check for undefined properties.
2541
- */
2542
- function getFramesFromEvent(event) {
2543
- const exception = event.exception;
2544
-
2545
- if (exception) {
2546
- const frames = [];
2547
- try {
2548
- // @ts-expect-error Object could be undefined
2549
- exception.values.forEach(value => {
2550
- // @ts-expect-error Value could be undefined
2551
- if (value.stacktrace.frames) {
2552
- // @ts-expect-error Value could be undefined
2553
- frames.push(...value.stacktrace.frames);
2554
- }
2555
- });
2556
- return frames;
2557
- } catch (_oO) {
2558
- return undefined;
2559
- }
2560
- }
2561
- return undefined;
2562
- }
2563
-
2564
- // Treeshakable guard to remove all code related to tracing
2565
-
2566
- /**
2567
- * Determines if span recording is currently enabled.
2568
- *
2569
- * Spans are recorded when at least one of `tracesSampleRate` and `tracesSampler`
2570
- * is defined in the SDK config. This function does not make any assumption about
2571
- * sampling decisions, it only checks if the SDK is configured to record spans.
2572
- *
2573
- * Important: This function only determines if span recording is enabled. Trace
2574
- * continuation and propagation is separately controlled and not covered by this function.
2575
- * If this function returns `false`, traces can still be propagated (which is what
2576
- * we refer to by "Tracing without Performance")
2577
- * @see https://develop.sentry.dev/sdk/telemetry/traces/tracing-without-performance/
2578
- *
2579
- * @param maybeOptions An SDK options object to be passed to this function.
2580
- * If this option is not provided, the function will use the current client's options.
2581
- */
2582
- function hasSpansEnabled(
2583
- maybeOptions,
2584
- ) {
2585
- if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {
2586
- return false;
2587
- }
2588
-
2589
- const options = maybeOptions || getClient()?.getOptions();
2590
- return (
2591
- !!options &&
2592
- // Note: This check is `!= null`, meaning "nullish". `0` is not "nullish", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)
2593
- (options.tracesSampleRate != null || !!options.tracesSampler)
2594
- );
2595
- }
2596
-
2597
- const DEFAULT_ENVIRONMENT = 'production';
2598
-
2599
- /** Regular expression used to extract org ID from a DSN host. */
2600
- const ORG_ID_REGEX = /^o(\d+)\./;
2601
-
2602
- /** Regular expression used to parse a Dsn. */
2603
- const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
2604
-
2605
- function isValidProtocol(protocol) {
2606
- return protocol === 'http' || protocol === 'https';
2607
- }
2608
-
2609
- /**
2610
- * Renders the string representation of this Dsn.
2611
- *
2612
- * By default, this will render the public representation without the password
2613
- * component. To get the deprecated private representation, set `withPassword`
2614
- * to true.
2615
- *
2616
- * @param withPassword When set to true, the password will be included.
2617
- */
2618
- function dsnToString(dsn, withPassword = false) {
2619
- const { host, path, pass, port, projectId, protocol, publicKey } = dsn;
2620
- return (
2621
- `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +
2622
- `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`
2623
- );
2624
- }
2625
-
2626
- /**
2627
- * Parses a Dsn from a given string.
2628
- *
2629
- * @param str A Dsn as string
2630
- * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string
2631
- */
2632
- function dsnFromString(str) {
2633
- const match = DSN_REGEX.exec(str);
2634
-
2635
- if (!match) {
2636
- // This should be logged to the console
2637
- consoleSandbox(() => {
2638
- // eslint-disable-next-line no-console
2639
- console.error(`Invalid Sentry Dsn: ${str}`);
2640
- });
2641
- return undefined;
2642
- }
2643
-
2644
- const [protocol, publicKey, pass = '', host = '', port = '', lastPath = ''] = match.slice(1);
2645
- let path = '';
2646
- let projectId = lastPath;
2647
-
2648
- const split = projectId.split('/');
2649
- if (split.length > 1) {
2650
- path = split.slice(0, -1).join('/');
2651
- projectId = split.pop() ;
2652
- }
2653
-
2654
- if (projectId) {
2655
- const projectMatch = projectId.match(/^\d+/);
2656
- if (projectMatch) {
2657
- projectId = projectMatch[0];
2658
- }
2659
- }
2660
-
2661
- return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });
2662
- }
2663
-
2664
- function dsnFromComponents(components) {
2665
- return {
2666
- protocol: components.protocol,
2667
- publicKey: components.publicKey || '',
2668
- pass: components.pass || '',
2669
- host: components.host,
2670
- port: components.port || '',
2671
- path: components.path || '',
2672
- projectId: components.projectId,
2673
- };
2674
- }
2675
-
2676
- function validateDsn(dsn) {
2677
- if (!DEBUG_BUILD) {
2678
- return true;
2679
- }
2680
-
2681
- const { port, projectId, protocol } = dsn;
2682
-
2683
- const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];
2684
- const hasMissingRequiredComponent = requiredComponents.find(component => {
2685
- if (!dsn[component]) {
2686
- logger.error(`Invalid Sentry Dsn: ${component} missing`);
2687
- return true;
2688
- }
2689
- return false;
2690
- });
2691
-
2692
- if (hasMissingRequiredComponent) {
2693
- return false;
2694
- }
2695
-
2696
- if (!projectId.match(/^\d+$/)) {
2697
- logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
2698
- return false;
2699
- }
2700
-
2701
- if (!isValidProtocol(protocol)) {
2702
- logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
2703
- return false;
2704
- }
2705
-
2706
- if (port && isNaN(parseInt(port, 10))) {
2707
- logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);
2708
- return false;
2709
- }
2710
-
2711
- return true;
2712
- }
2713
-
2714
- /**
2715
- * Extract the org ID from a DSN host.
2716
- *
2717
- * @param host The host from a DSN
2718
- * @returns The org ID if found, undefined otherwise
2719
- */
2720
- function extractOrgIdFromDsnHost(host) {
2721
- const match = host.match(ORG_ID_REGEX);
2722
-
2723
- return match?.[1];
2724
- }
2725
-
2726
- /**
2727
- * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.
2728
- * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source
2729
- */
2730
- function makeDsn(from) {
2731
- const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);
2732
- if (!components || !validateDsn(components)) {
2733
- return undefined;
2734
- }
2735
- return components;
2736
- }
2737
-
2738
- /**
2739
- * If you change this value, also update the terser plugin config to
2740
- * avoid minification of the object property!
2741
- */
2742
- const FROZEN_DSC_FIELD = '_frozenDsc';
2743
-
2744
- /**
2745
- * Creates a dynamic sampling context from a client.
2746
- *
2747
- * Dispatches the `createDsc` lifecycle hook as a side effect.
2748
- */
2749
- function getDynamicSamplingContextFromClient(trace_id, client) {
2750
- const options = client.getOptions();
2751
-
2752
- const { publicKey: public_key, host } = client.getDsn() || {};
2753
-
2754
- let org_id;
2755
- if (options.orgId) {
2756
- org_id = String(options.orgId);
2757
- } else if (host) {
2758
- org_id = extractOrgIdFromDsnHost(host);
2759
- }
2760
-
2761
- // Instead of conditionally adding non-undefined values, we add them and then remove them if needed
2762
- // otherwise, the order of baggage entries changes, which "breaks" a bunch of tests etc.
2763
- const dsc = {
2764
- environment: options.environment || DEFAULT_ENVIRONMENT,
2765
- release: options.release,
2766
- public_key,
2767
- trace_id,
2768
- org_id,
2769
- };
2770
-
2771
- client.emit('createDsc', dsc);
2772
-
2773
- return dsc;
2774
- }
2775
-
2776
- /**
2777
- * Get the dynamic sampling context for the currently active scopes.
2778
- */
2779
- function getDynamicSamplingContextFromScope(client, scope) {
2780
- const propagationContext = scope.getPropagationContext();
2781
- return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);
2782
- }
2783
-
2784
- /**
2785
- * Creates a dynamic sampling context from a span (and client and scope)
2786
- *
2787
- * @param span the span from which a few values like the root span name and sample rate are extracted.
2788
- *
2789
- * @returns a dynamic sampling context
2790
- */
2791
- function getDynamicSamplingContextFromSpan(span) {
2792
- const client = getClient();
2793
- if (!client) {
2794
- return {};
2795
- }
2796
-
2797
- const rootSpan = getRootSpan(span);
2798
- const rootSpanJson = spanToJSON(rootSpan);
2799
- const rootSpanAttributes = rootSpanJson.data;
2800
- const traceState = rootSpan.spanContext().traceState;
2801
-
2802
- // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.
2803
- // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.
2804
- const rootSpanSampleRate =
2805
- traceState?.get('sentry.sample_rate') ??
2806
- rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ??
2807
- rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];
2808
-
2809
- function applyLocalSampleRateToDsc(dsc) {
2810
- if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {
2811
- dsc.sample_rate = `${rootSpanSampleRate}`;
2812
- }
2813
- return dsc;
2814
- }
2815
-
2816
- // For core implementation, we freeze the DSC onto the span as a non-enumerable property
2817
- const frozenDsc = (rootSpan )[FROZEN_DSC_FIELD];
2818
- if (frozenDsc) {
2819
- return applyLocalSampleRateToDsc(frozenDsc);
2820
- }
2821
-
2822
- // For OpenTelemetry, we freeze the DSC on the trace state
2823
- const traceStateDsc = traceState?.get('sentry.dsc');
2824
-
2825
- // If the span has a DSC, we want it to take precedence
2826
- const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);
2827
-
2828
- if (dscOnTraceState) {
2829
- return applyLocalSampleRateToDsc(dscOnTraceState);
2830
- }
2831
-
2832
- // Else, we generate it from the span
2833
- const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);
2834
-
2835
- // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
2836
- const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
2837
-
2838
- // after JSON conversion, txn.name becomes jsonSpan.description
2839
- const name = rootSpanJson.description;
2840
- if (source !== 'url' && name) {
2841
- dsc.transaction = name;
2842
- }
2843
-
2844
- // How can we even land here with hasSpansEnabled() returning false?
2845
- // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests
2846
- // So we end up with an active span that is not sampled (neither positively nor negatively)
2847
- if (hasSpansEnabled()) {
2848
- dsc.sampled = String(spanIsSampled(rootSpan));
2849
- dsc.sample_rand =
2850
- // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans
2851
- // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span
2852
- traceState?.get('sentry.sample_rand') ??
2853
- // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)
2854
- getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();
2855
- }
2856
-
2857
- applyLocalSampleRateToDsc(dsc);
2858
-
2859
- client.emit('createDsc', dsc, rootSpan);
2860
-
2861
- return dsc;
2862
- }
2863
-
2864
- /**
2865
- * Recursively normalizes the given object.
2866
- *
2867
- * - Creates a copy to prevent original input mutation
2868
- * - Skips non-enumerable properties
2869
- * - When stringifying, calls `toJSON` if implemented
2870
- * - Removes circular references
2871
- * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format
2872
- * - Translates known global objects/classes to a string representations
2873
- * - Takes care of `Error` object serialization
2874
- * - Optionally limits depth of final output
2875
- * - Optionally limits number of properties/elements included in any single object/array
2876
- *
2877
- * @param input The object to be normalized.
2878
- * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)
2879
- * @param maxProperties The max number of elements or properties to be included in any single array or
2880
- * object in the normalized output.
2881
- * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization.
2882
- */
2883
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2884
- function normalize(input, depth = 100, maxProperties = +Infinity) {
2885
- try {
2886
- // since we're at the outermost level, we don't provide a key
2887
- return visit('', input, depth, maxProperties);
2888
- } catch (err) {
2889
- return { ERROR: `**non-serializable** (${err})` };
2890
- }
2891
- }
2892
-
2893
- /** JSDoc */
2894
- function normalizeToSize(
2895
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2896
- object,
2897
- // Default Node.js REPL depth
2898
- depth = 3,
2899
- // 100kB, as 200kB is max payload size, so half sounds reasonable
2900
- maxSize = 100 * 1024,
2901
- ) {
2902
- const normalized = normalize(object, depth);
2903
-
2904
- if (jsonSize(normalized) > maxSize) {
2905
- return normalizeToSize(object, depth - 1, maxSize);
2906
- }
2907
-
2908
- return normalized ;
2909
- }
2910
-
2911
- /**
2912
- * Visits a node to perform normalization on it
2913
- *
2914
- * @param key The key corresponding to the given node
2915
- * @param value The node to be visited
2916
- * @param depth Optional number indicating the maximum recursion depth
2917
- * @param maxProperties Optional maximum number of properties/elements included in any single object/array
2918
- * @param memo Optional Memo class handling decycling
2919
- */
2920
- function visit(
2921
- key,
2922
- value,
2923
- depth = +Infinity,
2924
- maxProperties = +Infinity,
2925
- memo = memoBuilder(),
2926
- ) {
2927
- const [memoize, unmemoize] = memo;
2928
-
2929
- // Get the simple cases out of the way first
2930
- if (
2931
- value == null || // this matches null and undefined -> eqeq not eqeqeq
2932
- ['boolean', 'string'].includes(typeof value) ||
2933
- (typeof value === 'number' && Number.isFinite(value))
2934
- ) {
2935
- return value ;
2936
- }
2937
-
2938
- const stringified = stringifyValue(key, value);
2939
-
2940
- // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`.
2941
- // Everything else will have already been serialized, so if we don't see that pattern, we're done.
2942
- if (!stringified.startsWith('[object ')) {
2943
- return stringified;
2944
- }
2945
-
2946
- // From here on, we can assert that `value` is either an object or an array.
2947
-
2948
- // Do not normalize objects that we know have already been normalized. As a general rule, the
2949
- // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that
2950
- // have already been normalized.
2951
- if ((value )['__sentry_skip_normalization__']) {
2952
- return value ;
2953
- }
2954
-
2955
- // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there
2956
- // We keep a certain amount of depth.
2957
- // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.
2958
- const remainingDepth =
2959
- typeof (value )['__sentry_override_normalization_depth__'] === 'number'
2960
- ? ((value )['__sentry_override_normalization_depth__'] )
2961
- : depth;
2962
-
2963
- // We're also done if we've reached the max depth
2964
- if (remainingDepth === 0) {
2965
- // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`.
2966
- return stringified.replace('object ', '');
2967
- }
2968
-
2969
- // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.
2970
- if (memoize(value)) {
2971
- return '[Circular ~]';
2972
- }
2973
-
2974
- // If the value has a `toJSON` method, we call it to extract more information
2975
- const valueWithToJSON = value ;
2976
- if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {
2977
- try {
2978
- const jsonValue = valueWithToJSON.toJSON();
2979
- // We need to normalize the return value of `.toJSON()` in case it has circular references
2980
- return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);
2981
- } catch (err) {
2982
- // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)
2983
- }
2984
- }
2985
-
2986
- // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse
2987
- // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each
2988
- // property/entry, and keep track of the number of items we add to it.
2989
- const normalized = (Array.isArray(value) ? [] : {}) ;
2990
- let numAdded = 0;
2991
-
2992
- // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant
2993
- // properties are non-enumerable and otherwise would get missed.
2994
- const visitable = convertToPlainObject(value );
2995
-
2996
- for (const visitKey in visitable) {
2997
- // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.
2998
- if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
2999
- continue;
3000
- }
3001
-
3002
- if (numAdded >= maxProperties) {
3003
- normalized[visitKey] = '[MaxProperties ~]';
3004
- break;
3005
- }
3006
-
3007
- // Recursively visit all the child nodes
3008
- const visitValue = visitable[visitKey];
3009
- normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
3010
-
3011
- numAdded++;
3012
- }
3013
-
3014
- // Once we've visited all the branches, remove the parent from memo storage
3015
- unmemoize(value);
3016
-
3017
- // Return accumulated values
3018
- return normalized;
3019
- }
3020
-
3021
- /* eslint-disable complexity */
3022
- /**
3023
- * Stringify the given value. Handles various known special values and types.
3024
- *
3025
- * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn
3026
- * the number 1231 into "[Object Number]", nor on `null`, as it will throw.
3027
- *
3028
- * @param value The value to stringify
3029
- * @returns A stringified representation of the given value
3030
- */
3031
- function stringifyValue(
3032
- key,
3033
- // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for
3034
- // our internal use, it'll do
3035
- value,
3036
- ) {
3037
- try {
3038
- if (key === 'domain' && value && typeof value === 'object' && (value )._events) {
3039
- return '[Domain]';
3040
- }
3041
-
3042
- if (key === 'domainEmitter') {
3043
- return '[DomainEmitter]';
3044
- }
3045
-
3046
- // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first
3047
- // which won't throw if they are not present.
3048
-
3049
- if (typeof global !== 'undefined' && value === global) {
3050
- return '[Global]';
3051
- }
3052
-
3053
- // eslint-disable-next-line no-restricted-globals
3054
- if (typeof window !== 'undefined' && value === window) {
3055
- return '[Window]';
3056
- }
3057
-
3058
- // eslint-disable-next-line no-restricted-globals
3059
- if (typeof document !== 'undefined' && value === document) {
3060
- return '[Document]';
3061
- }
3062
-
3063
- if (isVueViewModel(value)) {
3064
- return '[VueViewModel]';
3065
- }
3066
-
3067
- // React's SyntheticEvent thingy
3068
- if (isSyntheticEvent(value)) {
3069
- return '[SyntheticEvent]';
3070
- }
3071
-
3072
- if (typeof value === 'number' && !Number.isFinite(value)) {
3073
- return `[${value}]`;
3074
- }
3075
-
3076
- if (typeof value === 'function') {
3077
- return `[Function: ${getFunctionName(value)}]`;
3078
- }
3079
-
3080
- if (typeof value === 'symbol') {
3081
- return `[${String(value)}]`;
3082
- }
3083
-
3084
- // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion
3085
- if (typeof value === 'bigint') {
3086
- return `[BigInt: ${String(value)}]`;
3087
- }
3088
-
3089
- // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting
3090
- // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as
3091
- // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class),
3092
- // we can make sure that only plain objects come out that way.
3093
- const objName = getConstructorName(value);
3094
-
3095
- // Handle HTML Elements
3096
- if (/^HTML(\w*)Element$/.test(objName)) {
3097
- return `[HTMLElement: ${objName}]`;
3098
- }
3099
-
3100
- return `[object ${objName}]`;
3101
- } catch (err) {
3102
- return `**non-serializable** (${err})`;
3103
- }
3104
- }
3105
- /* eslint-enable complexity */
3106
-
3107
- function getConstructorName(value) {
3108
- const prototype = Object.getPrototypeOf(value);
3109
-
3110
- return prototype?.constructor ? prototype.constructor.name : 'null prototype';
3111
- }
3112
-
3113
- /** Calculates bytes size of input string */
3114
- function utf8Length(value) {
3115
- // eslint-disable-next-line no-bitwise
3116
- return ~-encodeURI(value).split(/%..|./).length;
3117
- }
3118
-
3119
- /** Calculates bytes size of input object */
3120
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3121
- function jsonSize(value) {
3122
- return utf8Length(JSON.stringify(value));
3123
- }
3124
-
3125
- /**
3126
- * Helper to decycle json objects
3127
- */
3128
- function memoBuilder() {
3129
- const inner = new WeakSet();
3130
- function memoize(obj) {
3131
- if (inner.has(obj)) {
3132
- return true;
3133
- }
3134
- inner.add(obj);
3135
- return false;
3136
- }
3137
-
3138
- function unmemoize(obj) {
3139
- inner.delete(obj);
3140
- }
3141
- return [memoize, unmemoize];
3142
- }
3143
-
3144
- /* eslint-disable @typescript-eslint/no-explicit-any */
3145
-
3146
- /** SyncPromise internal states */
3147
- var States; (function (States) {
3148
- /** Pending */
3149
- const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING";
3150
- /** Resolved / OK */
3151
- const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED";
3152
- /** Rejected / Error */
3153
- const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED";
3154
- })(States || (States = {}));
3155
-
3156
- // Overloads so we can call resolvedSyncPromise without arguments and generic argument
3157
-
3158
- /**
3159
- * Creates a resolved sync promise.
3160
- *
3161
- * @param value the value to resolve the promise with
3162
- * @returns the resolved sync promise
3163
- */
3164
- function resolvedSyncPromise(value) {
3165
- return new SyncPromise(resolve => {
3166
- resolve(value);
3167
- });
3168
- }
3169
-
3170
- /**
3171
- * Creates a rejected sync promise.
3172
- *
3173
- * @param value the value to reject the promise with
3174
- * @returns the rejected sync promise
3175
- */
3176
- function rejectedSyncPromise(reason) {
3177
- return new SyncPromise((_, reject) => {
3178
- reject(reason);
3179
- });
3180
- }
3181
-
3182
- /**
3183
- * Thenable class that behaves like a Promise and follows it's interface
3184
- * but is not async internally
3185
- */
3186
- class SyncPromise {
3187
-
3188
- constructor(executor) {
3189
- this._state = States.PENDING;
3190
- this._handlers = [];
3191
-
3192
- this._runExecutor(executor);
3193
- }
3194
-
3195
- /** @inheritdoc */
3196
- then(
3197
- onfulfilled,
3198
- onrejected,
3199
- ) {
3200
- return new SyncPromise((resolve, reject) => {
3201
- this._handlers.push([
3202
- false,
3203
- result => {
3204
- if (!onfulfilled) {
3205
- // TODO: ¯\_(ツ)_/¯
3206
- // TODO: FIXME
3207
- resolve(result );
3208
- } else {
3209
- try {
3210
- resolve(onfulfilled(result));
3211
- } catch (e) {
3212
- reject(e);
3213
- }
3214
- }
3215
- },
3216
- reason => {
3217
- if (!onrejected) {
3218
- reject(reason);
3219
- } else {
3220
- try {
3221
- resolve(onrejected(reason));
3222
- } catch (e) {
3223
- reject(e);
3224
- }
3225
- }
3226
- },
3227
- ]);
3228
- this._executeHandlers();
3229
- });
3230
- }
3231
-
3232
- /** @inheritdoc */
3233
- catch(
3234
- onrejected,
3235
- ) {
3236
- return this.then(val => val, onrejected);
3237
- }
3238
-
3239
- /** @inheritdoc */
3240
- finally(onfinally) {
3241
- return new SyncPromise((resolve, reject) => {
3242
- let val;
3243
- let isRejected;
3244
-
3245
- return this.then(
3246
- value => {
3247
- isRejected = false;
3248
- val = value;
3249
- if (onfinally) {
3250
- onfinally();
3251
- }
3252
- },
3253
- reason => {
3254
- isRejected = true;
3255
- val = reason;
3256
- if (onfinally) {
3257
- onfinally();
3258
- }
3259
- },
3260
- ).then(() => {
3261
- if (isRejected) {
3262
- reject(val);
3263
- return;
3264
- }
3265
-
3266
- resolve(val );
3267
- });
3268
- });
3269
- }
3270
-
3271
- /** Excute the resolve/reject handlers. */
3272
- _executeHandlers() {
3273
- if (this._state === States.PENDING) {
3274
- return;
3275
- }
3276
-
3277
- const cachedHandlers = this._handlers.slice();
3278
- this._handlers = [];
3279
-
3280
- cachedHandlers.forEach(handler => {
3281
- if (handler[0]) {
3282
- return;
3283
- }
3284
-
3285
- if (this._state === States.RESOLVED) {
3286
- handler[1](this._value );
3287
- }
3288
-
3289
- if (this._state === States.REJECTED) {
3290
- handler[2](this._value);
3291
- }
3292
-
3293
- handler[0] = true;
3294
- });
3295
- }
3296
-
3297
- /** Run the executor for the SyncPromise. */
3298
- _runExecutor(executor) {
3299
- const setResult = (state, value) => {
3300
- if (this._state !== States.PENDING) {
3301
- return;
3302
- }
3303
-
3304
- if (isThenable(value)) {
3305
- void (value ).then(resolve, reject);
3306
- return;
3307
- }
3308
-
3309
- this._state = state;
3310
- this._value = value;
3311
-
3312
- this._executeHandlers();
3313
- };
3314
-
3315
- const resolve = (value) => {
3316
- setResult(States.RESOLVED, value);
3317
- };
3318
-
3319
- const reject = (reason) => {
3320
- setResult(States.REJECTED, reason);
3321
- };
3322
-
3323
- try {
3324
- executor(resolve, reject);
3325
- } catch (e) {
3326
- reject(e);
3327
- }
3328
- }
3329
- }
3330
-
3331
- /**
3332
- * Process an array of event processors, returning the processed event (or `null` if the event was dropped).
3333
- */
3334
- function notifyEventProcessors(
3335
- processors,
3336
- event,
3337
- hint,
3338
- index = 0,
3339
- ) {
3340
- return new SyncPromise((resolve, reject) => {
3341
- const processor = processors[index];
3342
- if (event === null || typeof processor !== 'function') {
3343
- resolve(event);
3344
- } else {
3345
- const result = processor({ ...event }, hint) ;
3346
-
3347
- DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor "${processor.id}" dropped event`);
3348
-
3349
- if (isThenable(result)) {
3350
- void result
3351
- .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))
3352
- .then(null, reject);
3353
- } else {
3354
- void notifyEventProcessors(processors, result, hint, index + 1)
3355
- .then(resolve)
3356
- .then(null, reject);
3357
- }
3358
- }
3359
- });
3360
- }
3361
-
3362
- let parsedStackResults;
3363
- let lastKeysCount;
3364
- let cachedFilenameDebugIds;
3365
-
3366
- /**
3367
- * Returns a map of filenames to debug identifiers.
3368
- */
3369
- function getFilenameToDebugIdMap(stackParser) {
3370
- const debugIdMap = GLOBAL_OBJ._sentryDebugIds;
3371
- if (!debugIdMap) {
3372
- return {};
3373
- }
3374
-
3375
- const debugIdKeys = Object.keys(debugIdMap);
3376
-
3377
- // If the count of registered globals hasn't changed since the last call, we
3378
- // can just return the cached result.
3379
- if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) {
3380
- return cachedFilenameDebugIds;
3381
- }
3382
-
3383
- lastKeysCount = debugIdKeys.length;
3384
-
3385
- // Build a map of filename -> debug_id.
3386
- cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => {
3387
- if (!parsedStackResults) {
3388
- parsedStackResults = {};
3389
- }
3390
-
3391
- const result = parsedStackResults[stackKey];
3392
-
3393
- if (result) {
3394
- acc[result[0]] = result[1];
3395
- } else {
3396
- const parsedStack = stackParser(stackKey);
3397
-
3398
- for (let i = parsedStack.length - 1; i >= 0; i--) {
3399
- const stackFrame = parsedStack[i];
3400
- const filename = stackFrame?.filename;
3401
- const debugId = debugIdMap[stackKey];
3402
-
3403
- if (filename && debugId) {
3404
- acc[filename] = debugId;
3405
- parsedStackResults[stackKey] = [filename, debugId];
3406
- break;
3407
- }
3408
- }
3409
- }
3410
-
3411
- return acc;
3412
- }, {});
3413
-
3414
- return cachedFilenameDebugIds;
3415
- }
3416
-
3417
- /**
3418
- * Applies data from the scope to the event and runs all event processors on it.
3419
- */
3420
- function applyScopeDataToEvent(event, data) {
3421
- const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;
3422
-
3423
- // Apply general data
3424
- applyDataToEvent(event, data);
3425
-
3426
- // We want to set the trace context for normal events only if there isn't already
3427
- // a trace context on the event. There is a product feature in place where we link
3428
- // errors with transaction and it relies on that.
3429
- if (span) {
3430
- applySpanToEvent(event, span);
3431
- }
3432
-
3433
- applyFingerprintToEvent(event, fingerprint);
3434
- applyBreadcrumbsToEvent(event, breadcrumbs);
3435
- applySdkMetadataToEvent(event, sdkProcessingMetadata);
3436
- }
3437
-
3438
- /** Merge data of two scopes together. */
3439
- function mergeScopeData(data, mergeData) {
3440
- const {
3441
- extra,
3442
- tags,
3443
- user,
3444
- contexts,
3445
- level,
3446
- sdkProcessingMetadata,
3447
- breadcrumbs,
3448
- fingerprint,
3449
- eventProcessors,
3450
- attachments,
3451
- propagationContext,
3452
- transactionName,
3453
- span,
3454
- } = mergeData;
3455
-
3456
- mergeAndOverwriteScopeData(data, 'extra', extra);
3457
- mergeAndOverwriteScopeData(data, 'tags', tags);
3458
- mergeAndOverwriteScopeData(data, 'user', user);
3459
- mergeAndOverwriteScopeData(data, 'contexts', contexts);
3460
-
3461
- data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);
3462
-
3463
- if (level) {
3464
- data.level = level;
3465
- }
3466
-
3467
- if (transactionName) {
3468
- data.transactionName = transactionName;
3469
- }
3470
-
3471
- if (span) {
3472
- data.span = span;
3473
- }
3474
-
3475
- if (breadcrumbs.length) {
3476
- data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];
3477
- }
3478
-
3479
- if (fingerprint.length) {
3480
- data.fingerprint = [...data.fingerprint, ...fingerprint];
3481
- }
3482
-
3483
- if (eventProcessors.length) {
3484
- data.eventProcessors = [...data.eventProcessors, ...eventProcessors];
3485
- }
3486
-
3487
- if (attachments.length) {
3488
- data.attachments = [...data.attachments, ...attachments];
3489
- }
3490
-
3491
- data.propagationContext = { ...data.propagationContext, ...propagationContext };
3492
- }
3493
-
3494
- /**
3495
- * Merges certain scope data. Undefined values will overwrite any existing values.
3496
- * Exported only for tests.
3497
- */
3498
- function mergeAndOverwriteScopeData
3499
-
3500
- (data, prop, mergeVal) {
3501
- data[prop] = merge(data[prop], mergeVal, 1);
3502
- }
3503
-
3504
- function applyDataToEvent(event, data) {
3505
- const { extra, tags, user, contexts, level, transactionName } = data;
3506
-
3507
- if (Object.keys(extra).length) {
3508
- event.extra = { ...extra, ...event.extra };
3509
- }
3510
-
3511
- if (Object.keys(tags).length) {
3512
- event.tags = { ...tags, ...event.tags };
3513
- }
3514
-
3515
- if (Object.keys(user).length) {
3516
- event.user = { ...user, ...event.user };
3517
- }
3518
-
3519
- if (Object.keys(contexts).length) {
3520
- event.contexts = { ...contexts, ...event.contexts };
3521
- }
3522
-
3523
- if (level) {
3524
- event.level = level;
3525
- }
3526
-
3527
- // transaction events get their `transaction` from the root span name
3528
- if (transactionName && event.type !== 'transaction') {
3529
- event.transaction = transactionName;
3530
- }
3531
- }
3532
-
3533
- function applyBreadcrumbsToEvent(event, breadcrumbs) {
3534
- const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];
3535
- event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;
3536
- }
3537
-
3538
- function applySdkMetadataToEvent(event, sdkProcessingMetadata) {
3539
- event.sdkProcessingMetadata = {
3540
- ...event.sdkProcessingMetadata,
3541
- ...sdkProcessingMetadata,
3542
- };
3543
- }
3544
-
3545
- function applySpanToEvent(event, span) {
3546
- event.contexts = {
3547
- trace: spanToTraceContext(span),
3548
- ...event.contexts,
3549
- };
3550
-
3551
- event.sdkProcessingMetadata = {
3552
- dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),
3553
- ...event.sdkProcessingMetadata,
3554
- };
3555
-
3556
- const rootSpan = getRootSpan(span);
3557
- const transactionName = spanToJSON(rootSpan).description;
3558
- if (transactionName && !event.transaction && event.type === 'transaction') {
3559
- event.transaction = transactionName;
3560
- }
3561
- }
3562
-
3563
- /**
3564
- * Applies fingerprint from the scope to the event if there's one,
3565
- * uses message if there's one instead or get rid of empty fingerprint
3566
- */
3567
- function applyFingerprintToEvent(event, fingerprint) {
3568
- // Make sure it's an array first and we actually have something in place
3569
- event.fingerprint = event.fingerprint
3570
- ? Array.isArray(event.fingerprint)
3571
- ? event.fingerprint
3572
- : [event.fingerprint]
3573
- : [];
3574
-
3575
- // If we have something on the scope, then merge it with event
3576
- if (fingerprint) {
3577
- event.fingerprint = event.fingerprint.concat(fingerprint);
3578
- }
3579
-
3580
- // If we have no data at all, remove empty array default
3581
- if (!event.fingerprint.length) {
3582
- delete event.fingerprint;
3583
- }
3584
- }
3585
-
3586
- /**
3587
- * This type makes sure that we get either a CaptureContext, OR an EventHint.
3588
- * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:
3589
- * { user: { id: '123' }, mechanism: { handled: false } }
3590
- */
3591
-
3592
- /**
3593
- * Adds common information to events.
3594
- *
3595
- * The information includes release and environment from `options`,
3596
- * breadcrumbs and context (extra, tags and user) from the scope.
3597
- *
3598
- * Information that is already present in the event is never overwritten. For
3599
- * nested objects, such as the context, keys are merged.
3600
- *
3601
- * @param event The original event.
3602
- * @param hint May contain additional information about the original exception.
3603
- * @param scope A scope containing event metadata.
3604
- * @returns A new event with more information.
3605
- * @hidden
3606
- */
3607
- function prepareEvent(
3608
- options,
3609
- event,
3610
- hint,
3611
- scope,
3612
- client,
3613
- isolationScope,
3614
- ) {
3615
- const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;
3616
- const prepared = {
3617
- ...event,
3618
- event_id: event.event_id || hint.event_id || uuid4(),
3619
- timestamp: event.timestamp || dateTimestampInSeconds(),
3620
- };
3621
- const integrations = hint.integrations || options.integrations.map(i => i.name);
3622
-
3623
- applyClientOptions(prepared, options);
3624
- applyIntegrationsMetadata(prepared, integrations);
3625
-
3626
- if (client) {
3627
- client.emit('applyFrameMetadata', event);
3628
- }
3629
-
3630
- // Only put debug IDs onto frames for error events.
3631
- if (event.type === undefined) {
3632
- applyDebugIds(prepared, options.stackParser);
3633
- }
3634
-
3635
- // If we have scope given to us, use it as the base for further modifications.
3636
- // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.
3637
- const finalScope = getFinalScope(scope, hint.captureContext);
3638
-
3639
- if (hint.mechanism) {
3640
- addExceptionMechanism(prepared, hint.mechanism);
3641
- }
3642
-
3643
- const clientEventProcessors = client ? client.getEventProcessors() : [];
3644
-
3645
- // This should be the last thing called, since we want that
3646
- // {@link Scope.addEventProcessor} gets the finished prepared event.
3647
- // Merge scope data together
3648
- const data = getGlobalScope().getScopeData();
3649
-
3650
- if (isolationScope) {
3651
- const isolationData = isolationScope.getScopeData();
3652
- mergeScopeData(data, isolationData);
3653
- }
3654
-
3655
- if (finalScope) {
3656
- const finalScopeData = finalScope.getScopeData();
3657
- mergeScopeData(data, finalScopeData);
3658
- }
3659
-
3660
- const attachments = [...(hint.attachments || []), ...data.attachments];
3661
- if (attachments.length) {
3662
- hint.attachments = attachments;
3663
- }
3664
-
3665
- applyScopeDataToEvent(prepared, data);
3666
-
3667
- const eventProcessors = [
3668
- ...clientEventProcessors,
3669
- // Run scope event processors _after_ all other processors
3670
- ...data.eventProcessors,
3671
- ];
3672
-
3673
- const result = notifyEventProcessors(eventProcessors, prepared, hint);
3674
-
3675
- return result.then(evt => {
3676
- if (evt) {
3677
- // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified
3678
- // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.
3679
- // This should not cause any PII issues, since we're only moving data that is already on the event and not adding
3680
- // any new data
3681
- applyDebugMeta(evt);
3682
- }
3683
-
3684
- if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {
3685
- return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);
3686
- }
3687
- return evt;
3688
- });
3689
- }
3690
-
3691
- /**
3692
- * Enhances event using the client configuration.
3693
- * It takes care of all "static" values like environment, release and `dist`,
3694
- * as well as truncating overly long values.
3695
- *
3696
- * Only exported for tests.
3697
- *
3698
- * @param event event instance to be enhanced
3699
- */
3700
- function applyClientOptions(event, options) {
3701
- const { environment, release, dist, maxValueLength = 250 } = options;
3702
-
3703
- // empty strings do not make sense for environment, release, and dist
3704
- // so we handle them the same as if they were not provided
3705
- event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;
3706
-
3707
- if (!event.release && release) {
3708
- event.release = release;
3709
- }
3710
-
3711
- if (!event.dist && dist) {
3712
- event.dist = dist;
3713
- }
3714
-
3715
- const request = event.request;
3716
- if (request?.url) {
3717
- request.url = truncate(request.url, maxValueLength);
3718
- }
3719
- }
3720
-
3721
- /**
3722
- * Puts debug IDs into the stack frames of an error event.
3723
- */
3724
- function applyDebugIds(event, stackParser) {
3725
- // Build a map of filename -> debug_id
3726
- const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);
3727
-
3728
- event.exception?.values?.forEach(exception => {
3729
- exception.stacktrace?.frames?.forEach(frame => {
3730
- if (frame.filename) {
3731
- frame.debug_id = filenameDebugIdMap[frame.filename];
3732
- }
3733
- });
3734
- });
3735
- }
3736
-
3737
- /**
3738
- * Moves debug IDs from the stack frames of an error event into the debug_meta field.
3739
- */
3740
- function applyDebugMeta(event) {
3741
- // Extract debug IDs and filenames from the stack frames on the event.
3742
- const filenameDebugIdMap = {};
3743
- event.exception?.values?.forEach(exception => {
3744
- exception.stacktrace?.frames?.forEach(frame => {
3745
- if (frame.debug_id) {
3746
- if (frame.abs_path) {
3747
- filenameDebugIdMap[frame.abs_path] = frame.debug_id;
3748
- } else if (frame.filename) {
3749
- filenameDebugIdMap[frame.filename] = frame.debug_id;
3750
- }
3751
- delete frame.debug_id;
3752
- }
3753
- });
3754
- });
3755
-
3756
- if (Object.keys(filenameDebugIdMap).length === 0) {
3757
- return;
3758
- }
3759
-
3760
- // Fill debug_meta information
3761
- event.debug_meta = event.debug_meta || {};
3762
- event.debug_meta.images = event.debug_meta.images || [];
3763
- const images = event.debug_meta.images;
3764
- Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {
3765
- images.push({
3766
- type: 'sourcemap',
3767
- code_file: filename,
3768
- debug_id,
3769
- });
3770
- });
3771
- }
3772
-
3773
- /**
3774
- * This function adds all used integrations to the SDK info in the event.
3775
- * @param event The event that will be filled with all integrations.
3776
- */
3777
- function applyIntegrationsMetadata(event, integrationNames) {
3778
- if (integrationNames.length > 0) {
3779
- event.sdk = event.sdk || {};
3780
- event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];
3781
- }
3782
- }
3783
-
3784
- /**
3785
- * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.
3786
- * Normalized keys:
3787
- * - `breadcrumbs.data`
3788
- * - `user`
3789
- * - `contexts`
3790
- * - `extra`
3791
- * @param event Event
3792
- * @returns Normalized event
3793
- */
3794
- function normalizeEvent(event, depth, maxBreadth) {
3795
- if (!event) {
3796
- return null;
3797
- }
3798
-
3799
- const normalized = {
3800
- ...event,
3801
- ...(event.breadcrumbs && {
3802
- breadcrumbs: event.breadcrumbs.map(b => ({
3803
- ...b,
3804
- ...(b.data && {
3805
- data: normalize(b.data, depth, maxBreadth),
3806
- }),
3807
- })),
3808
- }),
3809
- ...(event.user && {
3810
- user: normalize(event.user, depth, maxBreadth),
3811
- }),
3812
- ...(event.contexts && {
3813
- contexts: normalize(event.contexts, depth, maxBreadth),
3814
- }),
3815
- ...(event.extra && {
3816
- extra: normalize(event.extra, depth, maxBreadth),
3817
- }),
3818
- };
3819
-
3820
- // event.contexts.trace stores information about a Transaction. Similarly,
3821
- // event.spans[] stores information about child Spans. Given that a
3822
- // Transaction is conceptually a Span, normalization should apply to both
3823
- // Transactions and Spans consistently.
3824
- // For now the decision is to skip normalization of Transactions and Spans,
3825
- // so this block overwrites the normalized event to add back the original
3826
- // Transaction information prior to normalization.
3827
- if (event.contexts?.trace && normalized.contexts) {
3828
- normalized.contexts.trace = event.contexts.trace;
3829
-
3830
- // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it
3831
- if (event.contexts.trace.data) {
3832
- normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);
3833
- }
3834
- }
3835
-
3836
- // event.spans[].data may contain circular/dangerous data so we need to normalize it
3837
- if (event.spans) {
3838
- normalized.spans = event.spans.map(span => {
3839
- return {
3840
- ...span,
3841
- ...(span.data && {
3842
- data: normalize(span.data, depth, maxBreadth),
3843
- }),
3844
- };
3845
- });
3846
- }
3847
-
3848
- // event.contexts.flags (FeatureFlagContext) stores context for our feature
3849
- // flag integrations. It has a greater nesting depth than our other typed
3850
- // Contexts, so we re-normalize with a fixed depth of 3 here. We do not want
3851
- // to skip this in case of conflicting, user-provided context.
3852
- if (event.contexts?.flags && normalized.contexts) {
3853
- normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);
3854
- }
3855
-
3856
- return normalized;
3857
- }
3858
-
3859
- function getFinalScope(scope, captureContext) {
3860
- if (!captureContext) {
3861
- return scope;
3862
- }
3863
-
3864
- const finalScope = scope ? scope.clone() : new Scope();
3865
- finalScope.update(captureContext);
3866
- return finalScope;
3867
- }
3868
-
3869
- /**
3870
- * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.
3871
- * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.
3872
- */
3873
- function parseEventHintOrCaptureContext(
3874
- hint,
3875
- ) {
3876
- {
3877
- return undefined;
3878
- }
3879
- }
3880
-
3881
- /**
3882
- * Captures an exception event and sends it to Sentry.
3883
- *
3884
- * @param exception The exception to capture.
3885
- * @param hint Optional additional data to attach to the Sentry event.
3886
- * @returns the id of the captured Sentry event.
3887
- */
3888
- function captureException(exception, hint) {
3889
- return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext());
3890
- }
3891
-
3892
- /**
3893
- * Captures a message event and sends it to Sentry.
3894
- *
3895
- * @param message The message to send to Sentry.
3896
- * @param captureContext Define the level of the message or pass in additional data to attach to the message.
3897
- * @returns the id of the captured message.
3898
- */
3899
- function captureMessage(message, captureContext) {
3900
- // This is necessary to provide explicit scopes upgrade, without changing the original
3901
- // arity of the `captureMessage(message, level)` method.
3902
- const level = undefined;
3903
- const context = { captureContext } ;
3904
- return getCurrentScope().captureMessage(message, level, context);
3905
- }
3906
-
3907
- /**
3908
- * Captures a manually created event and sends it to Sentry.
3909
- *
3910
- * @param event The event to send to Sentry.
3911
- * @param hint Optional additional data to attach to the Sentry event.
3912
- * @returns the id of the captured event.
3913
- */
3914
- function captureEvent(event, hint) {
3915
- return getCurrentScope().captureEvent(event, hint);
3916
- }
3917
-
3918
- /**
3919
- * Sets context data with the given name.
3920
- * @param name of the context
3921
- * @param context Any kind of data. This data will be normalized.
3922
- */
3923
- function setContext(name, context) {
3924
- getIsolationScope().setContext(name, context);
3925
- }
3926
-
3927
- /**
3928
- * Updates user context information for future events.
3929
- *
3930
- * @param user User context object to be set in the current context. Pass `null` to unset the user.
3931
- */
3932
- function setUser(user) {
3933
- getIsolationScope().setUser(user);
3934
- }
3935
-
3936
- /**
3937
- * Start a session on the current isolation scope.
3938
- *
3939
- * @param context (optional) additional properties to be applied to the returned session object
3940
- *
3941
- * @returns the new active session
3942
- */
3943
- function startSession(context) {
3944
- const isolationScope = getIsolationScope();
3945
- const currentScope = getCurrentScope();
3946
-
3947
- // Will fetch userAgent if called from browser sdk
3948
- const { userAgent } = GLOBAL_OBJ.navigator || {};
3949
-
3950
- const session = makeSession({
3951
- user: currentScope.getUser() || isolationScope.getUser(),
3952
- ...(userAgent && { userAgent }),
3953
- ...context,
3954
- });
3955
-
3956
- // End existing session if there's one
3957
- const currentSession = isolationScope.getSession();
3958
- if (currentSession?.status === 'ok') {
3959
- updateSession(currentSession, { status: 'exited' });
3960
- }
3961
-
3962
- endSession();
3963
-
3964
- // Afterwards we set the new session on the scope
3965
- isolationScope.setSession(session);
3966
-
3967
- return session;
3968
- }
3969
-
3970
- /**
3971
- * End the session on the current isolation scope.
3972
- */
3973
- function endSession() {
3974
- const isolationScope = getIsolationScope();
3975
- const currentScope = getCurrentScope();
3976
-
3977
- const session = currentScope.getSession() || isolationScope.getSession();
3978
- if (session) {
3979
- closeSession(session);
3980
- }
3981
- _sendSessionUpdate();
3982
-
3983
- // the session is over; take it off of the scope
3984
- isolationScope.setSession();
3985
- }
3986
-
3987
- /**
3988
- * Sends the current Session on the scope
3989
- */
3990
- function _sendSessionUpdate() {
3991
- const isolationScope = getIsolationScope();
3992
- const client = getClient();
3993
- const session = isolationScope.getSession();
3994
- if (session && client) {
3995
- client.captureSession(session);
3996
- }
3997
- }
3998
-
3999
- /**
4000
- * Sends the current session on the scope to Sentry
4001
- *
4002
- * @param end If set the session will be marked as exited and removed from the scope.
4003
- * Defaults to `false`.
4004
- */
4005
- function captureSession(end = false) {
4006
- // both send the update and pull the session from the scope
4007
- if (end) {
4008
- endSession();
4009
- return;
4010
- }
4011
-
4012
- // only send the update
4013
- _sendSessionUpdate();
4014
- }
4015
-
4016
- exports.CONSOLE_LEVELS = CONSOLE_LEVELS;
4017
- exports.DEBUG_BUILD = DEBUG_BUILD;
4018
- exports.DEFAULT_ENVIRONMENT = DEFAULT_ENVIRONMENT;
4019
- exports.GLOBAL_OBJ = GLOBAL_OBJ;
4020
- exports.SDK_VERSION = SDK_VERSION;
4021
- exports.SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME;
4022
- exports.SEMANTIC_ATTRIBUTE_PROFILE_ID = SEMANTIC_ATTRIBUTE_PROFILE_ID;
4023
- exports.SyncPromise = SyncPromise;
4024
- exports.UNKNOWN_FUNCTION = UNKNOWN_FUNCTION;
4025
- exports.addExceptionMechanism = addExceptionMechanism;
4026
- exports.addExceptionTypeValue = addExceptionTypeValue;
4027
- exports.addNonEnumerableProperty = addNonEnumerableProperty;
4028
- exports.captureEvent = captureEvent;
4029
- exports.captureException = captureException;
4030
- exports.captureMessage = captureMessage;
4031
- exports.captureSession = captureSession;
4032
- exports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught;
4033
- exports.consoleSandbox = consoleSandbox;
4034
- exports.createStackParser = createStackParser;
4035
- exports.dateTimestampInSeconds = dateTimestampInSeconds;
4036
- exports.dsnToString = dsnToString;
4037
- exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage;
4038
- exports.fill = fill;
4039
- exports.getClient = getClient;
4040
- exports.getComponentName = getComponentName;
4041
- exports.getCurrentScope = getCurrentScope;
4042
- exports.getDynamicSamplingContextFromScope = getDynamicSamplingContextFromScope;
4043
- exports.getEventDescription = getEventDescription;
4044
- exports.getFramesFromEvent = getFramesFromEvent;
4045
- exports.getFunctionName = getFunctionName;
4046
- exports.getIsolationScope = getIsolationScope;
4047
- exports.getLocationHref = getLocationHref;
4048
- exports.getOriginalFunction = getOriginalFunction;
4049
- exports.getSentryCarrier = getSentryCarrier;
4050
- exports.getTraceContextFromScope = getTraceContextFromScope;
4051
- exports.htmlTreeAsString = htmlTreeAsString;
4052
- exports.isDOMError = isDOMError;
4053
- exports.isDOMException = isDOMException;
4054
- exports.isError = isError;
4055
- exports.isErrorEvent = isErrorEvent;
4056
- exports.isEvent = isEvent;
4057
- exports.isInstanceOf = isInstanceOf;
4058
- exports.isParameterizedString = isParameterizedString;
4059
- exports.isPlainObject = isPlainObject;
4060
- exports.isPrimitive = isPrimitive;
4061
- exports.isRequest = isRequest;
4062
- exports.isString = isString;
4063
- exports.isThenable = isThenable;
4064
- exports.logger = logger;
4065
- exports.makeDsn = makeDsn;
4066
- exports.markFunctionWrapped = markFunctionWrapped;
4067
- exports.merge = merge;
4068
- exports.normalize = normalize;
4069
- exports.normalizeToSize = normalizeToSize;
4070
- exports.originalConsoleMethods = originalConsoleMethods;
4071
- exports.prepareEvent = prepareEvent;
4072
- exports.rejectedSyncPromise = rejectedSyncPromise;
4073
- exports.resolvedSyncPromise = resolvedSyncPromise;
4074
- exports.safeJoin = safeJoin;
4075
- exports.setContext = setContext;
4076
- exports.setUser = setUser;
4077
- exports.showSpanDropWarning = showSpanDropWarning;
4078
- exports.stackParserFromStackParserOptions = stackParserFromStackParserOptions;
4079
- exports.startSession = startSession;
4080
- exports.stringMatchesSomePattern = stringMatchesSomePattern;
4081
- exports.timestampInSeconds = timestampInSeconds;
4082
- exports.updateSession = updateSession;
4083
- exports.uuid4 = uuid4;
4084
- exports.withScope = withScope;
4085
- //# sourceMappingURL=exports-Dc-pQh4A.js.map
4086
-
4087
- //# sourceMappingURL=exports-Dc-pQh4A.js.map