@maestro_io/maestro-web-sdk 5.2.0 → 5.2.2

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 (680) hide show
  1. package/README.md +25 -0
  2. package/dist/index.d.ts +4 -3
  3. package/dist/maestro-web-sdk.esm.js +3 -3
  4. package/dist/maestro-web-sdk.esm.js.map +1 -1
  5. package/dist/maestro-web-sdk.umd.js +3 -3
  6. package/dist/maestro-web-sdk.umd.js.map +1 -1
  7. package/package.json +1 -1
  8. package/dist/1.maestro-web-sdk.esm.js +0 -2
  9. package/dist/1.maestro-web-sdk.esm.js.map +0 -1
  10. package/dist/10.maestro-web-sdk.esm.js +0 -2
  11. package/dist/10.maestro-web-sdk.esm.js.map +0 -1
  12. package/dist/11.maestro-web-sdk.esm.js +0 -2
  13. package/dist/11.maestro-web-sdk.esm.js.map +0 -1
  14. package/dist/12.maestro-web-sdk.esm.js +0 -2
  15. package/dist/12.maestro-web-sdk.esm.js.map +0 -1
  16. package/dist/13.maestro-web-sdk.esm.js +0 -2
  17. package/dist/13.maestro-web-sdk.esm.js.map +0 -1
  18. package/dist/14.maestro-web-sdk.esm.js +0 -2
  19. package/dist/14.maestro-web-sdk.esm.js.map +0 -1
  20. package/dist/15.maestro-web-sdk.esm.js +0 -2
  21. package/dist/15.maestro-web-sdk.esm.js.map +0 -1
  22. package/dist/16.maestro-web-sdk.esm.js +0 -2
  23. package/dist/16.maestro-web-sdk.esm.js.map +0 -1
  24. package/dist/17.maestro-web-sdk.esm.js +0 -2
  25. package/dist/17.maestro-web-sdk.esm.js.map +0 -1
  26. package/dist/18.maestro-web-sdk.esm.js +0 -2
  27. package/dist/18.maestro-web-sdk.esm.js.map +0 -1
  28. package/dist/19.maestro-web-sdk.esm.js +0 -2
  29. package/dist/19.maestro-web-sdk.esm.js.map +0 -1
  30. package/dist/2.maestro-web-sdk.esm.js +0 -2
  31. package/dist/2.maestro-web-sdk.esm.js.map +0 -1
  32. package/dist/20.maestro-web-sdk.esm.js +0 -2
  33. package/dist/20.maestro-web-sdk.esm.js.map +0 -1
  34. package/dist/21.maestro-web-sdk.esm.js +0 -2
  35. package/dist/21.maestro-web-sdk.esm.js.map +0 -1
  36. package/dist/22.maestro-web-sdk.esm.js +0 -2
  37. package/dist/22.maestro-web-sdk.esm.js.map +0 -1
  38. package/dist/23.maestro-web-sdk.esm.js +0 -2
  39. package/dist/23.maestro-web-sdk.esm.js.map +0 -1
  40. package/dist/24.maestro-web-sdk.esm.js +0 -2
  41. package/dist/24.maestro-web-sdk.esm.js.map +0 -1
  42. package/dist/25.maestro-web-sdk.esm.js +0 -2
  43. package/dist/25.maestro-web-sdk.esm.js.map +0 -1
  44. package/dist/26.maestro-web-sdk.esm.js +0 -2
  45. package/dist/26.maestro-web-sdk.esm.js.map +0 -1
  46. package/dist/27.maestro-web-sdk.esm.js +0 -2
  47. package/dist/27.maestro-web-sdk.esm.js.map +0 -1
  48. package/dist/28.maestro-web-sdk.esm.js +0 -2
  49. package/dist/28.maestro-web-sdk.esm.js.map +0 -1
  50. package/dist/29.maestro-web-sdk.esm.js +0 -2
  51. package/dist/29.maestro-web-sdk.esm.js.map +0 -1
  52. package/dist/3.maestro-web-sdk.esm.js +0 -2
  53. package/dist/3.maestro-web-sdk.esm.js.map +0 -1
  54. package/dist/30.maestro-web-sdk.esm.js +0 -2
  55. package/dist/30.maestro-web-sdk.esm.js.map +0 -1
  56. package/dist/31.maestro-web-sdk.esm.js +0 -2
  57. package/dist/31.maestro-web-sdk.esm.js.map +0 -1
  58. package/dist/32.maestro-web-sdk.esm.js +0 -2
  59. package/dist/32.maestro-web-sdk.esm.js.map +0 -1
  60. package/dist/33.maestro-web-sdk.esm.js +0 -2
  61. package/dist/33.maestro-web-sdk.esm.js.map +0 -1
  62. package/dist/34.maestro-web-sdk.esm.js +0 -2
  63. package/dist/34.maestro-web-sdk.esm.js.map +0 -1
  64. package/dist/35.maestro-web-sdk.esm.js +0 -2
  65. package/dist/35.maestro-web-sdk.esm.js.map +0 -1
  66. package/dist/36.maestro-web-sdk.esm.js +0 -2
  67. package/dist/36.maestro-web-sdk.esm.js.map +0 -1
  68. package/dist/37.maestro-web-sdk.esm.js +0 -2
  69. package/dist/37.maestro-web-sdk.esm.js.map +0 -1
  70. package/dist/38.maestro-web-sdk.esm.js +0 -2
  71. package/dist/38.maestro-web-sdk.esm.js.map +0 -1
  72. package/dist/39.maestro-web-sdk.esm.js +0 -2
  73. package/dist/39.maestro-web-sdk.esm.js.map +0 -1
  74. package/dist/4.maestro-web-sdk.esm.js +0 -2
  75. package/dist/4.maestro-web-sdk.esm.js.map +0 -1
  76. package/dist/40.maestro-web-sdk.esm.js +0 -2
  77. package/dist/40.maestro-web-sdk.esm.js.map +0 -1
  78. package/dist/5.maestro-web-sdk.esm.js +0 -2
  79. package/dist/5.maestro-web-sdk.esm.js.map +0 -1
  80. package/dist/6.maestro-web-sdk.esm.js +0 -2
  81. package/dist/6.maestro-web-sdk.esm.js.map +0 -1
  82. package/dist/7.maestro-web-sdk.esm.js +0 -2
  83. package/dist/7.maestro-web-sdk.esm.js.map +0 -1
  84. package/dist/8.maestro-web-sdk.esm.js +0 -2
  85. package/dist/8.maestro-web-sdk.esm.js.map +0 -1
  86. package/dist/9.maestro-web-sdk.esm.js +0 -2
  87. package/dist/9.maestro-web-sdk.esm.js.map +0 -1
  88. package/dist/package.json +0 -94
  89. package/dist/src/components/atoms/BaseButton/BaseButton.d.ts +0 -7
  90. package/dist/src/components/atoms/BaseButton/BaseButton.js +0 -11
  91. package/dist/src/components/atoms/BaseButton/index.d.ts +0 -2
  92. package/dist/src/components/atoms/BaseButton/index.js +0 -2
  93. package/dist/src/components/atoms/Image/index.d.ts +0 -13
  94. package/dist/src/components/atoms/Image/index.js +0 -34
  95. package/dist/src/components/atoms/Rive/index.d.ts +0 -221
  96. package/dist/src/components/atoms/Rive/index.js +0 -53
  97. package/dist/src/components/atoms/SvgIcon/AddIcon.d.ts +0 -3
  98. package/dist/src/components/atoms/SvgIcon/AddIcon.js +0 -6
  99. package/dist/src/components/atoms/SvgIcon/BetGeneralIcon.d.ts +0 -3
  100. package/dist/src/components/atoms/SvgIcon/BetGeneralIcon.js +0 -9
  101. package/dist/src/components/atoms/SvgIcon/BetsIcon.d.ts +0 -3
  102. package/dist/src/components/atoms/SvgIcon/BetsIcon.js +0 -8
  103. package/dist/src/components/atoms/SvgIcon/BetsWarningIcon.d.ts +0 -7
  104. package/dist/src/components/atoms/SvgIcon/BetsWarningIcon.js +0 -11
  105. package/dist/src/components/atoms/SvgIcon/BuilderIcon.d.ts +0 -3
  106. package/dist/src/components/atoms/SvgIcon/BuilderIcon.js +0 -8
  107. package/dist/src/components/atoms/SvgIcon/ChatIcon.d.ts +0 -3
  108. package/dist/src/components/atoms/SvgIcon/ChatIcon.js +0 -6
  109. package/dist/src/components/atoms/SvgIcon/CheckmarkIcon.d.ts +0 -3
  110. package/dist/src/components/atoms/SvgIcon/CheckmarkIcon.js +0 -6
  111. package/dist/src/components/atoms/SvgIcon/CollapseIcon.d.ts +0 -3
  112. package/dist/src/components/atoms/SvgIcon/CollapseIcon.js +0 -6
  113. package/dist/src/components/atoms/SvgIcon/ExpandIcon.d.ts +0 -3
  114. package/dist/src/components/atoms/SvgIcon/ExpandIcon.js +0 -6
  115. package/dist/src/components/atoms/SvgIcon/FantasyIcon.d.ts +0 -7
  116. package/dist/src/components/atoms/SvgIcon/FantasyIcon.js +0 -15
  117. package/dist/src/components/atoms/SvgIcon/FlameIcon.d.ts +0 -7
  118. package/dist/src/components/atoms/SvgIcon/FlameIcon.js +0 -11
  119. package/dist/src/components/atoms/SvgIcon/FoxKeyPlaysIcon.d.ts +0 -3
  120. package/dist/src/components/atoms/SvgIcon/FoxKeyPlaysIcon.js +0 -7
  121. package/dist/src/components/atoms/SvgIcon/FoxMultiViewIcon.d.ts +0 -3
  122. package/dist/src/components/atoms/SvgIcon/FoxMultiViewIcon.js +0 -10
  123. package/dist/src/components/atoms/SvgIcon/FoxStatsIcon.d.ts +0 -3
  124. package/dist/src/components/atoms/SvgIcon/FoxStatsIcon.js +0 -7
  125. package/dist/src/components/atoms/SvgIcon/HelloWorldIcon.d.ts +0 -3
  126. package/dist/src/components/atoms/SvgIcon/HelloWorldIcon.js +0 -6
  127. package/dist/src/components/atoms/SvgIcon/Icon.d.ts +0 -15
  128. package/dist/src/components/atoms/SvgIcon/Icon.js +0 -70
  129. package/dist/src/components/atoms/SvgIcon/KeyPlaysIcon.d.ts +0 -6
  130. package/dist/src/components/atoms/SvgIcon/KeyPlaysIcon.js +0 -10
  131. package/dist/src/components/atoms/SvgIcon/MobilePhoneIcon.d.ts +0 -7
  132. package/dist/src/components/atoms/SvgIcon/MobilePhoneIcon.js +0 -11
  133. package/dist/src/components/atoms/SvgIcon/PlayIcon.d.ts +0 -6
  134. package/dist/src/components/atoms/SvgIcon/PlayIcon.js +0 -8
  135. package/dist/src/components/atoms/SvgIcon/ShopIcon.d.ts +0 -5
  136. package/dist/src/components/atoms/SvgIcon/ShopIcon.js +0 -7
  137. package/dist/src/components/atoms/SvgIcon/ShopifyIcon.d.ts +0 -3
  138. package/dist/src/components/atoms/SvgIcon/ShopifyIcon.js +0 -6
  139. package/dist/src/components/atoms/SvgIcon/StatsIcon.d.ts +0 -6
  140. package/dist/src/components/atoms/SvgIcon/StatsIcon.js +0 -12
  141. package/dist/src/components/atoms/SvgIcon/TimesIcon.d.ts +0 -3
  142. package/dist/src/components/atoms/SvgIcon/TimesIcon.js +0 -6
  143. package/dist/src/components/atoms/SvgIcon/WarningIcon.d.ts +0 -6
  144. package/dist/src/components/atoms/SvgIcon/WarningIcon.js +0 -8
  145. package/dist/src/components/atoms/SvgIcon/index.d.ts +0 -2
  146. package/dist/src/components/atoms/SvgIcon/index.js +0 -2
  147. package/dist/src/components/core/App/App.d.ts +0 -11
  148. package/dist/src/components/core/App/App.js +0 -35
  149. package/dist/src/components/core/App/index.d.ts +0 -2
  150. package/dist/src/components/core/App/index.js +0 -2
  151. package/dist/src/components/core/PanelManager/PanelManager.d.ts +0 -21
  152. package/dist/src/components/core/PanelManager/PanelManager.js +0 -104
  153. package/dist/src/components/core/PanelManager/index.d.ts +0 -2
  154. package/dist/src/components/core/PanelManager/index.js +0 -2
  155. package/dist/src/components/core/ScrollableContainer/FocusableItem.d.ts +0 -11
  156. package/dist/src/components/core/ScrollableContainer/FocusableItem.js +0 -24
  157. package/dist/src/components/core/ScrollableContainer/ScrollableContainer.d.ts +0 -54
  158. package/dist/src/components/core/ScrollableContainer/ScrollableContainer.js +0 -111
  159. package/dist/src/components/core/ScrollableContainer/index.d.ts +0 -6
  160. package/dist/src/components/core/ScrollableContainer/index.js +0 -5
  161. package/dist/src/components/core/ScrollableContainer/useScrollableContainer.d.ts +0 -14
  162. package/dist/src/components/core/ScrollableContainer/useScrollableContainer.js +0 -22
  163. package/dist/src/components/molecules/ActionButton/ActionButton.d.ts +0 -96
  164. package/dist/src/components/molecules/ActionButton/ActionButton.js +0 -15
  165. package/dist/src/components/molecules/ActionButton/index.d.ts +0 -2
  166. package/dist/src/components/molecules/ActionButton/index.js +0 -2
  167. package/dist/src/components/molecules/HeadshotImage/HeadshotImage.d.ts +0 -16
  168. package/dist/src/components/molecules/HeadshotImage/HeadshotImage.js +0 -50
  169. package/dist/src/components/molecules/HeadshotImage/index.d.ts +0 -2
  170. package/dist/src/components/molecules/HeadshotImage/index.js +0 -2
  171. package/dist/src/components/molecules/NetworkDialog/NetworkDialog.d.ts +0 -11
  172. package/dist/src/components/molecules/NetworkDialog/NetworkDialog.js +0 -34
  173. package/dist/src/components/molecules/NetworkDialog/index.d.ts +0 -2
  174. package/dist/src/components/molecules/NetworkDialog/index.js +0 -2
  175. package/dist/src/components/molecules/NetworkError/NetworkError.d.ts +0 -104
  176. package/dist/src/components/molecules/NetworkError/NetworkError.js +0 -26
  177. package/dist/src/components/molecules/NetworkError/index.d.ts +0 -2
  178. package/dist/src/components/molecules/NetworkError/index.js +0 -2
  179. package/dist/src/components/molecules/PanelNavButton/PanelNavButton.d.ts +0 -107
  180. package/dist/src/components/molecules/PanelNavButton/PanelNavButton.js +0 -36
  181. package/dist/src/components/molecules/PanelNavButton/index.d.ts +0 -2
  182. package/dist/src/components/molecules/PanelNavButton/index.js +0 -2
  183. package/dist/src/components/molecules/SegmentButton/SegmentButton.d.ts +0 -9
  184. package/dist/src/components/molecules/SegmentButton/SegmentButton.js +0 -10
  185. package/dist/src/components/molecules/SegmentButton/index.d.ts +0 -2
  186. package/dist/src/components/molecules/SegmentButton/index.js +0 -2
  187. package/dist/src/components/molecules/TabLoadError/TabLoadError.d.ts +0 -96
  188. package/dist/src/components/molecules/TabLoadError/TabLoadError.js +0 -14
  189. package/dist/src/components/molecules/TabLoadError/index.d.ts +0 -2
  190. package/dist/src/components/molecules/TabLoadError/index.js +0 -2
  191. package/dist/src/components/molecules/WatchButton/WatchButton.d.ts +0 -10
  192. package/dist/src/components/molecules/WatchButton/WatchButton.js +0 -15
  193. package/dist/src/components/molecules/WatchButton/index.d.ts +0 -2
  194. package/dist/src/components/molecules/WatchButton/index.js +0 -2
  195. package/dist/src/components/organisms/PanelNavigation/PanelNavigation.d.ts +0 -17
  196. package/dist/src/components/organisms/PanelNavigation/PanelNavigation.js +0 -64
  197. package/dist/src/components/organisms/PanelNavigation/index.d.ts +0 -2
  198. package/dist/src/components/organisms/PanelNavigation/index.js +0 -2
  199. package/dist/src/components/organisms/SegmentController/SegmentController.d.ts +0 -12
  200. package/dist/src/components/organisms/SegmentController/SegmentController.js +0 -35
  201. package/dist/src/components/organisms/SegmentController/index.d.ts +0 -3
  202. package/dist/src/components/organisms/SegmentController/index.js +0 -2
  203. package/dist/src/development/MaestroEventDelegate.d.ts +0 -27
  204. package/dist/src/development/MaestroEventDelegate.js +0 -110
  205. package/dist/src/development/TimeSeek.d.ts +0 -22
  206. package/dist/src/development/TimeSeek.js +0 -218
  207. package/dist/src/development/development.d.ts +0 -1
  208. package/dist/src/development/development.js +0 -39
  209. package/dist/src/external/AxiosNetworkClient.d.ts +0 -28
  210. package/dist/src/external/AxiosNetworkClient.js +0 -110
  211. package/dist/src/external/LocalStorageCacheManager.d.ts +0 -65
  212. package/dist/src/external/LocalStorageCacheManager.js +0 -213
  213. package/dist/src/external/ReactRenderer.d.ts +0 -17
  214. package/dist/src/external/ReactRenderer.js +0 -66
  215. package/dist/src/external/mocks/MockExternalNetworkClient.d.ts +0 -104
  216. package/dist/src/external/mocks/MockExternalNetworkClient.js +0 -187
  217. package/dist/src/external/ports/cacheManager.d.ts +0 -17
  218. package/dist/src/external/ports/cacheManager.js +0 -1
  219. package/dist/src/external/ports/networkClient.d.ts +0 -19
  220. package/dist/src/external/ports/networkClient.js +0 -1
  221. package/dist/src/external/ports/renderer.d.ts +0 -4
  222. package/dist/src/external/ports/renderer.js +0 -1
  223. package/dist/src/external/spatial-navigation/__mocks__/withFocusable.d.ts +0 -8
  224. package/dist/src/external/spatial-navigation/__mocks__/withFocusable.js +0 -7
  225. package/dist/src/external/spatial-navigation/index.d.ts +0 -4
  226. package/dist/src/external/spatial-navigation/index.js +0 -3
  227. package/dist/src/external/spatial-navigation/measureLayout.d.ts +0 -2
  228. package/dist/src/external/spatial-navigation/measureLayout.js +0 -30
  229. package/dist/src/external/spatial-navigation/spatialNavigation.d.ts +0 -160
  230. package/dist/src/external/spatial-navigation/spatialNavigation.js +0 -944
  231. package/dist/src/external/spatial-navigation/utils.d.ts +0 -22
  232. package/dist/src/external/spatial-navigation/utils.js +0 -6
  233. package/dist/src/external/spatial-navigation/visualDebugger.d.ts +0 -17
  234. package/dist/src/external/spatial-navigation/visualDebugger.js +0 -76
  235. package/dist/src/external/spatial-navigation/withFocusable.d.ts +0 -131
  236. package/dist/src/external/spatial-navigation/withFocusable.js +0 -254
  237. package/dist/src/helpers/Observable.d.ts +0 -12
  238. package/dist/src/helpers/Observable.js +0 -37
  239. package/dist/src/helpers/site.d.ts +0 -1
  240. package/dist/src/helpers/site.js +0 -6
  241. package/dist/src/helpers/siteConfig.d.ts +0 -1
  242. package/dist/src/helpers/siteConfig.js +0 -5
  243. package/dist/src/helpers/strings.d.ts +0 -2
  244. package/dist/src/helpers/strings.js +0 -14
  245. package/dist/src/helpers/url.d.ts +0 -1
  246. package/dist/src/helpers/url.js +0 -12
  247. package/dist/src/hooks/useMaxHeightToBottom.d.ts +0 -11
  248. package/dist/src/hooks/useMaxHeightToBottom.js +0 -48
  249. package/dist/src/index.d.ts +0 -53
  250. package/dist/src/index.js +0 -197
  251. package/dist/src/interfaces/IMaestroEvent.d.ts +0 -108
  252. package/dist/src/interfaces/IMaestroEvent.js +0 -1
  253. package/dist/src/interfaces/IMaestroEventDelegate.d.ts +0 -81
  254. package/dist/src/interfaces/IMaestroEventDelegate.js +0 -1
  255. package/dist/src/interfaces/IMaestroManager.d.ts +0 -81
  256. package/dist/src/interfaces/IMaestroManager.js +0 -1
  257. package/dist/src/interfaces/IUserSettings.d.ts +0 -44
  258. package/dist/src/interfaces/IUserSettings.js +0 -20
  259. package/dist/src/models/IModel.d.ts +0 -7
  260. package/dist/src/models/IModel.js +0 -1
  261. package/dist/src/models/IPanel.d.ts +0 -19
  262. package/dist/src/models/IPanel.js +0 -12
  263. package/dist/src/models/ITheme.d.ts +0 -77
  264. package/dist/src/models/ITheme.js +0 -20
  265. package/dist/src/modules/espn/bets/interfaces/IBets.d.ts +0 -192
  266. package/dist/src/modules/espn/bets/interfaces/IBets.js +0 -1
  267. package/dist/src/modules/espn/bets/interfaces/IBetsViewModel.d.ts +0 -5
  268. package/dist/src/modules/espn/bets/interfaces/IBetsViewModel.js +0 -1
  269. package/dist/src/modules/espn/bets/mocks.d.ts +0 -2
  270. package/dist/src/modules/espn/bets/mocks.js +0 -573
  271. package/dist/src/modules/espn/bets/services/BetsService.d.ts +0 -81
  272. package/dist/src/modules/espn/bets/services/BetsService.js +0 -123
  273. package/dist/src/modules/espn/bets/types/BetsAnalyticsTypes.d.ts +0 -8
  274. package/dist/src/modules/espn/bets/types/BetsAnalyticsTypes.js +0 -1
  275. package/dist/src/modules/espn/bets/view/BetsView.d.ts +0 -30
  276. package/dist/src/modules/espn/bets/view/BetsView.js +0 -169
  277. package/dist/src/modules/espn/bets/view/HotProps/HotPropsView.d.ts +0 -103
  278. package/dist/src/modules/espn/bets/view/HotProps/HotPropsView.js +0 -133
  279. package/dist/src/modules/espn/bets/view/SixPack/SixPackView.d.ts +0 -9
  280. package/dist/src/modules/espn/bets/view/SixPack/SixPackView.js +0 -77
  281. package/dist/src/modules/espn/bets/view/UserBets/BetResult/BetResult.d.ts +0 -6
  282. package/dist/src/modules/espn/bets/view/UserBets/BetResult/BetResult.js +0 -6
  283. package/dist/src/modules/espn/bets/view/UserBets/BetsCard/BetsCard.d.ts +0 -104
  284. package/dist/src/modules/espn/bets/view/UserBets/BetsCard/BetsCard.js +0 -140
  285. package/dist/src/modules/espn/bets/view/UserBets/BetsCard/BetsCardEvent.d.ts +0 -16
  286. package/dist/src/modules/espn/bets/view/UserBets/BetsCard/BetsCardEvent.js +0 -8
  287. package/dist/src/modules/espn/bets/view/UserBets/BetsCard/BetsCardFooter.d.ts +0 -7
  288. package/dist/src/modules/espn/bets/view/UserBets/BetsCard/BetsCardFooter.js +0 -18
  289. package/dist/src/modules/espn/bets/view/UserBets/Boost/Boost.d.ts +0 -7
  290. package/dist/src/modules/espn/bets/view/UserBets/Boost/Boost.js +0 -6
  291. package/dist/src/modules/espn/bets/view/UserBets/OutcomeBadge/OutcomeBadge.d.ts +0 -6
  292. package/dist/src/modules/espn/bets/view/UserBets/OutcomeBadge/OutcomeBadge.js +0 -9
  293. package/dist/src/modules/espn/bets/view/UserBets/Parlay/Parlay.d.ts +0 -8
  294. package/dist/src/modules/espn/bets/view/UserBets/Parlay/Parlay.js +0 -13
  295. package/dist/src/modules/espn/bets/view/UserBets/Straight/Straight.d.ts +0 -7
  296. package/dist/src/modules/espn/bets/view/UserBets/Straight/Straight.js +0 -6
  297. package/dist/src/modules/espn/bets/view/UserBets/Teaser/Teaser.d.ts +0 -7
  298. package/dist/src/modules/espn/bets/view/UserBets/Teaser/Teaser.js +0 -13
  299. package/dist/src/modules/espn/bets/view/UserBets/UserBetsView.d.ts +0 -25
  300. package/dist/src/modules/espn/bets/view/UserBets/UserBetsView.js +0 -107
  301. package/dist/src/modules/espn/bets/view/components/Bet/Bet.d.ts +0 -10
  302. package/dist/src/modules/espn/bets/view/components/Bet/Bet.js +0 -41
  303. package/dist/src/modules/espn/bets/view/components/BetPill/BetPill.d.ts +0 -6
  304. package/dist/src/modules/espn/bets/view/components/BetPill/BetPill.js +0 -6
  305. package/dist/src/modules/espn/bets/view/components/BetsCard/BetsCard.d.ts +0 -10
  306. package/dist/src/modules/espn/bets/view/components/BetsCard/BetsCard.js +0 -24
  307. package/dist/src/modules/espn/bets/view/components/BetsCard/BetsCardHeader.d.ts +0 -16
  308. package/dist/src/modules/espn/bets/view/components/BetsCard/BetsCardHeader.js +0 -20
  309. package/dist/src/modules/espn/bets/view/components/GamblingDisclaimer/GamblingDisclaimer.d.ts +0 -7
  310. package/dist/src/modules/espn/bets/view/components/GamblingDisclaimer/GamblingDisclaimer.js +0 -31
  311. package/dist/src/modules/espn/bets/view/components/GamblingDisclaimer/index.d.ts +0 -1
  312. package/dist/src/modules/espn/bets/view/components/GamblingDisclaimer/index.js +0 -1
  313. package/dist/src/modules/espn/bets/view/components/LocationWarning/LocationWarning.d.ts +0 -10
  314. package/dist/src/modules/espn/bets/view/components/LocationWarning/LocationWarning.js +0 -16
  315. package/dist/src/modules/espn/bets/view/components/PromoCodeBanner/PromoCodeBanner.d.ts +0 -5
  316. package/dist/src/modules/espn/bets/view/components/PromoCodeBanner/PromoCodeBanner.js +0 -45
  317. package/dist/src/modules/espn/bets/view/components/PromoCodeBanner/index.d.ts +0 -1
  318. package/dist/src/modules/espn/bets/view/components/PromoCodeBanner/index.js +0 -1
  319. package/dist/src/modules/espn/bets/view-model/BetsViewModel.d.ts +0 -218
  320. package/dist/src/modules/espn/bets/view-model/BetsViewModel.js +0 -947
  321. package/dist/src/modules/espn/components/TabLoadError/TabLoadError.d.ts +0 -96
  322. package/dist/src/modules/espn/components/TabLoadError/TabLoadError.js +0 -14
  323. package/dist/src/modules/espn/components/TabLoadError/index.d.ts +0 -2
  324. package/dist/src/modules/espn/components/TabLoadError/index.js +0 -2
  325. package/dist/src/modules/espn/fantasy/components/ExpandedAthleteList/ExpandedAthletesList.d.ts +0 -28
  326. package/dist/src/modules/espn/fantasy/components/ExpandedAthleteList/ExpandedAthletesList.js +0 -107
  327. package/dist/src/modules/espn/fantasy/components/ExpandedAthleteList/index.d.ts +0 -1
  328. package/dist/src/modules/espn/fantasy/components/ExpandedAthleteList/index.js +0 -1
  329. package/dist/src/modules/espn/fantasy/components/LeagueCard/LeagueCard.d.ts +0 -104
  330. package/dist/src/modules/espn/fantasy/components/LeagueCard/LeagueCard.js +0 -20
  331. package/dist/src/modules/espn/fantasy/components/LeagueCard/index.d.ts +0 -2
  332. package/dist/src/modules/espn/fantasy/components/LeagueCard/index.js +0 -2
  333. package/dist/src/modules/espn/fantasy/components/TopPlayerCard/TopPlayerCard.d.ts +0 -101
  334. package/dist/src/modules/espn/fantasy/components/TopPlayerCard/TopPlayerCard.js +0 -29
  335. package/dist/src/modules/espn/fantasy/components/TopPlayerCard/index.d.ts +0 -2
  336. package/dist/src/modules/espn/fantasy/components/TopPlayerCard/index.js +0 -2
  337. package/dist/src/modules/espn/fantasy/components/TournamentOverflowQR/TournamentOverflowQR.d.ts +0 -103
  338. package/dist/src/modules/espn/fantasy/components/TournamentOverflowQR/TournamentOverflowQR.js +0 -28
  339. package/dist/src/modules/espn/fantasy/components/TournamentOverflowQR/index.d.ts +0 -1
  340. package/dist/src/modules/espn/fantasy/components/TournamentOverflowQR/index.js +0 -1
  341. package/dist/src/modules/espn/fantasy/mocks.d.ts +0 -7620
  342. package/dist/src/modules/espn/fantasy/mocks.js +0 -3682
  343. package/dist/src/modules/espn/fantasy/services/FantasyService.d.ts +0 -76
  344. package/dist/src/modules/espn/fantasy/services/FantasyService.js +0 -124
  345. package/dist/src/modules/espn/fantasy/types.d.ts +0 -294
  346. package/dist/src/modules/espn/fantasy/types.js +0 -9
  347. package/dist/src/modules/espn/fantasy/view/ActiveAthletesMarquee/ActiveAthletesMarquee.d.ts +0 -21
  348. package/dist/src/modules/espn/fantasy/view/ActiveAthletesMarquee/ActiveAthletesMarquee.js +0 -74
  349. package/dist/src/modules/espn/fantasy/view/ActiveAthletesMarquee/index.d.ts +0 -2
  350. package/dist/src/modules/espn/fantasy/view/ActiveAthletesMarquee/index.js +0 -2
  351. package/dist/src/modules/espn/fantasy/view/FantasyHeaderView.d.ts +0 -8
  352. package/dist/src/modules/espn/fantasy/view/FantasyHeaderView.js +0 -8
  353. package/dist/src/modules/espn/fantasy/view/FantasyItemView.d.ts +0 -8
  354. package/dist/src/modules/espn/fantasy/view/FantasyItemView.js +0 -48
  355. package/dist/src/modules/espn/fantasy/view/FantasyView.d.ts +0 -34
  356. package/dist/src/modules/espn/fantasy/view/FantasyView.js +0 -212
  357. package/dist/src/modules/espn/fantasy/view/InactiveLeague/DraftDateCountdown.d.ts +0 -23
  358. package/dist/src/modules/espn/fantasy/view/InactiveLeague/DraftDateCountdown.js +0 -95
  359. package/dist/src/modules/espn/fantasy/view/InactiveLeague/InactiveLeague.d.ts +0 -100
  360. package/dist/src/modules/espn/fantasy/view/InactiveLeague/InactiveLeague.js +0 -13
  361. package/dist/src/modules/espn/fantasy/view/InactiveLeague/index.d.ts +0 -2
  362. package/dist/src/modules/espn/fantasy/view/InactiveLeague/index.js +0 -2
  363. package/dist/src/modules/espn/fantasy/view/LoginView/LoginView.d.ts +0 -96
  364. package/dist/src/modules/espn/fantasy/view/LoginView/LoginView.js +0 -27
  365. package/dist/src/modules/espn/fantasy/view/LoginView/index.d.ts +0 -2
  366. package/dist/src/modules/espn/fantasy/view/LoginView/index.js +0 -2
  367. package/dist/src/modules/espn/fantasy/view/MatchupPair/DoubleAthleteCard/DoubleAthleteCard.d.ts +0 -97
  368. package/dist/src/modules/espn/fantasy/view/MatchupPair/DoubleAthleteCard/DoubleAthleteCard.js +0 -25
  369. package/dist/src/modules/espn/fantasy/view/MatchupPair/DoubleAthleteCard/index.d.ts +0 -2
  370. package/dist/src/modules/espn/fantasy/view/MatchupPair/DoubleAthleteCard/index.js +0 -2
  371. package/dist/src/modules/espn/fantasy/view/MatchupPair/ExpandedDoubleAthleteCards.d.ts +0 -14
  372. package/dist/src/modules/espn/fantasy/view/MatchupPair/ExpandedDoubleAthleteCards.js +0 -9
  373. package/dist/src/modules/espn/fantasy/view/MatchupPair/MatchupPair.d.ts +0 -102
  374. package/dist/src/modules/espn/fantasy/view/MatchupPair/MatchupPair.js +0 -118
  375. package/dist/src/modules/espn/fantasy/view/MatchupPair/index.d.ts +0 -2
  376. package/dist/src/modules/espn/fantasy/view/MatchupPair/index.js +0 -2
  377. package/dist/src/modules/espn/fantasy/view/MatchupSingle/ExpandedSingleAthleteCards.d.ts +0 -14
  378. package/dist/src/modules/espn/fantasy/view/MatchupSingle/ExpandedSingleAthleteCards.js +0 -9
  379. package/dist/src/modules/espn/fantasy/view/MatchupSingle/MatchupSingle.d.ts +0 -102
  380. package/dist/src/modules/espn/fantasy/view/MatchupSingle/MatchupSingle.js +0 -108
  381. package/dist/src/modules/espn/fantasy/view/MatchupSingle/SingleAthleteCard/SingleAthleteCard.d.ts +0 -97
  382. package/dist/src/modules/espn/fantasy/view/MatchupSingle/SingleAthleteCard/SingleAthleteCard.js +0 -18
  383. package/dist/src/modules/espn/fantasy/view/MatchupSingle/SingleAthleteCard/index.d.ts +0 -2
  384. package/dist/src/modules/espn/fantasy/view/MatchupSingle/SingleAthleteCard/index.js +0 -2
  385. package/dist/src/modules/espn/fantasy/view/MatchupSingle/index.d.ts +0 -2
  386. package/dist/src/modules/espn/fantasy/view/MatchupSingle/index.js +0 -2
  387. package/dist/src/modules/espn/fantasy/view/PromoView/PromoView.d.ts +0 -100
  388. package/dist/src/modules/espn/fantasy/view/PromoView/PromoView.js +0 -12
  389. package/dist/src/modules/espn/fantasy/view/PromoView/index.d.ts +0 -2
  390. package/dist/src/modules/espn/fantasy/view/PromoView/index.js +0 -2
  391. package/dist/src/modules/espn/fantasy/view/TournamentBracketCard/TournamentBracketCard.d.ts +0 -101
  392. package/dist/src/modules/espn/fantasy/view/TournamentBracketCard/TournamentBracketCard.js +0 -37
  393. package/dist/src/modules/espn/fantasy/view/TournamentBracketCard/index.d.ts +0 -2
  394. package/dist/src/modules/espn/fantasy/view/TournamentBracketCard/index.js +0 -2
  395. package/dist/src/modules/espn/fantasy/view/index.d.ts +0 -2
  396. package/dist/src/modules/espn/fantasy/view/index.js +0 -2
  397. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.FantasyPolling.d.ts +0 -32
  398. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.FantasyPolling.js +0 -132
  399. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.LeagueManagerPolling.d.ts +0 -32
  400. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.LeagueManagerPolling.js +0 -141
  401. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.TournamentPolling.d.ts +0 -32
  402. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.TournamentPolling.js +0 -140
  403. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.d.ts +0 -167
  404. package/dist/src/modules/espn/fantasy/view-model/FantasyViewModel.js +0 -805
  405. package/dist/src/modules/espn/key-plays/constants.d.ts +0 -3
  406. package/dist/src/modules/espn/key-plays/constants.js +0 -292
  407. package/dist/src/modules/espn/key-plays/interfaces/IKeyPlays.d.ts +0 -32
  408. package/dist/src/modules/espn/key-plays/interfaces/IKeyPlays.js +0 -14
  409. package/dist/src/modules/espn/key-plays/interfaces/IKeyPlaysResponse.d.ts +0 -44
  410. package/dist/src/modules/espn/key-plays/interfaces/IKeyPlaysResponse.js +0 -1
  411. package/dist/src/modules/espn/key-plays/interfaces/IKeyPlaysViewModel.d.ts +0 -17
  412. package/dist/src/modules/espn/key-plays/interfaces/IKeyPlaysViewModel.js +0 -1
  413. package/dist/src/modules/espn/key-plays/view/KeyPlayCardScoreTagView.d.ts +0 -9
  414. package/dist/src/modules/espn/key-plays/view/KeyPlayCardScoreTagView.js +0 -16
  415. package/dist/src/modules/espn/key-plays/view/KeyPlayCardView.d.ts +0 -27
  416. package/dist/src/modules/espn/key-plays/view/KeyPlayCardView.js +0 -115
  417. package/dist/src/modules/espn/key-plays/view/KeyPlayErrorStateView.d.ts +0 -13
  418. package/dist/src/modules/espn/key-plays/view/KeyPlayErrorStateView.js +0 -65
  419. package/dist/src/modules/espn/key-plays/view/KeyPlaysView.d.ts +0 -39
  420. package/dist/src/modules/espn/key-plays/view/KeyPlaysView.js +0 -179
  421. package/dist/src/modules/espn/key-plays/view-model/KeyPlaysViewModel.d.ts +0 -37
  422. package/dist/src/modules/espn/key-plays/view-model/KeyPlaysViewModel.js +0 -245
  423. package/dist/src/modules/espn/shop/mocks.d.ts +0 -22
  424. package/dist/src/modules/espn/shop/mocks.js +0 -391
  425. package/dist/src/modules/espn/shop/services/ShopService.d.ts +0 -23
  426. package/dist/src/modules/espn/shop/services/ShopService.js +0 -44
  427. package/dist/src/modules/espn/shop/types.d.ts +0 -164
  428. package/dist/src/modules/espn/shop/types.js +0 -7
  429. package/dist/src/modules/espn/shop/view/ProductDetailView/ProductDetailView.d.ts +0 -10
  430. package/dist/src/modules/espn/shop/view/ProductDetailView/ProductDetailView.js +0 -60
  431. package/dist/src/modules/espn/shop/view/ProductDetailView/index.d.ts +0 -2
  432. package/dist/src/modules/espn/shop/view/ProductDetailView/index.js +0 -2
  433. package/dist/src/modules/espn/shop/view/ShopView.d.ts +0 -38
  434. package/dist/src/modules/espn/shop/view/ShopView.js +0 -223
  435. package/dist/src/modules/espn/shop/view/components/BrowseCard/BrowseCard.d.ts +0 -103
  436. package/dist/src/modules/espn/shop/view/components/BrowseCard/BrowseCard.js +0 -23
  437. package/dist/src/modules/espn/shop/view/components/BrowseCard/index.d.ts +0 -2
  438. package/dist/src/modules/espn/shop/view/components/BrowseCard/index.js +0 -2
  439. package/dist/src/modules/espn/shop/view/components/ProductSummaryCard/ProductSummaryCard.d.ts +0 -104
  440. package/dist/src/modules/espn/shop/view/components/ProductSummaryCard/ProductSummaryCard.js +0 -26
  441. package/dist/src/modules/espn/shop/view/components/ProductSummaryCard/index.d.ts +0 -2
  442. package/dist/src/modules/espn/shop/view/components/ProductSummaryCard/index.js +0 -1
  443. package/dist/src/modules/espn/shop/view/components/ShopPromoView/ShopPromoView.d.ts +0 -8
  444. package/dist/src/modules/espn/shop/view/components/ShopPromoView/ShopPromoView.js +0 -19
  445. package/dist/src/modules/espn/shop/view/components/ShopPromoView/index.d.ts +0 -1
  446. package/dist/src/modules/espn/shop/view/components/ShopPromoView/index.js +0 -1
  447. package/dist/src/modules/espn/shop/view/components/ShopSection/ShopSection.d.ts +0 -12
  448. package/dist/src/modules/espn/shop/view/components/ShopSection/ShopSection.js +0 -34
  449. package/dist/src/modules/espn/shop/view/components/ShopSection/index.d.ts +0 -1
  450. package/dist/src/modules/espn/shop/view/components/ShopSection/index.js +0 -1
  451. package/dist/src/modules/espn/shop/view/index.d.ts +0 -2
  452. package/dist/src/modules/espn/shop/view/index.js +0 -2
  453. package/dist/src/modules/espn/shop/view-model/ShopViewModel.ShopPolling.d.ts +0 -31
  454. package/dist/src/modules/espn/shop/view-model/ShopViewModel.ShopPolling.js +0 -111
  455. package/dist/src/modules/espn/shop/view-model/ShopViewModel.d.ts +0 -73
  456. package/dist/src/modules/espn/shop/view-model/ShopViewModel.js +0 -323
  457. package/dist/src/modules/espn/stats/components/TeamStatistic.d.ts +0 -16
  458. package/dist/src/modules/espn/stats/components/TeamStatistic.js +0 -13
  459. package/dist/src/modules/espn/stats/interfaces/IStats.d.ts +0 -330
  460. package/dist/src/modules/espn/stats/interfaces/IStats.js +0 -46
  461. package/dist/src/modules/espn/stats/interfaces/IStatsViewModel.d.ts +0 -7
  462. package/dist/src/modules/espn/stats/interfaces/IStatsViewModel.js +0 -1
  463. package/dist/src/modules/espn/stats/mocks.d.ts +0 -2
  464. package/dist/src/modules/espn/stats/mocks.js +0 -746
  465. package/dist/src/modules/espn/stats/services/StatsService.d.ts +0 -54
  466. package/dist/src/modules/espn/stats/services/StatsService.js +0 -155
  467. package/dist/src/modules/espn/stats/utils/driveSummaryUtils.d.ts +0 -18
  468. package/dist/src/modules/espn/stats/utils/driveSummaryUtils.js +0 -48
  469. package/dist/src/modules/espn/stats/utils/playerStatusUtils.d.ts +0 -4
  470. package/dist/src/modules/espn/stats/utils/playerStatusUtils.js +0 -17
  471. package/dist/src/modules/espn/stats/utils.d.ts +0 -39
  472. package/dist/src/modules/espn/stats/utils.js +0 -62
  473. package/dist/src/modules/espn/stats/view/ActiveAthletes/ActiveAthletes.d.ts +0 -22
  474. package/dist/src/modules/espn/stats/view/ActiveAthletes/ActiveAthletes.js +0 -98
  475. package/dist/src/modules/espn/stats/view/ActiveAthletes/CollapsedAthletes/CollapsedAthletes.d.ts +0 -4
  476. package/dist/src/modules/espn/stats/view/ActiveAthletes/CollapsedAthletes/CollapsedAthletes.js +0 -27
  477. package/dist/src/modules/espn/stats/view/ActiveAthletes/ExpandedAthletes/ExpandedAthletes.d.ts +0 -22
  478. package/dist/src/modules/espn/stats/view/ActiveAthletes/ExpandedAthletes/ExpandedAthletes.js +0 -89
  479. package/dist/src/modules/espn/stats/view/ActiveAthletes/index.d.ts +0 -2
  480. package/dist/src/modules/espn/stats/view/ActiveAthletes/index.js +0 -2
  481. package/dist/src/modules/espn/stats/view/CareerMatchup/CareerMatchup.d.ts +0 -101
  482. package/dist/src/modules/espn/stats/view/CareerMatchup/CareerMatchup.js +0 -59
  483. package/dist/src/modules/espn/stats/view/CareerMatchup/index.d.ts +0 -1
  484. package/dist/src/modules/espn/stats/view/CareerMatchup/index.js +0 -1
  485. package/dist/src/modules/espn/stats/view/DriveSummary/DrivePlayCard.d.ts +0 -105
  486. package/dist/src/modules/espn/stats/view/DriveSummary/DrivePlayCard.js +0 -32
  487. package/dist/src/modules/espn/stats/view/DriveSummary/DriveSummary.d.ts +0 -10
  488. package/dist/src/modules/espn/stats/view/DriveSummary/DriveSummary.js +0 -40
  489. package/dist/src/modules/espn/stats/view/DriveSummary/ExpandedItems/DriveSummaryExpanded.d.ts +0 -27
  490. package/dist/src/modules/espn/stats/view/DriveSummary/ExpandedItems/DriveSummaryExpanded.js +0 -129
  491. package/dist/src/modules/espn/stats/view/DriveSummary/Header/DriveSummaryHeader.d.ts +0 -12
  492. package/dist/src/modules/espn/stats/view/DriveSummary/Header/DriveSummaryHeader.js +0 -26
  493. package/dist/src/modules/espn/stats/view/DriveSummary/MainStat/MainStat.d.ts +0 -10
  494. package/dist/src/modules/espn/stats/view/DriveSummary/MainStat/MainStat.js +0 -24
  495. package/dist/src/modules/espn/stats/view/DriveSummary/index.d.ts +0 -2
  496. package/dist/src/modules/espn/stats/view/DriveSummary/index.js +0 -2
  497. package/dist/src/modules/espn/stats/view/GameLeaders/GameLeaders.d.ts +0 -9
  498. package/dist/src/modules/espn/stats/view/GameLeaders/GameLeaders.js +0 -22
  499. package/dist/src/modules/espn/stats/view/GameLeaders/index.d.ts +0 -2
  500. package/dist/src/modules/espn/stats/view/GameLeaders/index.js +0 -2
  501. package/dist/src/modules/espn/stats/view/MatchPredictor/DonutChart/DonutChart.d.ts +0 -17
  502. package/dist/src/modules/espn/stats/view/MatchPredictor/DonutChart/DonutChart.js +0 -55
  503. package/dist/src/modules/espn/stats/view/MatchPredictor/DonutChart/index.d.ts +0 -2
  504. package/dist/src/modules/espn/stats/view/MatchPredictor/DonutChart/index.js +0 -1
  505. package/dist/src/modules/espn/stats/view/MatchPredictor/MatchPredictorView.d.ts +0 -100
  506. package/dist/src/modules/espn/stats/view/MatchPredictor/MatchPredictorView.js +0 -60
  507. package/dist/src/modules/espn/stats/view/MatchPredictor/index.d.ts +0 -3
  508. package/dist/src/modules/espn/stats/view/MatchPredictor/index.js +0 -2
  509. package/dist/src/modules/espn/stats/view/Penalties/Penalties.d.ts +0 -9
  510. package/dist/src/modules/espn/stats/view/Penalties/Penalties.js +0 -6
  511. package/dist/src/modules/espn/stats/view/Penalties/index.d.ts +0 -2
  512. package/dist/src/modules/espn/stats/view/Penalties/index.js +0 -2
  513. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/ExpandedPlayerStats.d.ts +0 -16
  514. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/ExpandedPlayerStats.js +0 -66
  515. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/PlayerSeasonStatsCard.d.ts +0 -99
  516. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/PlayerSeasonStatsCard.js +0 -26
  517. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/PlayerSeasonStatsMinified.d.ts +0 -6
  518. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/PlayerSeasonStatsMinified.js +0 -17
  519. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/PlayerSeasonStatsView.d.ts +0 -8
  520. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/PlayerSeasonStatsView.js +0 -165
  521. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/index.d.ts +0 -1
  522. package/dist/src/modules/espn/stats/view/PlayerSeasonStats/index.js +0 -1
  523. package/dist/src/modules/espn/stats/view/RecentGames/RecentGames.d.ts +0 -100
  524. package/dist/src/modules/espn/stats/view/RecentGames/RecentGames.js +0 -23
  525. package/dist/src/modules/espn/stats/view/RecentGames/index.d.ts +0 -2
  526. package/dist/src/modules/espn/stats/view/RecentGames/index.js +0 -2
  527. package/dist/src/modules/espn/stats/view/ScoringSummary/ExpandedScores/ExpandedScores.d.ts +0 -30
  528. package/dist/src/modules/espn/stats/view/ScoringSummary/ExpandedScores/ExpandedScores.js +0 -123
  529. package/dist/src/modules/espn/stats/view/ScoringSummary/ExpandedScores/ExpandedSummary.d.ts +0 -100
  530. package/dist/src/modules/espn/stats/view/ScoringSummary/ExpandedScores/ExpandedSummary.js +0 -24
  531. package/dist/src/modules/espn/stats/view/ScoringSummary/ExpandedScores/index.d.ts +0 -2
  532. package/dist/src/modules/espn/stats/view/ScoringSummary/ExpandedScores/index.js +0 -2
  533. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoreItem/ScoreItem.d.ts +0 -100
  534. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoreItem/ScoreItem.js +0 -62
  535. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoreItem/index.d.ts +0 -2
  536. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoreItem/index.js +0 -2
  537. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoresSection/ScoresSection.d.ts +0 -6
  538. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoresSection/ScoresSection.js +0 -23
  539. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoresSection/index.d.ts +0 -2
  540. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoresSection/index.js +0 -2
  541. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoringSummary.d.ts +0 -12
  542. package/dist/src/modules/espn/stats/view/ScoringSummary/ScoringSummary.js +0 -167
  543. package/dist/src/modules/espn/stats/view/ScoringSummary/index.d.ts +0 -1
  544. package/dist/src/modules/espn/stats/view/ScoringSummary/index.js +0 -1
  545. package/dist/src/modules/espn/stats/view/StatsItemView.d.ts +0 -8
  546. package/dist/src/modules/espn/stats/view/StatsItemView.js +0 -66
  547. package/dist/src/modules/espn/stats/view/StatsQRCode/StatsQRCodeView.d.ts +0 -100
  548. package/dist/src/modules/espn/stats/view/StatsQRCode/StatsQRCodeView.js +0 -36
  549. package/dist/src/modules/espn/stats/view/StatsQRCode/index.d.ts +0 -2
  550. package/dist/src/modules/espn/stats/view/StatsQRCode/index.js +0 -1
  551. package/dist/src/modules/espn/stats/view/StatsView.d.ts +0 -29
  552. package/dist/src/modules/espn/stats/view/StatsView.js +0 -164
  553. package/dist/src/modules/espn/stats/view/TeamStats/TeamStatsView.d.ts +0 -101
  554. package/dist/src/modules/espn/stats/view/TeamStats/TeamStatsView.js +0 -77
  555. package/dist/src/modules/espn/stats/view/TeamStats/index.d.ts +0 -2
  556. package/dist/src/modules/espn/stats/view/TeamStats/index.js +0 -1
  557. package/dist/src/modules/espn/stats/view/Teams/StatsCarousel.d.ts +0 -25
  558. package/dist/src/modules/espn/stats/view/Teams/StatsCarousel.js +0 -83
  559. package/dist/src/modules/espn/stats/view/Teams/StatsProgressBar.d.ts +0 -6
  560. package/dist/src/modules/espn/stats/view/Teams/StatsProgressBar.js +0 -19
  561. package/dist/src/modules/espn/stats/view/Teams/Teams.d.ts +0 -100
  562. package/dist/src/modules/espn/stats/view/Teams/Teams.js +0 -39
  563. package/dist/src/modules/espn/stats/view/Teams/index.d.ts +0 -2
  564. package/dist/src/modules/espn/stats/view/Teams/index.js +0 -2
  565. package/dist/src/modules/espn/stats/view/WinProbability/WinProbability.d.ts +0 -100
  566. package/dist/src/modules/espn/stats/view/WinProbability/WinProbability.js +0 -28
  567. package/dist/src/modules/espn/stats/view/WinProbability/index.d.ts +0 -2
  568. package/dist/src/modules/espn/stats/view/WinProbability/index.js +0 -2
  569. package/dist/src/modules/espn/stats/view/components/AthletesStatistics/AthletesStatistics.d.ts +0 -115
  570. package/dist/src/modules/espn/stats/view/components/AthletesStatistics/AthletesStatistics.js +0 -89
  571. package/dist/src/modules/espn/stats/view/components/AthletesStatistics/StatisticTable.d.ts +0 -3
  572. package/dist/src/modules/espn/stats/view/components/AthletesStatistics/StatisticTable.js +0 -12
  573. package/dist/src/modules/espn/stats/view/components/AthletesStatistics/index.d.ts +0 -2
  574. package/dist/src/modules/espn/stats/view/components/AthletesStatistics/index.js +0 -2
  575. package/dist/src/modules/espn/stats/view/index.d.ts +0 -2
  576. package/dist/src/modules/espn/stats/view/index.js +0 -2
  577. package/dist/src/modules/espn/stats/view-model/StatsViewModel.d.ts +0 -322
  578. package/dist/src/modules/espn/stats/view-model/StatsViewModel.js +0 -1416
  579. package/dist/src/modules/fox/components/TabLoadError/TabLoadError.d.ts +0 -96
  580. package/dist/src/modules/fox/components/TabLoadError/TabLoadError.js +0 -19
  581. package/dist/src/modules/fox/components/TabLoadError/index.d.ts +0 -2
  582. package/dist/src/modules/fox/components/TabLoadError/index.js +0 -2
  583. package/dist/src/modules/fox/key-plays/view/FoxKeyPlays.d.ts +0 -2
  584. package/dist/src/modules/fox/key-plays/view/FoxKeyPlays.js +0 -5
  585. package/dist/src/modules/fox/multi-view/interfaces/IMultiViewViewModel.d.ts +0 -3
  586. package/dist/src/modules/fox/multi-view/interfaces/IMultiViewViewModel.js +0 -1
  587. package/dist/src/modules/fox/multi-view/services/MultiViewService.d.ts +0 -99
  588. package/dist/src/modules/fox/multi-view/services/MultiViewService.js +0 -94
  589. package/dist/src/modules/fox/multi-view/types.d.ts +0 -48
  590. package/dist/src/modules/fox/multi-view/types.js +0 -86
  591. package/dist/src/modules/fox/multi-view/view/CuratedMultiview/CuratedMultiviews.d.ts +0 -8
  592. package/dist/src/modules/fox/multi-view/view/CuratedMultiview/CuratedMultiviews.js +0 -91
  593. package/dist/src/modules/fox/multi-view/view/CuratedMultiview/index.d.ts +0 -2
  594. package/dist/src/modules/fox/multi-view/view/CuratedMultiview/index.js +0 -2
  595. package/dist/src/modules/fox/multi-view/view/FoxMultiView.d.ts +0 -3
  596. package/dist/src/modules/fox/multi-view/view/FoxMultiView.js +0 -65
  597. package/dist/src/modules/fox/multi-view/view/components/CustomMultiviewStreamsCard/CustomMultiviewStreamsCard.d.ts +0 -122
  598. package/dist/src/modules/fox/multi-view/view/components/CustomMultiviewStreamsCard/CustomMultiviewStreamsCard.js +0 -51
  599. package/dist/src/modules/fox/multi-view/view/components/CustomMultiviewStreamsCard/index.d.ts +0 -2
  600. package/dist/src/modules/fox/multi-view/view/components/CustomMultiviewStreamsCard/index.js +0 -2
  601. package/dist/src/modules/fox/multi-view/view/components/LayoutSelector/LayoutSelector.d.ts +0 -13
  602. package/dist/src/modules/fox/multi-view/view/components/LayoutSelector/LayoutSelector.js +0 -40
  603. package/dist/src/modules/fox/multi-view/view/components/LayoutSelector/index.d.ts +0 -2
  604. package/dist/src/modules/fox/multi-view/view/components/LayoutSelector/index.js +0 -2
  605. package/dist/src/modules/fox/multi-view/view/components/curated-multiview-card/CuratedMultiviewCard.d.ts +0 -101
  606. package/dist/src/modules/fox/multi-view/view/components/curated-multiview-card/CuratedMultiviewCard.js +0 -21
  607. package/dist/src/modules/fox/multi-view/view/components/curated-multiview-card/index.d.ts +0 -2
  608. package/dist/src/modules/fox/multi-view/view/components/curated-multiview-card/index.js +0 -2
  609. package/dist/src/modules/fox/multi-view/view-model/MultiViewViewModel.d.ts +0 -63
  610. package/dist/src/modules/fox/multi-view/view-model/MultiViewViewModel.js +0 -328
  611. package/dist/src/modules/fox/multi-view/view-model/index.d.ts +0 -1
  612. package/dist/src/modules/fox/multi-view/view-model/index.js +0 -1
  613. package/dist/src/modules/fox/stats/view/FoxStatsView.d.ts +0 -2
  614. package/dist/src/modules/fox/stats/view/FoxStatsView.js +0 -5
  615. package/dist/src/modules/maestro/builder/components/BuilderSection/BuilderSection.d.ts +0 -11
  616. package/dist/src/modules/maestro/builder/components/BuilderSection/BuilderSection.js +0 -52
  617. package/dist/src/modules/maestro/builder/components/BuilderSection/index.d.ts +0 -2
  618. package/dist/src/modules/maestro/builder/components/BuilderSection/index.js +0 -2
  619. package/dist/src/modules/maestro/builder/components/ExpandableCard/ExpandableCard.d.ts +0 -110
  620. package/dist/src/modules/maestro/builder/components/ExpandableCard/ExpandableCard.js +0 -37
  621. package/dist/src/modules/maestro/builder/components/ExpandableCard/index.d.ts +0 -2
  622. package/dist/src/modules/maestro/builder/components/ExpandableCard/index.js +0 -2
  623. package/dist/src/modules/maestro/builder/components/SimpleCard/SimpleCard.d.ts +0 -104
  624. package/dist/src/modules/maestro/builder/components/SimpleCard/SimpleCard.js +0 -12
  625. package/dist/src/modules/maestro/builder/components/SimpleCard/index.d.ts +0 -2
  626. package/dist/src/modules/maestro/builder/components/SimpleCard/index.js +0 -2
  627. package/dist/src/modules/maestro/builder/index.d.ts +0 -7
  628. package/dist/src/modules/maestro/builder/index.js +0 -7
  629. package/dist/src/modules/maestro/builder/mocks/mockBuilderPanel.d.ts +0 -149
  630. package/dist/src/modules/maestro/builder/mocks/mockBuilderPanel.js +0 -240
  631. package/dist/src/modules/maestro/builder/types.d.ts +0 -52
  632. package/dist/src/modules/maestro/builder/types.js +0 -1
  633. package/dist/src/modules/maestro/builder/view/BuilderPanelView.d.ts +0 -4
  634. package/dist/src/modules/maestro/builder/view/BuilderPanelView.js +0 -52
  635. package/dist/src/modules/maestro/builder/view-model/BuilderPanelViewModel.d.ts +0 -40
  636. package/dist/src/modules/maestro/builder/view-model/BuilderPanelViewModel.js +0 -229
  637. package/dist/src/modules/maestro/builder/view-model/index.d.ts +0 -1
  638. package/dist/src/modules/maestro/builder/view-model/index.js +0 -1
  639. package/dist/src/modules/maestro/hello-world/HelloWorldImage.d.ts +0 -2
  640. package/dist/src/modules/maestro/hello-world/HelloWorldImage.js +0 -32
  641. package/dist/src/modules/maestro/hello-world/HelloWorldView.d.ts +0 -11
  642. package/dist/src/modules/maestro/hello-world/HelloWorldView.js +0 -40
  643. package/dist/src/modules/maestro/hello-world/index.d.ts +0 -2
  644. package/dist/src/modules/maestro/hello-world/index.js +0 -2
  645. package/dist/src/sentry.d.ts +0 -3
  646. package/dist/src/sentry.js +0 -51
  647. package/dist/src/services/AnalyticsService/AnalyticsService.d.ts +0 -85
  648. package/dist/src/services/AnalyticsService/AnalyticsService.js +0 -406
  649. package/dist/src/services/AnalyticsService/types.d.ts +0 -65
  650. package/dist/src/services/AnalyticsService/types.js +0 -1
  651. package/dist/src/services/InsightsService/InsightsPayloadBuilder.d.ts +0 -279
  652. package/dist/src/services/InsightsService/InsightsPayloadBuilder.js +0 -385
  653. package/dist/src/services/InsightsService/InsightsService.d.ts +0 -11
  654. package/dist/src/services/InsightsService/InsightsService.js +0 -74
  655. package/dist/src/services/NetworkManager/NetworkManager.d.ts +0 -153
  656. package/dist/src/services/NetworkManager/NetworkManager.js +0 -434
  657. package/dist/src/services/NetworkManager/errors.d.ts +0 -19
  658. package/dist/src/services/NetworkManager/errors.js +0 -59
  659. package/dist/src/services/NetworkManager/types.d.ts +0 -7
  660. package/dist/src/services/NetworkManager/types.js +0 -1
  661. package/dist/src/services/StaticService/StaticService.d.ts +0 -20
  662. package/dist/src/services/StaticService/StaticService.js +0 -86
  663. package/dist/src/services/StaticService/index.d.ts +0 -2
  664. package/dist/src/services/StaticService/index.js +0 -2
  665. package/dist/src/services/StaticService/mocks.d.ts +0 -3
  666. package/dist/src/services/StaticService/mocks.js +0 -119
  667. package/dist/src/services/StaticService/types.d.ts +0 -78
  668. package/dist/src/services/StaticService/types.js +0 -1
  669. package/dist/src/services/ThemeManager/constants.d.ts +0 -2
  670. package/dist/src/services/ThemeManager/constants.js +0 -47
  671. package/dist/src/services/UserSettingsManager.d.ts +0 -63
  672. package/dist/src/services/UserSettingsManager.js +0 -158
  673. package/dist/src/test-polyfills.d.ts +0 -1
  674. package/dist/src/test-polyfills.js +0 -15
  675. package/dist/src/view-models/MaestroEventViewModel.d.ts +0 -96
  676. package/dist/src/view-models/MaestroEventViewModel.js +0 -386
  677. package/dist/src/view-models/PanelManagerViewModel.d.ts +0 -49
  678. package/dist/src/view-models/PanelManagerViewModel.js +0 -195
  679. package/dist/src/view-models/ViewModel.d.ts +0 -12
  680. package/dist/src/view-models/ViewModel.js +0 -32
@@ -1 +0,0 @@
1
- {"version":3,"sources":["webpack:///../../src/worldwide.ts","webpack:///../../src/is.ts","webpack:///../../src/object.ts","webpack:///../../src/debug-build.ts","webpack:///../../src/logger.ts","webpack:///../../src/string.ts","webpack:///(webpack)/buildin/harmony-module.js","webpack:///../../src/stacktrace.ts","webpack:///../../src/browser.ts","webpack:///../../src/time.ts","webpack:///../../src/node.ts","webpack:///../../src/env.ts","webpack:///../../src/normalize.ts","webpack:///../../src/memo.ts","webpack:///./node_modules/lodash.debounce/index.js","webpack:///../../../src/integrations/functiontostring.ts","webpack:///../../src/misc.ts","webpack:///../../../src/integrations/inboundfilters.ts","webpack:///../../src/constants.ts","webpack:///../../src/syncpromise.ts","webpack:///../../src/session.ts","webpack:///../../src/scope.ts","webpack:///../../src/hub.ts","webpack:///../../src/dsn.ts","webpack:///../../src/envelope.ts","webpack:///../../src/metadata.ts","webpack:///../../../src/integrations/metadata.ts","webpack:///../../src/version.ts","webpack:///../../src/exports.ts","webpack:///../../../src/utils/hasTracingEnabled.ts","webpack:///../../src/supports.ts","webpack:///../../../src/vendor/supportsHistory.ts","webpack:///../../src/instrument.ts","webpack:///../../../src/tracing/utils.ts","webpack:///../../../src/tracing/errors.ts","webpack:///../../src/baggage.ts","webpack:///../../src/tracing.ts","webpack:///../../../src/tracing/span.ts","webpack:///../../../src/tracing/dynamicSamplingContext.ts","webpack:///../../../src/tracing/transaction.ts","webpack:///../../../src/tracing/idletransaction.ts","webpack:///../../../src/tracing/hubextensions.ts","webpack:///../../src/error.ts","webpack:///../../src/promisebuffer.ts","webpack:///../../src/ratelimit.ts","webpack:///../../../src/transports/base.ts","webpack:///../../src/api.ts","webpack:///../../../src/transports/multiplexed.ts","webpack:///../../../src/tracing/measurement.ts","webpack:///../../../src/tracing/trace.ts","webpack:///../../../src/helpers.ts","webpack:///../../src/integration.ts","webpack:///../../../src/utils/prepareEvent.ts","webpack:///../../src/baseclient.ts","webpack:///../../../src/eventbuilder.ts","webpack:///../../../src/userfeedback.ts","webpack:///../../../src/client.ts","webpack:///../../src/clientreport.ts","webpack:///../../../../src/transports/utils.ts","webpack:///../../../../src/transports/fetch.ts","webpack:///../../../../src/transports/xhr.ts","webpack:///../../../src/stack-parsers.ts","webpack:///../../../../src/integrations/globalhandlers.ts","webpack:///../../../../src/integrations/trycatch.ts","webpack:///../../src/severity.ts","webpack:///../../src/url.ts","webpack:///../../../../src/integrations/breadcrumbs.ts","webpack:///../../src/aggregate-errors.ts","webpack:///../../../../src/integrations/linkederrors.ts","webpack:///../../../../src/integrations/httpcontext.ts","webpack:///../../../../src/integrations/dedupe.ts","webpack:///../../../src/sdk.ts","webpack:///../../src/sdk.ts","webpack:///../../src/eventProcessors.ts","webpack:///../../../src/utils/spanUtils.ts","webpack:///../../../src/utils/getRootSpan.ts","webpack:///../../../src/utils/applyScopeDataToEvent.ts","webpack:///../../../src/instrument/_handlers.ts","webpack:///../../../src/instrument/console.ts","webpack:///../../../src/instrument/dom.ts","webpack:///../../../src/instrument/fetch.ts","webpack:///../../../src/instrument/globalError.ts","webpack:///../../../src/instrument/globalUnhandledRejection.ts","webpack:///../../../src/instrument/history.ts","webpack:///../../../src/instrument/xhr.ts","webpack:///../../../src/instrument/index.ts","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb-snapshot/es/rrweb-snapshot.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/ext/tslib/tslib.es6.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/types.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/utils.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/mutation.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observer.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/iframe-manager.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/shadow-dom-manager.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/2d.js","webpack:///./node_modules/rrweb/es/rrweb/ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/serialize-args.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/webgl.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/index.js","webpack:///./node_modules/rrweb/es/rrweb/packages/rrweb/src/record/observers/canvas/canvas-manager.js","webpack:///./node_modules/@sentry/replay/dist/index.es.js","webpack:///../../../src/browser/types.ts","webpack:///../../../../../src/browser/web-vitals/lib/bindReporter.ts","webpack:///../../../../../src/browser/web-vitals/lib/getNavigationEntry.ts","webpack:///../../../../../src/browser/web-vitals/lib/getActivationStart.ts","webpack:///../../../../../src/browser/web-vitals/lib/initMetric.ts","webpack:///../../../../../src/browser/web-vitals/lib/generateUniqueID.ts","webpack:///../../../../../src/browser/web-vitals/lib/observe.ts","webpack:///../../../../../src/browser/web-vitals/lib/onHidden.ts","webpack:///../../../../../src/browser/web-vitals/lib/getVisibilityWatcher.ts","webpack:///../../../../src/browser/web-vitals/getLCP.ts","webpack:///../../../../src/browser/metrics/utils.ts","webpack:///../../../../src/browser/metrics/index.ts","webpack:///../../../../src/browser/web-vitals/getFID.ts","webpack:///../../../../src/browser/web-vitals/getCLS.ts","webpack:///../../../src/browser/request.ts","webpack:///../../../src/browser/browsertracing.ts","webpack:///../../../src/browser/router.ts","webpack:///../../../src/browser/backgroundtab.ts","webpack:///../../../src/transports/offline.ts","webpack:///../../../../src/transports/offline.ts","webpack:///../../../../src/profiling/utils.ts","webpack:///../../../../src/profiling/hubextensions.ts","webpack:///../../../../src/profiling/integration.ts","webpack:///../../../src/index.ts"],"names":["isGlobalObj","obj","Math","undefined","GLOBAL_OBJ","globalThis","window","self","global","this","getGlobalObject","getGlobalSingleton","name","creator","gbl","__SENTRY__","objectToString","Object","prototype","toString","isBuiltin","wat","DEBUG_BUILD","isError","call","isInstanceOf","Error","className","isString","isPrimitive","isParameterizedString","isPlainObject","isEvent","Event","isElement","Element","isRegExp","isThenable","Boolean","then","isSyntheticEvent","isNaN","base","_e","isVueViewModel","__isVue","_isVue","serializeEventTarget","target","getOwnProperties","_dropUndefinedKeys","module","exports","originalModule","webpackPolyfill","create","children","defineProperty","enumerable","get","l","i","truncate","str","max","length","getFunctionName","fn","e","WINDOW","visit","reTrim","reIsBadHex","reIsBinary","reIsOctal","freeParseInt","parseInt","freeGlobal","freeSelf","root","Function","nativeMax","nativeMin","min","now","Date","isObject","value","type","toNumber","isObjectLike","isSymbol","other","valueOf","replace","isBinary","test","slice","func","wait","options","lastArgs","lastThis","maxWait","result","timerId","lastCallTime","lastInvokeTime","leading","maxing","trailing","TypeError","invokeFunc","time","args","thisArg","apply","leadingEdge","setTimeout","timerExpired","shouldInvoke","timeSinceLastCall","trailingEdge","remainingWait","debounced","isInvoking","arguments","cancel","clearTimeout","flush","htmlTreeAsString","elem","currentElem","MAX_TRAVERSE_HEIGHT","out","height","len","separator","sepLength","nextStr","keyAttrs","Array","isArray","maxStringLength","_htmlElementAsString","push","parentNode","reverse","join","_oO","el","classes","key","attr","tagName","HTMLElement","dataset","toLowerCase","keyAttrPairs","filter","keyAttr","getAttribute","map","forEach","keyAttrPair","id","normalize","input","depth","maxProperties","Infinity","memo","memoize","unmemoize","includes","stringified","_events","document","String","objName","getPrototypeOf","constructor","getConstructorName","err","stringifyValue","startsWith","remainingDepth","valueWithToJSON","toJSON","jsonValue","normalized","numAdded","visitable","visitKey","hasOwnProperty","visitValue","ERROR","memoBuilder","hasWeakSet","WeakSet","inner","has","add","delete","splice","originalFunctionToString","DEFAULT_IGNORE_ERRORS","DEFAULT_IGNORE_TRANSACTIONS","event","_getEventFilterUrl","frames","encodeUTF8","buffers","ITEM_TYPE_TO_DATA_CATEGORY_MAP","filenameMetadataMap","Map","parsedStacks","Set","parser","instrumented","instrument","triggerHandlers","hasProp","getUrlFromResource","resource","lastHref","debounceTimerID","lastCapturedEvent","makeDOMEventHandler","handler","previous","_oldOnErrorHandler","_oldOnUnhandledRejectionHandler","errorsInstrumented","errorCallback","tag","IDLE_TRANSACTION_FINISH_REASONS","traceHeaders","sample","rate","_startTransaction","configInstrumenter","getEventForEnvelopeItem","item","getBaseApiEndpoint","dsn","ignoreOnError","integrations","ALREADY_SEEN_ERROR","isErrorEvent","isTransactionEvent","ex","reactMinifiedRegexp","extractMessage","getNonErrorObjectExceptionValue","feedback","cachedFetchImpl","createFrame","filename","chromeRegex","chromeEvalRegex","geckoREgex","geckoEvalRegex","winjsRegex","opera10Regex","opera11Regex","extractSafariExtensionDetails","_installGlobalOnErrorHandler","msg","_installGlobalOnUnhandledRejectionHandler","_enhanceEventWithInitialFrame","addMechanismAndCapture","hub","getHubAndOptions","DEFAULT_EVENT_TARGET","_wrapTimeFunction","original","_wrapRAF","_wrapXHR","originalSend","_wrapEventTarget","dom","addSentryBreadcrumb","_consoleBreadcrumb","handlerData","_xhrBreadcrumb","_fetchBreadcrumb","_historyBreadcrumb","exceptions","aggregateExceptionsFromError","applyExceptionGroupFieldsForParentException","exception","applyExceptionGroupFieldsForChildException","currentEvent","_isSameStacktrace","_isSameFingerprint","_getExceptionFromEvent","_getFramesFromEvent","startSessionOnHub","crypto","msCrypto","getRandomByte","random","randomUUID","getRandomValues","typedArray","Uint8Array","_","c","dateTimestampInSeconds","timestampInSeconds","performance","approxStartingTimeOrigin","timeOrigin","createUnixTimestampInSecondsFunc","_browserPerformanceTimeOriginMode","browserPerformanceTimeOrigin","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","executor","_state","PENDING","_handlers","_resolve","_reject","onfulfilled","onrejected","resolve","reject","reason","_executeHandlers","val","onfinally","isRejected","_setResult","RESOLVED","REJECTED","state","_value","cachedHandlers","notifyEventProcessors","processors","hint","index","processor","log","final","context","startingTime","session","sid","init","timestamp","started","duration","status","errors","ignoreDuration","user","ipAddress","ip_address","did","email","username","abnormal_mechanism","RegExp","spanToTraceContext","span","spanId","span_id","traceId","trace_id","spanContext","data","op","parent_span_id","tags","origin","spanToJSON","getSpanJSON","spanIsSpanClass","spanIsSampled","traceFlags","WeakMap","parseEventHintOrCaptureContext","hintIsScopeOrFunction","keys","some","captureContextKeys","hintIsScopeContext","captureContext","captureException","getClient","getCurrentScope","getScope","getRootSpan","transaction","getDynamicSamplingContextFromSpan","client","dsc","scope","getOptions","publicKey","public_key","getDsn","segment","user_segment","getUser","environment","release","emit","txn","v7FrozenDsc","_frozenDynamicSamplingContext","sampleRate","maybeSampleRate","source","metadata","sample_rate","applyScopeDataToEvent","fingerprint","breadcrumbs","sdkProcessingMetadata","extra","contexts","level","transactionName","cleanedExtra","cleanedTags","cleanedUser","cleanedContexts","applyDataToEvent","trace","rootSpan","dynamicSamplingContext","description","applySpanToEvent","concat","applyFingerprintToEvent","mergedBreadcrumbs","applyBreadcrumbsToEvent","applySdkMetadataToEvent","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_extra","_contexts","_sdkProcessingMetadata","_propagationContext","clone","newScope","_level","_span","_session","_transactionName","_fingerprint","_requestSession","_client","callback","_notifyScopeListeners","requestSession","extras","scopeToMerge","scopeData","getScopeData","getRequestSession","propagationContext","scopeContext","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","attachment","attachments","eventProcessors","additionalEventProcessors","newData","eventId","event_id","warn","syntheticException","originalException","message","captureMessage","captureEvent","substring","parseFloat","isolationScope","_version","assignedScope","assignedIsolationScope","setClient","_stack","bindClient","_isolationScope","version","top","getStackTop","setupIntegrations","getStack","pop","pushScope","maybePromiseResult","popScope","res","_lastEventId","beforeBreadcrumb","finalBreadcrumb","addBreadcrumb","setUser","getIsolationScope","setTags","setExtras","setTag","setExtra","setContext","oldHub","integration","getIntegration","customSamplingContext","_callExtensionMethod","endSession","_sendSessionUpdate","getSession","setSession","userAgent","navigator","currentSession","sendDefaultPii","captureSession","method","sentry","extensions","registry","acs","getCurrentHub","isOlderThan","carrier","addHandler","maybeInstrument","instrumentFn","typeHandlers","error","console","originalConsoleMethod","lastCapturedEventType","lastCapturedEventTargetId","triggerDOMHandler","bind","globalDOMEventHandler","addEventListener","proto","originalAddEventListener","listener","handlers","__sentry_instrumentation_handlers__","handlerForType","refCount","originalRemoveEventListener","globalListener","getEventTarget","eventType","isContentEditable","_sentryId","isSimilarToLastCapturedEvent","Headers","Request","Response","EdgeRuntime","fetch","doc","createElement","sandbox","hidden","head","appendChild","contentWindow","removeChild","originalFetch","url","fetchArgs","toUpperCase","arg","fetchData","startTimestamp","response","endTimestamp","prop","onerror","line","column","__SENTRY_LOADER__","__SENTRY_INSTRUMENTED__","onunhandledrejection","chromeVar","chrome","isChromePackagedApp","app","runtime","hasHistoryApi","history","pushState","replaceState","oldOnPopState","onpopstate","historyReplacementFunction","originalHistoryFunction","from","to","location","href","XMLHttpRequest","xhrproto","originalOpen","request_headers","match","__sentry_own_request__","onreadystatechangeHandler","xhrInfo","readyState","status_code","xhr","onreadystatechange","readyStateArgs","setRequestHeaderArgs","header","sentryXhrData","body","addClickKeypressInstrumentationHandler","addXhrInstrumentationHandler","addFetchInstrumentationHandler","addHistoryInstrumentationHandler","addGlobalErrorInstrumentationHandler","addGlobalUnhandledRejectionInstrumentationHandler","NodeType","__assign","assign","t","s","n","p","__values","o","Symbol","iterator","m","next","done","__read","r","ar","__spreadArray","pack","nodeType","ELEMENT_NODE","isShadowRoot","_a","host","shadowRoot","maskInputValue","maskInputOptions","maskInputFn","text","repeat","canvasService","canvasCtx","_id","tagNameRegex","getCssRulesString","rules","cssRules","getCssRuleString","rule","cssStringified","cssText","isCSSImportRule","styleSheet","URL_IN_CSS_REF","RELATIVE_PATH","DATA_URI","absoluteToStylesheet","quote1","path1","quote2","path2","path3","filePath","maybeQuote","indexOf","split","stack","parts","_i","parts_1","part","SRCSET_NOT_SPACES","SRCSET_COMMAS_OR_SPACES","absoluteToDoc","attributeValue","trim","a","getHref","transformAttribute","pos","collectCharacters","regEx","chars","exec","output","descriptorsStr","inParens","charAt","getAbsoluteSrcsetString","needMaskingText","node","maskTextClass","maskTextSelector","classList","contains","eIndex","matches","TEXT_NODE","serializeNode","rootId","sheet","blockClass","blockSelector","inlineStylesheet","_b","maskTextFn","_c","dataURLOptions","inlineImages","recordCanvas","keepIframeSrcFn","__sn","docId","DOCUMENT_NODE","compatMode","Document","childNodes","DOCUMENT_TYPE_NODE","DocumentType","publicId","systemId","needBlock","element","_isBlockedElement","HTMLFormElement","processedTagName","getValidTagName","attributes_1","_d","attributes","name_1","stylesheet","styleSheets","find","rel","_cssText","innerText","textContent","checked","selected","__context","canvas","ctx","getContext","x","width","y","getImageData","originalGetImageData","Uint32Array","buffer","pixel","is2DCanvasBlank","rr_dataURL","toDataURL","quality","canvasDataURL","blankCanvas","image_1","oldValue_1","crossOrigin","recordInlineImage","naturalWidth","naturalHeight","drawImage","currentSrc","complete","onload","rr_mediaState","paused","rr_mediaCurrentTime","currentTime","scrollLeft","rr_scrollLeft","scrollTop","rr_scrollTop","_f","getBoundingClientRect","rr_width","rr_height","src","contentDocument","rr_src","isSVG","ownerSVGElement","parentTagName","isStyle","isScript","nextSibling","previousSibling","Text","CDATA_SECTION_NODE","CDATA","COMMENT_NODE","Comment","lowerIfExists","maybeAttr","serializeNodeWithId","skipChild","slimDOMOptions","onSerialize","onIframeLoad","_g","iframeLoadTimeout","_h","_j","preserveWhiteSpace","_serializedNode","sn","comment","script","as","endsWith","headFavicon","headMetaDescKeywords","headMetaSocial","property","headMetaRobots","headMetaHttpEquiv","headMetaAuthorship","headMetaVerification","slimDOMExcluded","serializedNode","recordChild","isShadowHost","headWhitespace","bypassOptions","_k","serializedChildNode","_l","_m","isShadow","iframeEl","win","fired","timer_1","onceIframeLoaded","iframeDoc","serializedIframeNode","EventType","IncrementalSource","MouseInteractions","CanvasContext","MediaInteractions","ReplayerEvents","HOVER_SELECTOR","on","capture","passive","removeEventListener","DEPARTED_MIRROR_ACCESS_WARNING","_mirror","getId","getNode","removeNodeFromMap","reset","throttle","timeout","remaining","hookSetter","d","isRevoked","getOwnPropertyDescriptor","set","_this","patch","replacement","original_1","wrapped","defineProperties","__rrweb_original__","getWindowHeight","innerHeight","documentElement","clientHeight","getWindowWidth","innerWidth","clientWidth","isBlocked","needBlock_1","closest","isIgnored","isTouchEvent","changedTouches","Proxy","Reflect","receiver","TreeIndex","mutation","parentTreeNode","indexes","parentId","treeNode","texts","parent","tree","remove","mirror","deepRemoveFromMirror","removeIdSet","childNode","deepRemoveFromTreeIndex","values","_treeNode","_parentTreeNode","removeNodeMutations","textMutations","attribute","attributeMutations","scroll","scrollMap","inputMap","e_1","e_2","batchMutationData","Mutation","removes","adds","walk","removed","e_1_1","return","e_2_1","mutationData","idRemoved","isIframeINode","hasShadowRoot","isNodeInLinkedList","DoubleLinkedList","position","current","addNode","__ln","removeNode","moveKey","isINode","deepDelete","addsSet","childN","isParentRemoved","isAncestorInSet","MutationBuffer","frozen","locked","mapRemoves","movedMap","addedSet","movedSet","droppedSet","processMutations","mutations","processMutation","addList","getNextId","ns","nextId","pushAdd","shadowHost","getRootNode","rootShadowHost","notInDoc","currentN","iframeManager","addIframe","shadowDomManager","addShadowRoot","iframe","childSn","attachIframe","observeAttachShadow","shift","candidate","_node","payload","mutationCb","e_3","e_4","oldValue","attributeName","old","setAttribute","style","styleObj","pname","newValue","getPropertyValue","newPriority","getPropertyPriority","e_3_1","e_4_1","addedNodes","genAdds","removedNodes","nodeId","isAncestorRemoved","targetId","freeze","canvasManager","unfreeze","isFrozen","lock","unlock","mutationBuffers","isCSSGroupingRuleSupported","CSSGroupingRule","isCSSMediaRuleSupported","CSSMediaRule","isCSSSupportsRuleSupported","CSSSupportsRule","isCSSConditionRuleSupported","CSSConditionRule","path","composedPath","initMutationObserver","rootEl","mutationBuffer","mutationObserverCtor","MutationObserver","__rrMutationObserver","angularZoneSymbol","Zone","__symbol__","observer","observe","attributeOldValue","characterData","characterDataOldValue","childList","subtree","initMouseInteractionObserver","mouseInteractionCb","sampling","mouseInteraction","disableMap","Number","eventKey","eventName","clientX","clientY","getHandler","h","initScrollObserver","scrollCb","evt","scrollEl","scrollingElement","wrapEventWithUserTriggeredFlag","v","enable","userTriggered","INPUT_TAGS","lastInputValueMap","getNestedCSSRulePositions","childRule","parentRule","unshift","parentStyleSheet","recurse","initObservers","hooks","currentWindow","defaultView","mousemoveCb","viewportResizeCb","inputCb","mediaInteractionCb","styleSheetRuleCb","styleDeclarationCb","canvasMutationCb","fontCb","mousemove","viewportResize","mediaInteaction","styleSheetRule","styleDeclaration","canvasMutation","font","mergeHooks","mutationObserver","mousemoveHandler","timeBaseline","threshold","callbackThreshold","mousemoveCallback","positions","wrappedCb","totalOffset","timeOffset","updatePosition","DragEvent","Drag","MouseEvent","MouseMove","TouchMove","initMoveObserver","mouseInteractionHandler","scrollHandler","viewportResizeHandler","lastH","lastW","initViewportResizeObserver","inputHandler","ignoreClass","userTriggeredOnInput","eventHandler","isTrusted","parentElement","isChecked","cbWithDedup","querySelectorAll","lastInputValue","propertyDescriptor","HTMLInputElement","hookProperties","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","initInputObserver","mediaInteractionHandler","volume","muted","media","initMediaInteractionObserver","styleSheetObserver","insertRule","CSSStyleSheet","ownerNode","deleteRule","supportedNestedCSSRuleTypes","unmodifiedFunctions","entries","typeKey","initStyleSheetObserver","styleDeclarationObserver","setProperty","CSSStyleDeclaration","priority","removeProperty","initStyleDeclarationObserver","fontObserver","collectFonts","fontMap","originalFontFace","FontFace","family","descriptors","fontFace","fontSource","JSON","stringify","restoreHandler","fonts","initFontObserver","pluginHandlers","plugins","plugin","b","disconnect","IframeManager","iframes","addLoadListener","cb","loadListener","isAttachIframe","ShadowDomManager","restorePatches","manager","ownerDocument","iframeElement","manager_1","restorePatch","props2D","getOwnPropertyNames","CanvasRenderingContext2D","_loop_1","recordArgs","HTMLCanvasElement","imgd","pix","hookHandler","setter","props2D_1","props2D_1_1","contextType","lookup","charCodeAt","webGLVarMap","saveWebGLVar","isInstanceOfWebGLObject","list","ctor","contextMap","variableListFor","serializeArg","Float32Array","Float64Array","Int32Array","Uint16Array","Int16Array","Int8Array","Uint8ClampedArray","rr_type","ArrayBuffer","base64","arraybuffer","bytes","encode","DataView","byteOffset","byteLength","HTMLImageElement","ImageData","serializeArgs","supportedWebGLConstructorNames","patchGLPrototype","props","props_1","props_1_1","wrappedEmit","takeFullSnapshot","WebGLRenderingContext","WebGL","WebGL2RenderingContext","WebGL2","CanvasManager","pendingCanvasMutations","rafStamps","latestId","invokeId","initCanvasMutationObserver","clear","resetObservers","startRAFTimestamping","startPendingCanvasMutationFlusher","canvasContextReset","canvas2DReset","canvasWebGL1and2Reset","requestAnimationFrame","flushPendingCanvasMutations","setLatestRAFTimestamp","flushPendingCanvasMutationFor","valuesWithType","getOwnPropertySymbols","propertyIsEnumerable","__rest","commands","wrapEvent","child","record","checkoutEveryNms","checkoutEveryNth","maskAllInputs","_maskInputOptions","_slimDOMOptions","packFn","mousemoveWait","lastFullSnapshotEvent","color","date","month","number","range","search","tel","week","textarea","select","password","NodeList","DOMTokenList","Node","incrementalSnapshotCount","isCheckout","FullSnapshot","IncrementalSnapshot","buf","eventProcessor","exceedCount","exceedTime","wrappedMutationEmit","wrappedScrollEmit","Scroll","wrappedCanvasMutationEmit","CanvasMutation","Meta","slimDOM","idNodeMap","snapshot","initialOffset","left","pageXOffset","pageYOffset","handlers_1","DomContentLoaded","observe_1","MouseInteraction","ViewportResize","Input","MediaInteraction","StyleSheetRule","StyleDeclaration","Font","Plugin","init_1","Load","addCustomEvent","Custom","freezePage","__awaiter","_arguments","P","generator","Promise","fulfilled","step","rejected","__generator","f","g","label","sent","trys","ops","verb","createBreadcrumb","getTime","handleDom","targetNode","category","_LAST_BREADCRUMB","handleScope","newBreadcrumb","isBrowser$1","isInternal","isIngestHost","targetHost","protocol","handleFetch","start","end","statusCode","handleHistory","handleXhr","__sentry_xhr__","isExpired","initialTime","expiry","targetTime","isSessionExpired","idleTimeout","lastActivity","wrapLogger","logFn","logger$1","logger","saveSession","sessionStorage","setItem","isSampled","Session","stickySession","sessionSampleRate","errorSampleRate","uuid4","_started","_lastActivity","_segmentId","segmentId","_sampled","sampled","configurable","newDate","_previousSessionId","_isSampled","sessionStringFromStorage","getItem","sessionObj","parse","fetchSession","createSession","addInternalBreadcrumb","rest","captureInternalException","NAVIGATION_ENTRY_KEYS","isNavigationEntryEqual","every","ENTRY_TYPES","entry","entryType","initiatorType","responseEnd","startTime","encodedBodySize","transferSize","getAbsoluteTime","size","paint","navigation","domComplete","createPerformanceEntry","EventBufferArray","events","destroy","addEvent","finish","eventsRet","EventBufferCompressionWorker","worker","eventBufferItemLength","sendEventToWorker","promise","postMessage","finishRequest","stringifiedArgs","success","terminate","MEDIA_SELECTORS","_initialized","isBrowser","Replay","flushMinDelay","flushMaxDelay","initialFlushDelay","useCompression","maskAllText","blockAllMedia","_o","_p","_q","replaysSamplingRate","captureOnlyOnError","recordingOptions","performanceEvents","performanceObserver","retryCount","retryInterval","flushLock","isEnabled","isPaused","waitForError","hasInitializedCoreListeners","stopRecording","errorIds","traceIds","urls","earliestEvent","initialTimestamp","initialUrl","handleGlobalEvent","replayId","exc","flushImmediate","startRecording","handleRecordingEmit","checkAndHandleExpiredSession","addUpdate","setInitialState","previousSessionId","conditionalFlush","debouncedFlush","handleVisibilityChange","visibilityState","doChangeToForegroundTasks","doChangeToBackgroundTasks","handleWindowBlur","handleWindowFocus","handleCoreSpanListener","getSpanHandler","triggerUserActivity","createPerformanceSpans","handleCoreBreadcrumbListener","getBreadcrumbHandler","handlePerformanceObserver","newPerformanceEntries","currentList","newList","reduce","acc","existingNavigationEntries","existingLcpEntries","existingEntries","newEntries","newNavigationEntries","newLcpEntry","navigationEntry","sort","dedupePerformanceEntries","getEntries","err_1","runFlush","usingDeprecatedReplaysSamplingRate","usingDeprecatedCaptureOnlyOnError","debounce","setupOnce","loadSession","updateSessionActivity","eventBuffer","Worker","workerBlob","Blob","workerUrl","URL","createObjectURL","createEventBuffer","addListeners","stop","removeListeners","pause","resume","clearSession","removeItem","deleteSession","urlPath","pathname","hash","clearContext","addScopeListener","addInstrumentationHandler","PerformanceObserver","buffered","cbResult","expired","createCustomBreadcrumb","triggerFullSnapshot","timestampInMs","updateUserActivity","all","addPerformanceEntries","createPerformanceEntries","addMemoryEntry","memoryEntry","jsHeapSizeLimit","totalJSHeapSize","usedJSHeapSize","memory","oldSessionId","popEventContext","recordingData","eventContext","err_2","sendReplay","includeReplayStartTimestamp","sendReplayRequest","segment_id","payloadWithSequence","currentTimestamp","sdkInfo","replayEvent","envelope","headers","replayHeaders","sequence","TextEncoder","createPayload","_withClient","preparedEvent","_prepareEvent","replay_start_timestamp","error_ids","trace_ids","replay_id","_updateSessionFromEvent","sdk","replayType","items","createEnvelope","sent_at","toISOString","getTransport","send","resetRetries","ex_1","err_3","firstHiddenTime","reportedMetricIDs","msToSec","getBrowserPerformanceAPI","_lcpEntry","_clsEntry","_performanceCursor","_measurements","_addPerformanceNavigationTiming","addHTTPTimings","resourceTiming","setHeaderOnXhr","DEFAULT_BROWSER_TRACING_OPTIONS","promisifyRequest","createIndexedDbStore","THREAD_ID_STRING","OS_PLATFORM","OS_PLATFORM_VERSION","OS_ARCH","OS_BROWSER","OS_MODEL","OS_LOCALE","userAgentData","profile","PROFILING_CONSTRUCTOR_FAILED","windowIntegrations","INTEGRATIONS"],"mappings":"2FAkBA,YAwEA,SAASA,EAAYC,GACnB,OAAOA,GAAOA,EAAIC,MAAQA,KAAOD,OAAME,EAzEzC,sGA6EO,MAAMC,EACW,iBAAdC,YAA0BL,EAAYK,aAE5B,iBAAVC,QAAsBN,EAAYM,SAC1B,iBAARC,MAAoBP,EAAYO,OACtB,iBAAVC,GAAsBR,EAAYQ,IACzC,WACC,OAAOC,KADR,IAGD,GAKK,SAASC,IACd,OAAON,EAcF,SAASO,EAAsBC,EAA0CC,EAAkBZ,GAChG,MAAMa,EAAOb,GAAOG,EACdW,EAAcD,EAAIC,WAAaD,EAAIC,YAAc,GAEvD,OADkBA,EAAWH,KAAUG,EAAWH,GAAQC,Q,mDC1H5D,4dACA,MAAMG,EAAiBC,OAAOC,UAAUC,SASxC,cACA,kBACA,qBACA,yBACA,4BACA,SACA,QACA,mBAU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GP,MAdwB,iB,6JCtH5B,MAAMC,EAAS,OAAf,IAAe,GAUf,WACA,EACA,MAUA,IACA,QACA,UACA,KACA,QACA,IACA,cACA,WACA,MACA,sCACA,wCA9BkC,GAgClC,gBACA,WAKA,6CAIA,UAEA,YACA,eAGA,2BACA,SACA,mBASA,gBACA,UAOA,KACA,MACA,EACA,EACA,EACA,EAEA,kBACA,SAGA,gCAGA,QACA,YACA,6DACA,KAEA,eACA,cACA,qCASA,GANA,MACA,iBAIA,cACA,kBAEA,IADA,iBACA,mBACA,iBAIA,mDACA,uBACA,OACA,oBACA,GACA,wBAGA,kBAMA,aACA,IACA,gCACA,SACA,UAqBA,cACA,4CACA,4BAEA,O,0KCrJA,sBAgBA,GACA,+BA2EA,sBAZA,WACA,IAEA,OADA,4BACA,YACA,SACA,QAOA,GAnDA,WACA,uBACA,cACA,OA0BA,OACA,gBACA,WAJA,oBAwBA,GAEA,OACA,MACA,EACA,CACA,2CAMA,uBAaA,uBAkBA,MAMA,cAKA,uBACA,cAEA,YADA,UAIA,MACA,UACA,aAGA,eACA,2BANA,KAQA,IARA,KAgBA,qCAGA,EAFA,mBAEA,gBAnBA,KAsBA,UAFA,EApBA,KAwBA,MACA,eACA,eAEA,oBACA,IAKA,YACA,IA9CA,K,uJCrIA,aAGA,OACA,eACA,oEAUA,gBAEA,uB,6DCLA,aACA,iFAMA,aAEA,YAjCA,qE,0JCmCA,0BACA,IAEA,OAiCA,SAASC,EACT,EACA,EACA,MACA,MACA,iBAEA,aAGA,GACA,SACA,kEAEA,SAGA,QAgGA,SACA,EAGA,GAEA,IACA,kDACA,iBAGA,uBACA,wBAMA,qBACA,iBAIA,0CACA,iBAIA,8CACA,mBAIA,kBACA,yBAGA,4BACA,cAGA,wBACA,sCAGA,sBACA,uBAIA,sBACA,+BAOA,QAcA,YACA,iCAEA,6CAjBA,IAGA,mCACA,sBAGA,gBACA,SACA,qCAnKA,MAIA,6BACA,SAQA,mCACA,SAMA,QACA,2DACA,0CACA,E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ACA,kBAEA,IACA,8BACA,SACA,iBAKA,KACA,EACA,GAEA,qBACA,sBACA,EACA,IACA,KAKA,IACA,QACA,SACA,UALA,MASA,IACA,KAGA,IACA,QACA,SACA,UALA,QAUA,0BAKA,MACA,GAEA,yBAIA,WACA,qBACA,MACA,EAEA,iBACA,IACA,KACA,IACA,GACA,KAGA,IACA,KACA,IACA,GACA,MAGA,UACA,EACA,KAIA,SAMA,2BACA,+BAIA,2BACA,+BAIA,kCACA,0BAIA,eACA,oCAIA,cACA,cAEA,2BAIA,qCACA,2BACA,OAGA,+BACA,kBAEA,cACA,OAIA,0BAEA,kBAGA,0BACA,kBAGA,aCrLA,cAEA,sBAEA,GACA,QACA,QACA,YACA,UACA,WACA,YACA,SACA,kBACA,WA8GA,YACA,oBACA,aACA,YAEA,8CACA,kDACA,gBACA,gBACA,mEACA,oBACA,OACA,kBACA,0BACA,uBACA,0BA7HA,KAOA,OAJA,GACA,OAGA,EAeA,mBA6BA,GA5BA,UACA,iCACA,+BAGA,eACA,iDAIA,uCAEA,mBACA,mCAEA,QAEA,wCAEA,aACA,gBAEA,eACA,gBAEA,6BACA,qBAEA,iBACA,uBACA,+BACA,0BACA,CACA,8BACA,oBAEA,YACA,qBAEA,gBACA,8BAEA,2BACA,0BAEA,2BACA,yBAEA,4BACA,mBAEA,WACA,mBCrDA,QA0DA,cACA,4BACA,wBACA,yBACA,qBACA,qBACA,cACA,cACA,eACA,kBACA,+BACA,6BAOA,gBACA,cAkBA,OAjBA,IACA,mCACA,qBACA,uBACA,6BACA,gBACA,kBACA,gBACA,sBACA,sCACA,8BACA,2CACA,oCACA,mCACA,uDACA,kDAEA,EAOA,oBACA,6BAMA,qBAEA,OADA,8BACA,KAMA,WAMA,OALA,iBACA,eACA,0BAEA,6BACA,KAMA,UACA,kBAMA,oBACA,4BAMA,qBAEA,OADA,uBACA,KAMA,WAMA,OALA,eACA,cACA,GAEA,6BACA,KAMA,YAGA,OAFA,iCACA,6BACA,KAMA,aAMA,OALA,gBACA,eACA,GAEA,6BACA,KAMA,cAGA,OAFA,mCACA,6BACA,KAMA,kBAGA,OAFA,oBACA,6BACA,KAMA,SAEA,GAIA,OAFA,cACA,6BACA,KAMA,sBAGA,OAFA,wBACA,6BACA,KAMA,gBASA,OARA,gBAEA,kBAEA,oBAGA,6BACA,KAMA,WAGA,OAFA,aACA,6BACA,KAMA,UACA,kBAMA,iBAGA,uBACA,wBAMA,cAOA,OANA,EAGA,uBAFA,cAIA,6BACA,KAMA,aACA,qBAMA,UACA,MACA,YAGA,yBACA,gBACA,6BA6CA,OA1CA,gBACA,sCACA,yCACA,kDACA,uCACA,oBAEA,WACA,sBAEA,iBACA,kCAEA,oBACA,wCAEA,wBACA,iDAEA,iBAEA,IACA,qCACA,wCACA,iDACA,SACA,mBAEA,UACA,qBAEA,gBACA,iCAEA,mBACA,uCAEA,uBACA,gDAIA,KAMA,QAeA,OAdA,qBACA,cACA,eACA,cACA,kBACA,mBACA,6BACA,yBACA,4BACA,kBACA,qBACA,6BACA,qBACA,6BACA,KAMA,mBACA,6BAlXA,IAqXA,QACA,YAGA,SACA,2BACA,GAKA,OAHA,qDACA,6BAEA,KAMA,oBACA,qDAMA,mBAGA,OAFA,qBACA,6BACA,KAMA,iBAEA,OADA,0BACA,KAMA,iBACA,yBAMA,mBAEA,OADA,qBACA,KAUA,qBAuBA,GAtBA,+CACA,qCAEA,6CACA,kCAEA,6CACA,kCAEA,qDACA,8CAEA,cACA,qBAEA,wBACA,qCAMA,YACA,8DACA,+BACA,MACA,yBACA,wDACA,yBAEA,eACA,IACA,mCAgBA,OAXA,0BAEA,0DACA,0DAEA,4BACA,2BACA,4BACA,6CAGA,mEAMA,4BAGA,OAFA,kEAEA,KAMA,yBAEA,OADA,2BACA,KAMA,wBACA,gCAMA,uBACA,EACA,EACA,EACA,KAEA,qBACA,aACA,kCACA,SACA,CACA,qBAEA,yDACA,MACA,UACA,iDAEA,eACA,EACA,wDACA,aAEA,uCACA,QACA,gBASA,wBAIA,2BACA,4BACA,iCACA,UAEA,6BAQA,qBAEA,gDAGA,oBACA,uDAIA,6CACA,eAQA,aACA,mDAOA,cACA,YAGA,aACA,OACA,YACA,0BCzlBA,MAMA,MAuDA,QAeA,wBA5EA,GA4EA,gBACA,wBACA,GACA,mBAOA,eACA,uBAMA,cACA,mBACA,SACA,wBACA,sBAOA,YAEA,iCAKA,OAJA,sBACA,wBACA,UAEA,EAMA,WACA,sCACA,sBAMA,aACA,yBACA,IACA,KACA,QACA,iBAOA,YACA,iCAIA,WACA,gCAIA,WACA,mBAIA,cACA,yCAMA,sBACA,uDACA,yCAaA,OAZA,yBACA,mBACA,EACA,CACA,oBACA,wBACA,EACA,YAEA,KAGA,EAMA,eACA,EAEA,EACA,GAEA,uDACA,eAcA,OAbA,yBACA,iBACA,EACA,EACA,CACA,oBACA,wBACA,EACA,YAEA,KAGA,EAMA,kBACA,qCAQA,OAPA,SACA,qBAGA,yBACA,wCAEA,EAMA,cACA,yBAMA,mBACA,2CAEA,aAEA,kDACA,iCAEA,eAEA,MACA,aADA,iBACA,GACA,IACA,cACA,EAEA,WAEA,QACA,kCAGA,sBAMA,WACA,2BAMA,WACA,2BAMA,aACA,6BAMA,YACA,4BAMA,cACA,8BAOA,gBACA,gCAMA,kBACA,2CACA,GACA,KAOA,OACA,gBACA,IACA,QACA,QACA,MAOA,kBACA,yBACA,kBACA,IACA,2BACA,SAEA,OADA,4HACA,MAOA,sBACA,0DAEA,iEACA,iBAQA,mLALA,aACA,gHAWA,SAMA,eACA,iDAMA,qBAEA,KACA,yBAIA,0BAMA,aACA,MACA,EADA,mBACA,MACA,iBACA,GFnTA,cACA,SACA,EACA,aACA,kBACA,qBAGA,OE4SA,IAEA,0BAGA,eAMA,gBACA,4CACA,kDAGA,+BAEA,KACA,UACA,cACA,oBACA,oBACA,IAIA,+BASA,OARA,oBACA,uBAEA,kBAGA,gBAEA,EAOA,uBACA,yBACA,oBACA,oCAMA,qBACA,2CAEA,iBACA,wBACA,oBAUA,eACA,2CACA,GACA,OASA,6BACA,MACA,EADA,IACA,WACA,uDACA,sCAEA,4HAWA,aAKA,OAJA,gCACA,cACA,YAEA,IAQA,cACA,YACA,OAEA,OADA,OACA,EAUA,aAEA,YAEA,mCACA,yCAEA,KACA,SAKA,YAGA,kBAOA,OALA,wBA/gBA,IAghBA,WAIA,KAkDA,cACA,4CASA,cACA,sCASA,gBACA,eAGA,OAFA,+BACA,OACA,EC7nBA,0EAeA,mBACA,wEACA,MACA,+BACA,kCAUA,cACA,kBAEA,MAIA,YADA,wCAIA,oCACA,SACA,IAEA,qBAMA,GALA,aACA,0BACA,WAGA,GACA,wBACA,IACA,QAIA,2EAGA,cACA,OACA,oBACA,0BACA,gBACA,YACA,gBACA,gBACA,uBA8CA,cACA,qCACA,MA5CA,YACA,2DACA,SAGA,uCAWA,OATA,4CACA,SACA,OACA,6CACA,MASA,iBAzFA,YACA,8BA6FA,KAKA,4BACA,gDACA,IANA,oDACA,IANA,qDACA,IAsBA,IAGA,S,aClGA,mBACA,YAQA,iBACA,aACA,mBASA,YACA,EACA,GAEA,aAEA,kBAIA,GAFA,IADA,WAIA,SAIA,SAaA,SAASC,GAAW5C,EAApB,GAEA,OADA,oBACA,UAMA,iBACA,aAGA,wBAEA,cACA,mBACA,qCAEA,qCAIA,kBACA,aAIA,GAFA,8BAEA,4CACA,SACA,CACA,MACA,IACA,oBACA,SAIA,iCAEA,MAIA,2BAGA,SAAuB6C,GACvB,sCAEA,oBACA,QACA,iBACA,WACA,YAGA,SAbA,IAgEA,YACA,EACA,GAEA,oDAEA,OACA,aACA,kBACA,gBACA,oBACA,2BACA,mCAEA,GAIA,MAAMC,GAAN,CACA,kBACA,mBACA,wBACA,0BACA,cACA,yBACA,sBACA,kBACA,sBACA,0BACA,oBAMA,eACA,aAIA,eACA,cACA,OAEA,8BACA,yBC5NA,MAAMC,GAAsB,IAAIC,IAE1BC,GAAe,IAAIC,IAoCzB,iBAEA,OApCA,SAAuCC,GACvC,6BAIA,uDACA,qCAEA,aACA,SAIA,UAEA,aAGA,2BACA,eAEA,qBACA,QAaA,IACA,UC/BA,SAIA,+CAOA,cACA,gBAMA,eACA,wBAEA,+BACA,OAIA,0BACA,aACA,gBACA,qCAEA,KDoCA,YACA,IAEA,+BACA,gBAIA,8CACA,oBAGA,WC/CA,IACA,aAMA,mCAEA,MDFA,cACA,IAEA,+BACA,gBAIA,wCACA,eACA,SAGA,yBAEA,IACA,wBAIA,WCjBA,MACA,KAGA,kBC5DA,kBCqCA,iBACA,kDAUA,YACA,EAEA,GAIA,oCACA,+CACA,iCASA,iBACA,6BAOA,eACA,sBAWA,eACA,qBASA,iBACA,oBAOA,eACA,iBAQA,iBACA,kBAOA,eACA,eAWA,iBACA,gBAQA,eACA,eAgBA,eACA,iBAuBA,YACA,EACA,GAEA,sCAiCA,qBACA,wBACA,SACA,aAEA,2GACA,qBAWA,qBACA,wBACA,SACA,aAEA,2HACA,qBAQA,cACA,yBChPA,YACA,GAEA,6DACA,SAGA,wBACA,uBACA,0E,cCjBA,uBA0DA,cACA,mBACA,SAGA,IAIA,OAHA,YACA,sCACA,cACA,EACA,SACA,UAOA,eACA,gFCvDA,MAAM,GAAN,cCNA,MAAM,GAAN,cA0BM,GAAN,GACMC,GAAN,GAGA,SAASC,GAAWpI,GACpB,UAMA,OAFA,SAEA,GACA,eAoEA,WACA,sBACA,OAGA,uBACA,kBAIA,uCAGA,OAFA,OAEA,eACA,+BAEA,aACA,iCApFA,GACA,MACA,WAieA,WACA,gBACA,OAMA,4BACA,WACA,2CACA,8CAOA,mCAEA,+BAEA,4DAIA,8CACA,gBAEA,EACA,EACA,GAEA,8BACA,IACA,aACA,kFACA,0BAEA,eACA,cACA,YACA,mBAGA,aACA,UAMA,8BAIA,YACA,EACA,uBACA,YACA,gBAEA,EACA,EACA,GAEA,8BACA,IACA,aACA,4CACA,OAEA,IACA,aAEA,gBACA,2BACA,wBACA,MAIA,kCACA,uCAGA,UAMA,iCA5jBA,GACA,MACA,WAyLA,WAEA,sBACA,OAGA,iCAEA,kCACA,sBACA,aACA,0BAEA,iDACA,SACA,oBAKA,2DACA,gCAGA,aAEA,+BAEA,MAIA,qBACA,IAGA,0BACA,UAIA,UACA,OACA,wBACA,0BACA,aAiCA,MA5BA,wEACA,mDACA,sBAEA,OADA,IACA,oBAIA,4CAMA,iDACA,sBACA,aAEA,yBAMA,OAJA,IACA,sCAGA,oBAIA,oBAIA,kCACA,sBACA,+BAWA,OAVA,mBACA,aAGA,UACA,OACA,0BACA,WAGA,oBAvRA,GACA,MACA,aAmFA,WACA,IF7DA,WACA,SACA,SAKA,gBACA,SAKA,SACA,oBAEA,yCACA,IACA,kCACA,YACA,sBACA,yCAEA,6BAEA,sBACA,UACA,yDACA,4FAIA,SE6BA,GACA,OAGA,qCACA,sBACA,sBAsEA,YACA,gBACA,4BAGA,iBACA,aAEA,OACA,UACA,4DAIA,aACA,OACA,UACA,4DAvFA,IAEA,GACA,OACA,WACA,SACA,OAEA,2BAQA,OALA,eACA,IAIA,oBACA,IACA,eACA,EACA,wBACA,aAEA,GAEA,IASA,MARA,eACA,EACA,wBACA,UAKA,QA3HA,GACA,MACA,eA0RA,WACA,ID/TA,WAMA,kBACA,0BAEA,oEAEA,YCoTA,GACA,OAGA,sBAuBA,cACA,sBACA,+BACA,MAEA,WACA,YAEA,KACA,cACA,OACA,OAGA,wBApCA,6BACA,yBAEA,KAMA,GALA,KACA,cACA,OACA,OAEA,EAIA,IACA,uBACA,YAyBA,sCACA,yCAxUA,GACA,MACA,YA2jBA,cAEA,+BASA,OARA,YACA,SACA,QACA,OACA,MACA,WAGA,2BAEA,0BAMA,sCA5kBA,MACA,yBAilBA,2BAEA,oCAGA,OAFA,6BAEA,4BAEA,0BAMA,mDA5lBA,MACA,QAEA,aADA,qGAUA,iBACA,gBACA,cACA,MAcA,SAASqI,GAAgBrI,EAAzB,GACA,YAIA,yBACA,IACA,KACA,UACA,yDACA,QACA,gGACA,IA+EA,SAASsI,GAAT,KACA,s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A,OACA,+BACA,sBAEA,oBAQA,SAoFA,kBACA,4BACA,wCACA,oDACA,qBACA,qBACA,2CACA,+BAEA,iBACA,kCAGA,gBACA,wBAEA,OACA,cAEA,gBACA,gCAEA,SACA,yBAEA,WACA,sBAEA,iBACA,kCAKA,WACA,4BAGA,YACA,gBAMA,WACA,GAEA,mBACA,EACA,yBACA,qBACA,uBAUA,GAPA,iCACA,gBACA,sBAGA,gCAEA,wEACA,MAIA,yBAJA,mDACA,4CACA,yBAGA,6DACA,SAGA,SAMA,YAEA,OADA,+BACA,KAOA,aAEA,OADA,+BACA,KAMA,aAEA,OADA,cACA,KAMA,iBACA,0CACA,4CACA,cAIA,MAHA,qBACA,kBAEA,KAMA,WACA,mBAMA,YACA,yBAMA,UACA,IACA,yDAEA,kBACA,sCACA,CACA,wEACA,GACA,yCAIA,qDAMA,gBACA,iDAMA,YACA,oBACA,eACA,6BACA,+BACA,WACA,+BACA,qBACA,mBACA,mCACA,mBACA,eACA,uBAOA,qBAaA,OAZA,qBACA,+BACA,iCACA,aACA,iCACA,uBACA,kCACA,0DACA,qBACA,qBACA,qCAEA,KAMA,kBACA,oBACA,sDACA,6BACA,WACA,iCACA,oBACA,mBACA,sDACA,wBAOA,SAcA,oBACA,sDACA,6BACA,WACA,iCACA,oBACA,oCACA,mBACA,sDACA,4BACA,sBACA,sBA+CA,eACA,iBACA,WAGA,iBACA,UACA,SACA,wBACA,SACA,0BACA,SACA,kBACA,SACA,uBACA,SACA,4BACA,SACA,2BACA,QACA,yBAIA,iBACA,UACA,SACA,sBACA,SACA,oBACA,SACA,0BACA,QACA,uBAIA,sBCvbA,YACA,EACA,EACA,GAEA,wBAEA,6BACA,8BAEA,eACA,6BACA,kBACA,eACA,aACA,aAKA,OAFA,8BAEA,ECXA,oBAyBA,iBACA,gBAGA,iBAEA,sBACA,kBAEA,iBAEA,sBAEA,eACA,mBACA,WACA,iBAGA,wBAGA,sBAIA,6CACA,IAEA,2CAKA,WACA,kBAIA,YACA,gB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BAGA,6CAGA,qFACA,sBAEA,4BASA,kBACA,GACA,yBACA,GAGA,CACA,8BAGA,4CACA,sBACA,kCACA,2BAEA,gFACA,yBACA,iBAcA,mBACA,qBAMA,uBACA,yBACA,oCACA,0DACA,yBACA,iBAEA,mBAOA,iBACA,iGACA,6FACA,uBACA,qIAOA,gBAQA,GAPA,sBACA,kGAEA,oBACA,sIAGA,yCACA,sBACA,sCACA,yBACA,gBAIA,mDASA,QAEA,kBACA,OAGA,8CAEA,8BACA,yBAEA,yBAGA,4BAEA,4BACA,wIACA,oCACA,yBACA,eAEA,sBAOA,kBACA,gIACA,gBACA,cACA,0BClWA,SAASC,KACT,MACA,EADA,gBACA,UAEA,SACA,CACA,kCAEA,GAeA,SAASC,GACT,EACA,EACA,GAGA,UAEA,OADA,aACA,EAIA,sBAIA,OAHA,eACA,+BAEA,EAKA,MAuBA,MAtBA,oCACA,qBACA,eACA,6BAEA,oBACA,uBACA,wBACA,qBACA,eACA,yBAIA,IACA,eACA,gBAgDA,SAA2BC,GAG3B,2DAOA,OANA,yDACA,OACA,yHACA,cACA,8BAEA,EAIA,YAGA,OAFA,yDACA,kGACA,EAEA,SA7DA,IAOA,GAeA,0BAGA,YAUA,qHACA,KAVA,yDACA,MACA,2GACA,OAGA,MAxBA,yDACA,MACA,6CACA,mCACA,oCACA,+EAGA,aACA,KAhBA,oIACA,aACA,GA4EA,SAASC,GAET,EACA,GAEA,yBACA,wBAEA,2BACA,2BAEA,SACA,yDACA,QACA,wKACsDC,4CAGtD,cAGA,qBAYA,OAXA,UACA,8BACA,wBACA,IAEA,WACA,4DAEA,WACA,6BAEA,EAMA,YACA,EACA,EACA,EACA,EACA,EACA,EACA,GAEA,sBACA,wBAEA,0BAYA,OAXA,UACA,8BACA,wBACA,IAEA,WACA,4DAEA,WACA,6BAEA,EAMA,cACA,YACA,eAGA,oDACA,2CACA,6CAEA,uCACA,yCPjOA,KAIA,MACA,eACA,8BQdA,uBAMA,wBACA,wBAEA,gDAIA,i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YAEA,oBAGA,eASA,OANA,cACA,iBAGA,kCAEA,IAWA,MARA,kBACA,2CAEA,aADA,mCACA,eC7HA,mBACA,aACA,GACA,wBCSA,YACA,EACA,EAEA,YAEA,oBAEA,qCACA,sBAGA,YACA,eAEA,cASA,QAPA,WACA,QAGA,+CAGA,GAGA,aACA,cACA,wBAGA,MAPA,aAQA,IACA,OACA,SAIA,MAHA,iCACA,KACA,IACA,EAkBA,OAfA,eACA,wBACA,KACA,KAEA,IACA,iCACA,KACA,MAIA,IAGA,ECjEA,aAEA,IAAIC,GAAJ,EAKA,cACA,YAMA,cAEA,KACA,gBACA,OAaA,YACA,EACA,EAEA,GACA,GAUA,wBACA,SAGA,IAGA,6BACA,KACA,SAIA,kBACA,SAEA,SAIA,SAKA,mBACA,8CAEA,IACA,yBACA,wBAIA,0BAMA,uBACA,SAqBA,MApBA,KAEA,OACA,wBACA,cACA,mBACA,kBAGA,YACA,QACA,aAGA,IAGA,QAGA,IAOA,IACA,iBACA,4CACA,WAGA,UAIA,iBAEA,sCAGA,IACA,0CACA,cACA,gCACA,QACA,SAKA,UAEA,S1B/FA,YACA,EACA,EACA,EACA,GAEA,cASA,kDAlDA,cACA,IAGA,gBACA,8BACA,uCACA,qEACA,0DA4CA,aAEA,QA2JA,SACA,EACA,EACA,EACA,GAEA,gFACA,OACA,oBACA,oCACA,gBACA,iBACA,IACA,4BAxKA,iBAMA,wBAGA,YADA,e2BzEA,YAkCA,eACA,kCACA,iBAOA,MAJA,cACA,yBAMA,EADA,iBACA,YACA,qBACA,QAEA,EAGA,QAxCA,SAA0BC,GAC1B,WAgBA,OAdA,cACA,gBAEA,OAIA,+CAIA,UAGA,4BAuBA,IAMA,EAwCA,cACA,2BACA,gBACA,SAIA,SA/CA,wBACA,WACA,uBACA,UAGA,SAuBA,iBACA,aAEA,yBACA,iBACA,iBACA,kGCnFA,YACA,EACA,EACA,EACA,GAEA,sDACA,MACA,EACA,qCACA,sCAEA,iDA+DA,cACA,6DAEA,oBACA,0CAGA,4BACA,kBAGA,yBACA,UAGA,YACA,oCAGA,+DACA,aACA,gCAGA,kBACA,WACA,4BAvFA,MAkMA,cACA,aACA,gBACA,qDApMA,WAGA,YA4FA,cACA,4BAEA,MACA,OAGA,MACA,kBACA,EACA,KAEA,UACA,aAIA,sCACA,MACA,iBACA,EACA,KAEA,OACA,YAGA,+BACA,aACA,eACA,mBACA,OAGA,UACA,IAEA,IAEA,+BAEA,gCACA,aACA,8BAIA,WA1IA,kBAKA,QACA,mBACA,uCAIA,WASA,MAEA,qBACA,qDAEA,WACA,iBAKA,sBAGA,kBACA,GA+GA,YAEA,WACA,IAEA,+BAEA,gCACA,aACA,WACA,yBACA,aACA,iCAEA,gBAIA,UAIA,6BACA,OAIA,8BACA,4CACA,4BACA,2BACA,QACA,iBACA,YACA,kBA5IA,IAGA,wBAmKA,gBACA,MACA,YAGA,YACA,KACA,gBACA,sCACA,KACA,SACA,qCAIA,SACA,iCAEA,aACA,yCAEA,UACA,iCAWA,2CACA,kCAGA,wBACA,+DAKA,UACA,wBAEA,SACA,gCAEA,KAIA,SAvNA,QAEA,IAwCA,qBC5EA,MAAMC,GAAqB,8DA4uB3B,SAASC,GAAazC,GACtB,uBAGA,SAAS0C,GAAmB1C,GAC5B,6B,cChxBA,cAAA2C,GAEA,gBAEA,GACA,eACA,aAWA,OARA,WACA,8BAGA,2BACA,sCAGA,EA4CA,cAAAA,GACA,OACA,WACA,mBAMA,YACA,EACA,GAKA,kCAEA,EAcA,SAAoBA,GACpB,MACA,kCACA,qBAGA,sBACA,SAIA,SAzBA,IAEA,IACA,cACA,UAIA,SAIA,MAAMC,GAAsB,8BAqB5B,SAASC,GAAeF,GACxB,qBACA,SAGA,0CACA,gBAEA,EALA,mBAYA,YACA,EACA,EACA,EACA,GAEA,MACA,SADA,gCACA,GAMA,OALA,KACA,gBACA,gBACA,uBAEA,KAOA,YACA,EACA,EAEA,SACA,EACA,GAEA,MACA,SADA,gCACA,GAKA,OAJA,UACA,gBACA,uBAEA,KAMA,YACA,EACA,EACA,EACA,EACA,GAEA,MAEA,4BAGA,YADA,EACA,OAUA,mCACA,UAEA,eACA,cACA,CACA,2DACA,mCACA,cACA,OAOA,MALA,aAEA,kDAGA,EAEA,kBAEA,eAEA,mCASA,OAJA,EAjMA,SACA,EACA,EACA,EACA,GAEA,MACA,EADA,IACA,YACA,mCAEA,GACA,WACA,QACA,CACA,sEACA,wCAIA,OACA,kCAIA,MACA,gBACA,WAEA,6CAIA,SAiKA,GADA,EACA,KACA,KACA,eAEA,EAkBA,OANA,cACA,iBACA,KACA,eAGA,EAMA,YACA,EACA,EACA,EACA,GAEA,SACA,WAGA,SACA,gBACA,WACA,aACA,2CAKA,SAGA,SAASG,GACT,GACA,yBAEA,uBACA,oCAIA,kBACA,4EAGA,mBAEA,iBAMA,SAA4B7P,GAC5B,IACA,iCACA,mCACA,WAXA,eACA,2BAGA,gDC3SA,YACA,GACA,SACA,SACA,MACA,IAqBA,SAdA,CACA,oBACA,oCACA,GACA,QACA,KACA,gBACA,6BAGA,oBAIA,CAGA,SAAwC8P,GAIxC,OAHA,CACA,oBAEA,GATA,MCYA,iBH2CA,MA6BA,eAcA,GAbA,gBACA,sBACA,iCACA,sBACA,kBACA,eAEA,MACA,oBAEA,iHAGA,WACA,wBACA,6BACA,yDACA,mBACA,SASA,wBAEA,QAEA,aADA,oEAIA,oBAUA,OARA,cACA,6BACA,mCACA,SACA,OAIA,EAMA,eACA,EAEA,EACA,EACA,GAEA,oBAEA,uBACA,qCACA,6BAUA,OARA,cACA,EACA,mCACA,SACA,OAIA,EAMA,oBAEA,kDAEA,aADA,oEAIA,oBAQA,OANA,cACA,mCACA,OAIA,EAMA,kBACA,kBAKA,4BACA,+HAEA,oBAEA,iBATA,8GAgBA,SACA,iBAMA,aACA,qBAQA,iBACA,+BAMA,eACA,uBAMA,SACA,wBACA,SACA,wCACA,0BAGA,MAOA,SACA,8BACA,6BACA,IAOA,oBACA,oDACA,mBFzMA,YACA,WASA,OAPA,cAEA,GACA,UAIA,EE+LA,6BACA,kCASA,sBACA,6BAMA,kBACA,IACA,sCACA,SAEA,OADA,+HACA,MAOA,kBACA,yBAMA,kBAGA,GAFA,iCAEA,WACA,mEAEA,iCACA,KACA,EACA,GACA,EACA,6EAKA,8BACA,GACA,iDAQA,eACA,cACA,Q7B3TA,SACA,EACA,EACA,EACA,GAEA,cAUA,SATA,CACA,oCACA,gBACA,eAMA,CAFA,uE6B6SA,2DACA,uBAOA,0BAGA,oCAOA,qBACA,yFAGA,0CA+BA,QACA,iBACA,mBAIA,uBAyBA,aACA,gBAEA,mCAKA,6BACA,SACA,KACA,wCAEA,MACA,KAEA,kBACA,oBACA,sBACA,KACA,QAQA,yBACA,yBAGA,QACA,sBACA,gCAEA,wBAcA,2BACA,iBACA,QACA,MAEA,mBACA,wBACA,iBACA,QAEA,GAPA,EAQA,UACA,iBACA,SAVA,KAkBA,aACA,yDAiBA,qBACA,0BACA,kCAIA,OAHA,6BACA,kBAEA,qBACA,YACA,SAMA,wDAEA,KADA,+BACA,GACA,iDACA,YACA,OACA,WACA,UACA,qBAEA,YAGA,wBAEA,yBACA,4BACA,yBAGA,WAUA,wBACA,sCACA,GACA,WAEA,IACA,2DAGA,UACA,mBACA,iBAEA,aAqBA,qBACA,2BACA,gBAEA,sBACA,mEAGA,cACA,QACA,kBACA,kCAKA,0CAEA,OADA,iDACA,EACA,OACA,yFACA,QAKA,sCAEA,iCACA,SACA,YAEA,MADA,+CACA,yEAIA,GADA,+BAEA,SAIA,OAiHA,SACA,EACA,GAEA,kDACA,kBACA,cACA,IACA,6BACA,gBAEA,UAEA,IACA,0CAGA,6BACA,gBAEA,SArIA,CA2IA,SACA,EACA,EACA,GAEA,8CAEA,YACA,cAGA,YACA,cAGA,SA3JA,QACA,KAEA,SACA,YAEA,MADA,2CACA,yDAGA,2BACA,MACA,kCAMA,2BACA,wCACA,iBACA,uBACA,EACA,UAKA,OADA,oBACA,IAEA,cACA,mBACA,QASA,MANA,yBACA,MACA,eAEA,sBAEA,OACA,mIAQA,YACA,sBACA,OACA,IACA,sBACA,GAEA,IACA,sBACA,IAQA,iBACA,8BAGA,OAFA,8BAEA,uCACA,oGAGA,uFAOA,iBACA,uBAEA,OADA,kBACA,uBACA,wBACA,OACA,SACA,WACA,mBG3qBA,eACA,6CAEA,4BACA,kCACA,iCACA,UACA,CACA,0BACA,aAGA,YAGA,SAEA,kCACA,qDACA,wCACA,wBASA,wBACA,wEAMA,iBACA,EAEA,SACA,GAEA,0EAMA,uBACA,sBAEA,aADA,qHAIA,cACA,+BACA,kBACA,kCAEA,sBAMA,qBAEA,OADA,oCACA,2BAMA,iBACA,8BAEA,gBAEA,aADA,uFAIA,cAEA,aADA,4GAIA,sFAEA,SC7HA,ED6HA,EClHA,GAVA,ED4HA,oCClHA,YAPA,CACA,uBACA,CACA,2BACA,wBATA,IACA,EACA,EACA,ED4HA,uBErIA,IAAIC,QAAJ,ECOA,YACA,EACA,EDiCA,WACA,MACA,UAMA,gBACA,4BAGA,oBACA,eAEA,yCACA,IACA,kCACA,YACA,sBACA,wBACA,aACA,WAEA,sBACA,UACA,yDACA,4FAIA,qBChEA,IAEA,QACA,IA+CA,aA7CA,YACA,sBACA,KACA,IAEA,SACA,YACA,cACA,wBACA,kBAYA,0BACA,gBAGA,IACA,2BACA,KACA,IACA,CACA,oBACA,SACA,6DACA,+CAIA,SAIA,ODwBA,UC1BA,KACA,IACA,SCxCA,eA+BA,aA9BA,YACA,qBACA,2BAEA,YAEA,0BAZ4B,IAa5B,cACA,GACA,oBACA,SACA,mEACA,qDAMA,qBAEA,yBACA,mDACA,mCAIA,oBCTA,SAASC,GAAYC,EAArBhK,EAAA,KACA,SACA,WACA,WACA,WAWA,YARA,QACA,iBAGA,QACA,WAGA,EAIA,MAAMiK,GACN,6IACMC,GAAkB,gCA6BxB,IAtDwB,GA2BxB,IACA,mBAEA,MAGA,GAFA,+BAEA,CACA,sBAEA,IAEA,UACA,UACA,WAMA,oBAlDyB,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,SAASC,KACT,YACA,gBACA,sBACA,mBACA,qBAEA,2CA1LA,kBCvEA,MAAMC,GAAuB,CAC7B,cACA,SACA,OACA,mBACA,iBACA,mBACA,oBACA,kBACA,cACA,aACA,qBACA,cACA,aACA,iBACA,eACA,kBACA,cACA,cACA,eACA,qBACA,SACA,eACA,YACA,eACA,gBACA,YACA,kBACA,SACA,iBACA,4BACA,wBAeA,SAIA,yCAaA,eACA,gBACA,eACA,kBACA,eACA,yBACA,eACA,iBACA,GAQA,YACA,0BACA,gCAGA,2BACA,iCAGA,qCACA,2CAGA,qDACA,gDAGA,kCACA,OACA,uBACA,cAMA,SAASC,GAAkBC,GAE3B,sBACA,aAQA,OAPA,WACA,WACA,gCACA,WACA,qBAGA,iBAMA,SAASC,GAASD,GAElB,mBAEA,qBACA,MACA,WACA,MACA,iCACA,yBAEA,WACA,wBAQA,SAASE,GAASC,GAElB,sBAEA,aA8BA,MA7BA,uDAEA,YACA,iCAEA,6BACA,SACA,WACA,MACA,WACA,yBAEA,WACA,oBAKA,iBAMA,OALA,IACA,0CAIA,aAKA,iBAKA,SAASC,GAAiBxO,GAE1B,WAEA,uBAGA,4DAIA,8CAKA,gBAGA,EACA,EACA,GAEA,IACA,mCAOA,gCACA,WACA,MACA,uBACA,wBACA,UAEA,WACA,sBAIA,UAIA,qBACA,EAEA,MACA,WACA,MACA,4BACA,wBACA,UAEA,WACA,qBAGA,QAKA,YACA,EACA,uBACA,SACA,GAGA,gBAGA,EACA,EACA,GAmBA,UACA,IACA,gCACA,GACA,mBAEA,UAGA,+BAzLA,kBC9FA,0DAoBA,eACA,kDClBA,eACA,MACA,SAGA,gFAEA,MACA,SAIA,iBACA,WACA,OACA,UACA,UACA,cACA,SACA,OACA,mBCWA,SAIA,4CAgBA,eACA,gBACA,cACA,WACA,OACA,SACA,WACA,UACA,UACA,GAYA,YA4CA,IAAwByO,EA5BxB,GAfA,sBACA,iBAEA,kBACA,UAuCwBA,EAvCxB,iBAwCA,YACA,MACA,iDAEA,EACA,gFACA,KAlGkC,QAmGlC,yDACA,OACA,iHAEA,EAvGkC,MA0GlC,qBACA,OAIA,IACA,gBACA,EAoMA,SAAkBzE,GAClB,sBArMA,IACA,sDACA,+CACA,SACA,cAGA,cAIA,kBACA,CACA,sBACA,WAEA,CACA,cACA,YACA,qBA9EA,kBACA,aAEA,oBACA,eAEA,sBACA,iBAEA,qBACA,wBACA,sCAQA,SAAS0E,GAAoB1E,GAC7B,kBACA,CACA,kEACA,oBACA,cACA,cAEA,CACA,UA6DA,SAAS2E,GAAmBC,GAO5B,gCACA,2BACA,sBACA,MAGA,SACA,mBACA,MACA,iBACA,kBAEA,kBACA,iCAGA,uBACA,kBAKA,OAJA,oFACA,iCAOA,qBACA,aACA,gBAOA,SAASC,GAAeD,GACxB,yCAEA,0BAGA,cACA,OAGA,6CAEA,GACA,SACA,MACA,eAGA,GACA,UACA,QACA,iBACA,gBAGA,kBACA,CACA,eACA,OACA,aAEA,GAOA,SAASE,GAAiBF,GAC1B,yCAGA,QAIA,kEAKA,YACA,oBACA,GACA,aACA,aACA,iBACA,gBAGA,kBACA,CACA,iBACA,OACA,cACA,aAEA,OAEA,CACA,YACA,YACA,2CAEA,GACA,aACA,oBACA,iBACA,gBAEA,kBACA,CACA,iBACA,OACA,aAEA,IAQA,SAASG,GAAmBH,GAC5B,aACA,OACA,6BACA,YACA,cAGA,SACA,KAKA,2CACA,cAEA,2CACA,cAGA,mBACA,sBACA,MACA,OACA,QCjVA,YACA,EACA,EACA,MACA,EACA,EACA,EACA,GAEA,iFACA,OAIA,QACA,mFAiHA,IAAqCI,EAArC,EA9GA,IACA,oBA6GqCA,EA7FrC,SAASC,EACT,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GAEA,iBACA,SAGA,aAEA,4BACA,QACA,kBACA,WACA,YACA,IACA,EACA,EACA,EACA,KACA,EACA,SACA,EACA,GA2BA,OArBA,yBACA,yBACA,yBACA,QACA,eACA,WACA,yBACA,IACA,EACA,EACA,EACA,EACA,EACA,SACA,EACA,MAMA,EAvEA,CACA,EACA,EACA,EACA,oBACA,EACA,mBACA,EACA,GAoGA,EAlGA,EAmGA,UACA,UACA,gCAEA,MAvCA,SAASC,GAA4CC,EAArD,GAEA,qDAEA,gBACA,YACA,sBACA,gBAIA,SAASC,GACT,EACA,EACA,EACA,GAGA,qDAEA,gBACA,YACA,eACA,SACA,eACA,aDlBA,kBE/FA,SAIA,6CAoBA,kBACA,gBACA,iBAnCoB,QAoCpB,qBAnCsB,EAyCtB,eACA,UACA,YACA,gBACA,uBAEA,UACA,SAGA,uBAWA,OAVA,GACA,GACA,cACA,iBACA,OACA,SACA,EACA,GAGA,KAGA,kBCjEA,SAIA,4CAOA,cACA,gBAMA,YACA,MACA,2BAEA,6CACA,SAIA,iEACA,6BACA,8BAEA,MACA,gCACA,kBACA,qBAEA,yCAEA,uBAEA,YAGA,kBC7CA,SAIA,uCAYA,cACA,gBAMA,eACA,YAGA,UACA,SAGA,+BACA,MAEA,IACA,GAmBA,cACA,MACA,SAGA,GAYA,SAA6BC,EAA7B,GACA,kBACA,YAGA,UACA,SAIA,gBACA,SAGA,SACA,SAGA,YACA,SAGA,YACA,SAGA,SAtCA,MACA,SAGA,GAsCA,SAA+BA,EAA/B,GACA,cACA,QAEA,UACA,SAGA,sCACA,SAGA,YACA,SAGA,YACA,SAGA,SA1DA,MACA,SAGA,SAhCA,qBAEA,OADA,wIACA,KAEA,SACA,0BAGA,0BAEA,UAGA,eACA,MA4EA,SAASC,GAAkBD,EAA3B,GACA,YACA,QAGA,UACA,SAIA,gBACA,SAOA,GAJA,IACA,IAGA,oBACA,SAIA,4BACA,aACA,OAEA,GACA,yBACA,qBACA,mBACA,wBAEA,SAIA,SAIA,SAASE,GAAmBF,EAA5B,GACA,oBACA,gBAGA,UACA,SAIA,gBACA,SAGA,IACA,IAGA,IACA,iCACA,SACA,UAKA,SAASG,GAAuBxF,GAChC,8DAIA,SAASyF,GAAoBzF,GAC7B,oBAEA,KACA,IAEA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A,IAAI0J,IAAmB,EAEvB,MAaA,QAGA,OAKA,GAlBA,uEAKA,qBACA,OACA,IAcA,CACA,sBACA,aCvBMC,GAAN,GClBA,eACA,sCAQA,uCAKA,OAJA,wBACA,oBAGA,cACA,oBACA,ICHA,SAASC,GAAQx9C,GACjB,aAGA,SAASy9C,KAET,+CAGA,IAGIC,GACAC,GAJAC,GAAJ,EAEIC,GAAJ,GASA,cACA,aACA,WAEA,QACA,2CCZA,KACA,aACA,YAEA,MAEA,YAEA,gCACA,sCACA,kBACA,QAIA,MACA,cAGA,sBACA,UAEA,GACA,QACA,mBACA,iBACA,ID6FA,KACA,wBACA,MACA,OAGA,gBACA,mBACA,4FACA,0CACA,2CAlHA,QEJA,KACA,oBACA,MAEA,IACA,KAGA,YACA,cAEA,sBACA,aACA,gBAMA,GACA,cACA,6BACA,6BAEA,WACA,YAEA,UACA,OAKA,YACA,UACA,YACA,GACA,SAOA,uBACA,MACA,UAEA,aACA,mBACA,OAKA,OAFA,MAEA,IFyBA,KACA,wBACA,KAIA,4FACA,+BACA,QAnFA,EFhBA,KACA,aACA,YACA,MAEA,YACA,sBACA,MAKA,qCAGA,sBACA,UACA,cACA,OAKA,mCAEA,MACA,UAEA,aACA,WACA,mBACA,eACA,YACA,QAaA,MANA,gCACA,6CAGA,SAEA,IE2DA,KACA,wBACA,KAIA,4FACA,0CACA,QA/FA,WACA,GACA,IAEA,GACA,KAKA,aA0GA,eACA,aACA,wCAEA,QAGA,2HACA,gBAEA,iBAEA,MACA,EAqDA,GAlDA,wBACA,wBACA,iBAEA,gDAIA,oBACA,kBA8IA,SAA6B5rC,EAA7B,KACA,qFACA,cAEA,oDACA,8CACA,+BA8BA,SAAqBA,EAArB,KACA,MACA,aACA,sCACA,sBACA,oCACA,mCAGA,MACA,aACA,sCACA,uBACA,qCACA,mCA3CA,QApJA,QACA,wBACA,uBACA,MAEA,WACA,YACA,gBA8GA,SACA,EAEA,EACA,EACA,EACA,GAEA,YACA,MAEA,MACA,mBACA,eACA,eACA,uCACA,mBA7HA,YAGA,aAEA,gCAEA,6BACA,2FACA,8CAEA,wCACA,4FACA,+CAEA,MAEA,gBACA,+CAkLA,SACA,EACA,EACA,EACA,EACA,EACA,GAIA,iEACA,OAIA,WACA,qBACA,iDAEA,wBACA,qDAEA,wBACA,6DAEA,6BACA,6DAGA,YAGA,MACA,cACA,aAJA,IAKA,gEACA,uCACA,iBACA,SAvNA,cACA,UAOA,0BAsNA,SAAyBA,GACzB,qBACA,MACA,OAIA,qBACA,IACA,iBACA,oDAGA,QACA,kCAGA,YACA,wDAIA,oBACA,8CAGA,2BACA,8DA/OA,IAGA,mBAGA,sBACA,6FACA,SACA,+BACA,oBAGA,2BAGA,wBACA,gBACA,sBAKA,+BACA,+BACA,OAKA,oBACA,UAGA,qCACA,OAEA,yDACA,iEACA,gBAGA,uBACA,YAEA,MACA,gCACA,sCACA,eACA,iCACA,gCAIA,gBAKA,mBACA,OAGA,4BACA,iBACA,EACA,YACA,cAiLA,SAAwBA,GACxB,MACA,iGAIA,YACA,iDAGA,OACA,yBAGA,QAEA,+CAGA,8BAIA,kBACA,iGACA,0BACA,qDAvMA,IAGA,UACA,UACA,MAuCA,SAAS6rC,GACT,EAEA,EACA,EACA,EACA,EACA,GAEA,0BACA,eACA,MAGA,MACA,aACA,sCACA,iBACA,uBACA,uBG7VA,mCAsGA,IACA,cACA,YACA,qBAEA,kBACA,4BAIA,eACA,iBACA,WACA,0BAEA,iBAEA,6BACA,oBACA,GACA,CACA,yBACA,wBACA,GAGA,EACA,6BAKA,KAyHA,cACA,4BAzHA,SAEA,KAEA,GACA,eACA,QA2HA,SACA,EACA,EACA,EACA,GAEA,uBACA,OAGA,2BAEA,sBACA,2BACA,aAEA,aACA,MACA,eAGA,mCAEA,QAEA,yEAEA,cACA,KACA,iDAEA,SACA,8BAEA,kBAGA,KAEA,OAGA,YACA,eACA,gBACA,eAEA,4BAEA,EACA,KACA,cACA,MACA,MACA,aACA,iBAEA,wBACA,iBACA,kCAEA,EAEA,IACA,4BACA,eAGA,0BACA,kBAGA,wBAGA,kBAGA,UASA,SACA,EACA,EACA,EACA,EAOA,GAEA,uBAEA,oBAEA,qDAEA,qCAOA,KANA,EACA,8BACA,GAEA,WAIA,EACA,wEAEA,KAEA,yDACA,uBAUA,OARA,2BAEA,GAGA,SjFjZA,UiFiZA,GAGA,EACA,qBACA,kCAQA,OANA,GAGA,QjF3ZA,UiF2ZA,IAGA,EACA,CACA,uCACA,KAYA,OAVA,iBACA,aACA,GACA,UAGA,GACA,UAGA,IACA,EACA,iBACA,wCAxCA,mCAzCA,YAGA,SA5MA,UACA,MACA,QAKA,GACA,aACA,QA4RA,SACA,EACA,EACA,EACA,GAEA,cACA,yBAEA,8CACA,OAGA,iBAGA,sBACA,iCACA,aAEA,aAQA,YAPA,IACA,+BACA,kBAGA,OAKA,YACA,eACA,cAEA,EACA,KACA,cACA,SACA,OACA,WACA,uBACA,WAEA,mCACA,iBACA,kCAEA,EAEA,IACA,kCACA,+BAGA,gCACA,MACA,yBAEA,KADA,kCAEA,8BACA,CACA,uBACA,qDACA,iBAGA,KADA,yBAEA,UAIA,SApWA,UACA,MACA,QAqBA,SAASC,GAAe3tC,GACxB,mBACA,8BACA,eACA,YACA,GApBA,SAAqCwhC,GACrC,MACA,0BACA,qBACA,qCACA,+DAeA,0BA+CA,SAAuCoM,GACvC,wBA9BA,YACA,gBACA,YACA,KACA,kBAEA,aACA,kBACA,MAGA,sBACA,mBACA,gBACA,MAEA,KAEA,QAEA,KAEA,yBAQA,oBAEA,KAIA,GAFA,oEAEA,IACA,SAEA,UACA,EACA,oDACA,8CACA,6DACA,yDACA,kDACA,qEACA,iDACA,kDACA,oDACA,kDAnEA,IACA,4BACA,oBAIA,WACA,0BAmCA,SAAS,GAAT,KACA,4CA+RA,SAASC,GACT,EACA,EACA,GAEA,IAEA,qCACA,GAKA,mBjFnhBA,UiFmhBA,GAEA,WCxgBA,MAoHMC,GAAN,IACA,GACA,8BACA,uBCjIA,SACA,EACA,KACA,MAEA,qBAEA,aADA,yIAIA,IAEA,EAFA,mBAGA,IACA,KACA,0BAEA,kCACA,cACA,+BACA,2BAIA,GACA,oCAUA,4BACA,SAIA,QACA,SACA,KACA,yHAEA,YAEA,KACA,0BACA,gBACA,iCACA,8BD+EA,oCACA,8BACA,kBACA,mBACA,IAUA,SAuBA,eACA,UA9JA,iBA+JA,uCAEA,MAEA,0DACA,uCACA,IAEA,+CAIA,iBACA,MACA,QAKA,+CACA,sEAOA,kDAEA,uDAGA,4BACA,6BJ5HA,cAnBA,IACA,kBACA,aACA,MACA,OAEA,4BACA,iBAEA,cACA,qCACA,kBACA,iCACA,iBACA,sBIoIA,8CJlGA,WAtBA,IACA,kBACA,aACA,MACA,OAGA,qBACA,4BACA,iBAEA,cACA,mCACA,4BACA,iCACA,iBACA,sBAMA,uBI0GA,eACA,sBACA,MACA,EADA,IACA,YACA,qBAGA,0DACA,6BACA,6BACA,aACA,WACA,6BACA,oBACA,eACA,GACA,aAEA,+BAYA,2CACA,iGACA,OACA,0KAIA,EACA,IACA,wCAKA,OAHA,mDACA,yDAEA,GAEA,EACA,GAGA,IEpQA,gBACA,qDACA,aACA,0BACA,qBAEA,yDACA,MACA,iFAIA,UACA,eAEA,+CACA,eAIA,yDACA,8FFmPA,sBACA,oCAGA,IACA,aACA,WACA,0BACA,6BACA,sBAKA,2BACA,wBAGA,aAFA,yDACA,2FAIA,+BAEA,gFAEA,oBAEA,0BACA,sBACA,oEACA,EACA,GAGA,MACA,KACA,EACA,aACA,WACA,mCAEA,YAGA,8BAIA,iCAGA,WACA,gBACA,gCACA,WAEA,6BACA,uDAEA,gBACA,yDACA,iFAGA,kHAEA,qBAEA,KACA,EACA,EACA,EACA,GACA,EACA,aACA,GAGA,eAsBA,OAlBA,KACA,2BAIA,yBACA,kBACA,gBACA,4BACA,oBAIA,mCACA,yBACA,QAGA,EAIA,+BACA,MACA,aACA,qEACA,oBAEA,OACA,qDAKA,aAJA,yDACA,OACA,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AU,GACVC,GAAa,GAAjB,sCACIC,GAAW,GACf,MAAMC,GACN,qCACA,iEACA,GAsBA,MAAMC,GAAgB,GAAtB,sCALA,IAAyBluC,GAiCzB,eACA,OAVA,SAAkCmuC,GAClC,+BASA,IAuHA,YACA,aACA,IAGA,SACA,WACA,UACA,UACA,iBACA,WA/LoB,UAmMpB,qBACA,SAIA,+BAKA,EACA,sEACA,aAEA,oCACA,qBAGA,4BACA,QACA,IACA,eACA,KAGA,cAEA,wBAlOiB,KAkOjB,6BACA,WACA,cAEA,SAGA,0BAIA,WAEA,SACA,kBAEA,iCAGA,0BACA,qBACA,gBACA,wEACA,cACA,iBAIA,kDAGA,SAEA,wBAnQiB,KAmQjB,6BACA,WACA,cAGA,cACA,eACA,IAGA,SAvMA,IAHA,EA2CA,YACA,EACA,EACA,GAEA,0BAGA,uGAGA,WACA,oBACA,wFAIA,QA9CA,SAAoB94C,GACpB,mEASA,MALA,oCACA,yDACA,6DAGA,mBACA,GAGA,EAgCA,IACA,QACA,sEACA,0DAyCA,MAvCA,CACA,WACA,oCACA,sBACA,YACA,sBACA,6BACA,SACA,kBACA,gCAEA,IACA,QACA,WACA,iBAEA,QACA,UACA,SACA,gBACA,gBACA,gBAEA,YACA,wBAEA,UACA,cACA,CACA,uBACA,mBACA,WACA,oBACA,sBACA,0CArIA,iBADyB2K,GAOLkuC,KANpB,wCAOA,GACA,8FACA,SAMA,GALA,kBACA,sBACA,eACA,yBAEA,+CACA,sDACA,gCAGA,aAoQA,MAAM,GAAN,YAIA,eACA,4BAEA,MACA,SAGA,YACA,MACA,SAEA,sBACA,MACA,SAEA,uBACA,MACA,SAEA,sBACA,MACA,SAGA,MACA,kBACA,EACA,KAEA,UACA,aAIA,sCACA,MAEA,iBACA,EACA,KAEA,OACA,YAGA,+BACA,aACA,gBAEA,SACA,UACA,OAGA,UACA,IAEA,KACA,iBACA,SACA,QACA,iBACA,YACA,gBAKA,SA0DA,mBACA,OA3BA,SAAwBC,GACxB,4BACA,y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,iFAGA,kBCvFA,IAAIC,GAAqB,GAGrB,GAAJ,iCACA,2BAGA,MAAMC,GAAe,IACrB,MACA,KACA","file":"2.maestro-web-sdk.esm.js","sourcesContent":["/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Integration } from '@sentry/types';\n\nimport type { SdkSource } from './env';\n\n/** Internal global with common properties and Sentry extensions */\nexport interface InternalGlobal {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: {\n Integrations?: Integration[];\n };\n onerror?: {\n (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record<string, string>;\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record<string, any>;\n}\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj: { Math?: Math }): any | undefined {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ: InternalGlobal =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function (this: any) {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nexport function getGlobalObject<T>(): T & InternalGlobal {\n return GLOBAL_OBJ as T & InternalGlobal;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton<T>(name: keyof InternalGlobal['__SENTRY__'], creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record<string, unknown> {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike<any> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isNaN(wat: unknown): boolean {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other\n * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: { [key: string]: unknown }, name: string, value: unknown): void {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject<V>(value: V):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '<unknown>';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record<string, unknown>)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record<string, unknown>, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys<T>(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map<unknown, unknown>();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys<T>(inputValue: T, memoizationMap: Map<unknown, unknown>): T {\n if (isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * 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.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] as const;\nexport type ConsoleLevel = (typeof CONSOLE_LEVELS)[number];\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record<ConsoleLevel, LoggerMethod>;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox<T>(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial<LoggerConsoleMethods> = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial<Logger> = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if (__DEBUG_BUILD__) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n","import { isRegExp, isString, isVueViewModel } from './is';\n\nexport { escapeStringForRegex } from './vendor/escapeStringForRegex';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nexport function isMatchingPattern(\n value: string,\n pattern: RegExp | string,\n requireExactStringMatch: boolean = false,\n): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nexport function stringMatchesSomePattern(\n testString: string,\n patterns: Array<string | RegExp> = [],\n requireExactStringMatch: boolean = false,\n): boolean {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n","module.exports = function(originalModule) {\n\tif (!originalModule.webpackPolyfill) {\n\t\tvar module = Object.create(originalModule);\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"exports\", {\n\t\t\tenumerable: true\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","import type { StackFrame, StackLineParser, StackParser } from '@sentry/types';\n\nimport type { GetModuleFn } from './node-stack-trace';\nimport { filenameIsInApp, node } from './node-stack-trace';\n\nexport { filenameIsInApp };\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nexport function createStackParser(...parsers: StackLineParser[]): StackParser {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack: string, skipFirst: number = 0): StackFrame[] => {\n const frames: StackFrame[] = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nexport function stackParserFromStackParserOptions(stackParser: StackParser | StackLineParser[]): StackParser {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nexport function stripSentryFramesAndReverse(stack: ReadonlyArray<StackFrame>): StackFrame[] {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // 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)\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '<anonymous>';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nexport function nodeStackLineParser(getModule?: GetModuleFn): StackLineParser {\n return [90, node(getModule)];\n}\n","import { isString } from './is';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject<Window>();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\n if (!elem) {\n return '<unknown>';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '<unknown>';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement<Element>('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getDomElement<E = any>(selector: string): E | null {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) as unknown as E;\n }\n return null;\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` attribute. This attribute is added at build-time\n * by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n","import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n","/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\nimport { isBrowserBundle } from './env';\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule<T>(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\ndeclare const __SENTRY_BROWSER_BUNDLE__: boolean | undefined;\n\nexport type SdkSource = 'npm' | 'cdn' | 'loader';\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nexport function isBrowserBundle(): boolean {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nexport function getSDKSource(): SdkSource {\n // @ts-ignore __SENTRY_SDK_SOURCE__ is injected by rollup during build process\n return __SENTRY_SDK_SOURCE__;\n}\n","import type { Primitive } from '@sentry/types';\n\nimport { isNaN, isSyntheticEvent, isVueViewModel } from './is';\nimport type { MemoFunc } from './memo';\nimport { memoBuilder } from './memo';\nimport { convertToPlainObject } from './object';\nimport { getFunctionName } from './stacktrace';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n// This is a hack to placate TS, relying on the fact that technically, arrays are objects with integer keys. Normally we\n// think of those keys as actual numbers, but `arr['0']` turns out to work just as well as `arr[0]`, and doing it this\n// way lets us use a single type in the places where behave as if we are only dealing with objects, even if some of them\n// might be arrays.\ntype ObjOrArray<T> = { [key: string]: T };\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function normalize(input: unknown, depth: number = 100, maxProperties: number = +Infinity): any {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nexport function normalizeToSize<T>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized as T;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key: string,\n value: unknown,\n depth: number = +Infinity,\n maxProperties: number = +Infinity,\n memo: MemoFunc = memoBuilder(),\n): Primitive | ObjOrArray<unknown> {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))\n ) {\n return value as Primitive;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value as ObjOrArray<unknown>)['__sentry_skip_normalization__']) {\n return value as ObjOrArray<unknown>;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value as ObjOrArray<unknown>)['__sentry_override_normalization_depth__'] === 'number'\n ? ((value as ObjOrArray<unknown>)['__sentry_override_normalization_depth__'] as number)\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value as unknown & { toJSON?: () => unknown };\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // 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\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) as ObjOrArray<unknown>;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value as ObjOrArray<unknown>);\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * @deprecated This export will be removed in v8.\n */\nexport { visit as walk };\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key: unknown,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value: Exclude<unknown, string | number | boolean | null>,\n): string {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value as { _events: unknown })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value: unknown): string {\n const prototype: Prototype | null = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nexport function normalizeUrlToBase(url: string, basePath: string): string {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport type MemoFunc = [\n // memoize\n (obj: any) => boolean,\n // unmemoize\n (obj: any) => void,\n];\n\n/**\n * Helper to decycle json objects\n */\nexport function memoBuilder(): MemoFunc {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner: any = hasWeakSet ? new WeakSet() : [];\n function memoize(obj: any): boolean {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj: any): void {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n","/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = debounce;\n","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n public constructor() {\n this.name = FunctionToString.id;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function (this: WrappedFunction, ...args: any[]): string {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '<unknown>';\n }\n return eventId || '<unknown>';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial<Mechanism>): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify<T = unknown>(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n","import type { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, logger, stringMatchesSomePattern } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*healthcheck.*$/,\n /^.*healthy.*$/,\n /^.*live.*$/,\n /^.*ready.*$/,\n /^.*heartbeat.*$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\nexport interface InboundFiltersOptions {\n allowUrls: Array<string | RegExp>;\n denyUrls: Array<string | RegExp>;\n ignoreErrors: Array<string | RegExp>;\n ignoreTransactions: Array<string | RegExp>;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n disableTransactionDefaults: boolean;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private readonly _options: Partial<InboundFiltersOptions>;\n\n public constructor(options: Partial<InboundFiltersOptions> = {}) {\n this.name = InboundFilters.id;\n this._options = options;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcess: EventProcessor = (event: Event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n}\n\n/** JSDoc */\nexport function _mergeOptions(\n internalOptions: Partial<InboundFiltersOptions> = {},\n clientOptions: Partial<InboundFiltersOptions> = {},\n): Partial<InboundFiltersOptions> {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nexport function _shouldDropEvent(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (options.ignoreInternal && _isSentryError(event)) {\n __DEBUG_BUILD__ &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event: Event, ignoreErrors?: Array<string | RegExp>): boolean {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array<string | RegExp>): boolean {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event: Event, denyUrls?: Array<string | RegExp>): boolean {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event: Event, allowUrls?: Array<string | RegExp>): boolean {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n const { values } = event.exception;\n try {\n const { type = '', value = '' } = (values && values[values.length - 1]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event: Event): boolean {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event: Event): string | null {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n __DEBUG_BUILD__ && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n","export const DEFAULT_ENVIRONMENT = 'production';\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 0,\n /** Resolved / OK */\n RESOLVED = 1,\n /** Rejected / Error */\n REJECTED = 2,\n}\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\nexport function resolvedSyncPromise(): PromiseLike<void>;\nexport function resolvedSyncPromise<T>(value: T | PromiseLike<T>): PromiseLike<T>;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nexport function resolvedSyncPromise<T>(value?: T | PromiseLike<T>): PromiseLike<T> {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nexport function rejectedSyncPromise<T = never>(reason?: any): PromiseLike<T> {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise<T> implements PromiseLike<T> {\n private _state: States;\n private _handlers: Array<[boolean, (value: T) => void, (reason: any) => any]>;\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike<T> | null) => void, reject: (reason?: any) => void) => void,\n ) {\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): PromiseLike<TResult1 | TResult2> {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result as any);\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n public catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): PromiseLike<T | TResult> {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally<TResult>(onfinally?: (() => void) | null): PromiseLike<TResult> {\n return new SyncPromise<TResult>((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val as unknown as any);\n });\n });\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike<T> | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike<T> | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike<T>).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value as unknown as any);\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };\n}\n\nexport { SyncPromise };\n","import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit<SessionContext, 'started' | 'status'>): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude<SessionStatus, 'ok'>): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n","/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n Severity,\n SeverityLevel,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { getGlobalEventProcessors, notifyEventProcessors } from './eventProcessors';\nimport { updateSession } from './session';\nimport { applyScopeDataToEvent } from './utils/applyScopeDataToEvent';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * The global scope is kept in this module.\n * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present.\n */\nlet globalScope: ScopeInterface | undefined;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n protected _level?: Severity | SeverityLevel;\n\n /**\n * Transaction Name\n */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @deprecated Use `scope.clone()` and `new Scope()` instead.\n */\n public static clone(scope?: Scope): Scope {\n return scope ? scope.clone() : new Scope();\n }\n\n /**\n * Clone this scope instance.\n */\n public clone(): Scope {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._span = this._span;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n\n return newScope;\n }\n\n /** Update the client on the scope. */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * Get the client assigned to this scope.\n *\n * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing.\n */\n public getClient(): Client | undefined {\n return this._client;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n segment: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel,\n ): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope for future events.\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the Span on the scope.\n * @param span Span\n * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead.\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Returns the `Span` if there is one.\n * @deprecated Use `getActiveSpan()` instead.\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * Returns the `Transaction` attached to the scope (if there is one).\n * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead.\n */\n public getTransaction(): Transaction | undefined {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this._span;\n // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction\n // Also, this method will be removed anyway.\n // eslint-disable-next-line deprecation/deprecation\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n if (scopeToMerge instanceof Scope) {\n const scopeData = scopeToMerge.getScopeData();\n\n this._tags = { ...this._tags, ...scopeData.tags };\n this._extra = { ...this._extra, ...scopeData.extra };\n this._contexts = { ...this._contexts, ...scopeData.contexts };\n if (scopeData.user && Object.keys(scopeData.user).length) {\n this._user = scopeData.user;\n }\n if (scopeData.level) {\n this._level = scopeData.level;\n }\n if (scopeData.fingerprint.length) {\n this._fingerprint = scopeData.fingerprint;\n }\n if (scopeToMerge.getRequestSession()) {\n this._requestSession = scopeToMerge.getRequestSession();\n }\n if (scopeData.propagationContext) {\n this._propagationContext = scopeData.propagationContext;\n }\n } else if (isPlainObject(scopeToMerge)) {\n const scopeContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...scopeContext.tags };\n this._extra = { ...this._extra, ...scopeContext.extra };\n this._contexts = { ...this._contexts, ...scopeContext.contexts };\n if (scopeContext.user) {\n this._user = scopeContext.user;\n }\n if (scopeContext.level) {\n this._level = scopeContext.level;\n }\n if (scopeContext.fingerprint) {\n this._fingerprint = scopeContext.fingerprint;\n }\n if (scopeContext.requestSession) {\n this._requestSession = scopeContext.requestSession;\n }\n if (scopeContext.propagationContext) {\n this._propagationContext = scopeContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `getScopeData()` instead.\n */\n public getAttachments(): Attachment[] {\n const data = this.getScopeData();\n\n return data.attachments;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n const {\n _breadcrumbs,\n _attachments,\n _contexts,\n _tags,\n _extra,\n _user,\n _level,\n _fingerprint,\n _eventProcessors,\n _propagationContext,\n _sdkProcessingMetadata,\n _transactionName,\n _span,\n } = this;\n\n return {\n breadcrumbs: _breadcrumbs,\n attachments: _attachments,\n contexts: _contexts,\n tags: _tags,\n extra: _extra,\n user: _user,\n level: _level,\n fingerprint: _fingerprint || [],\n eventProcessors: _eventProcessors,\n propagationContext: _propagationContext,\n sdkProcessingMetadata: _sdkProcessingMetadata,\n transactionName: _transactionName,\n span: _span,\n };\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n * @deprecated Use `applyScopeDataToEvent()` directly\n */\n public applyToEvent(\n event: Event,\n hint: EventHint = {},\n additionalEventProcessors: EventProcessor[] = [],\n ): PromiseLike<Event | null> {\n applyScopeDataToEvent(event, this.getScopeData());\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors: EventProcessor[] = [\n ...additionalEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n ...this._eventProcessors,\n ];\n\n return notifyEventProcessors(eventProcessors, event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @param exception The exception to capture.\n * @param hint Optinal additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @param message The message to capture.\n * @param level An optional severity level to report the message with.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured message.\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Captures a manually created event for this scope and sends it to Sentry.\n *\n * @param exception The event to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): ScopeInterface {\n if (!globalScope) {\n globalScope = new Scope();\n }\n\n return globalScope;\n}\n\n/**\n * This is mainly needed for tests.\n * DO NOT USE this, as this is an internal API and subject to change.\n * @hidden\n */\nexport function setGlobalScope(scope: ScopeInterface | undefined): void {\n globalScope = scope;\n}\n\nfunction generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport {\n GLOBAL_OBJ,\n consoleSandbox,\n dateTimestampInSeconds,\n getGlobalSingleton,\n isThenable,\n logger,\n uuid4,\n} from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport { SDK_VERSION } from './version';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = parseFloat(SDK_VERSION);\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\nexport interface RunWithAsyncContextOptions {\n /** Whether to reuse an existing async context if one exists. Defaults to false. */\n reuseExisting?: boolean;\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Strategy used to track async context.\n */\nexport interface AsyncContextStrategy {\n /**\n * Gets the current async context. Returns undefined if there is no current async context.\n */\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub: () => Hub | undefined;\n /**\n * Runs the supplied callback in its own async context.\n */\n runWithAsyncContext<T>(callback: () => T, options: RunWithAsyncContextOptions): T;\n}\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n // eslint-disable-next-line deprecation/deprecation\n hub?: Hub;\n acs?: AsyncContextStrategy;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects.\n *\n * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information:\n * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/)\n * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/)\n *\n * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated\n * themselves and will also be removed in version 8. More information:\n * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub)\n */\n// eslint-disable-next-line deprecation/deprecation\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n private _isolationScope: Scope;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n *\n * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK.\n *\n * If you are currently using the Hub for multi-client use like so:\n *\n * ```\n * // OLD\n * const hub = new Hub();\n * hub.bindClient(client);\n * makeMain(hub)\n * ```\n *\n * instead initialize the client as follows:\n *\n * ```\n * // NEW\n * Sentry.withIsolationScope(() => {\n * Sentry.setCurrentClient(client);\n * client.init();\n * });\n * ```\n *\n * If you are using the Hub to capture events like so:\n *\n * ```\n * // OLD\n * const client = new Client();\n * const hub = new Hub(client);\n * hub.captureException()\n * ```\n *\n * instead capture isolated events as follows:\n *\n * ```\n * // NEW\n * const client = new Client();\n * const scope = new Scope();\n * scope.setClient(client);\n * scope.captureException();\n * ```\n */\n public constructor(\n client?: Client,\n scope?: Scope,\n isolationScope?: Scope,\n private readonly _version: number = API_VERSION,\n ) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n assignedScope.setClient(client);\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n assignedIsolationScope.setClient(client);\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n\n if (client) {\n // eslint-disable-next-line deprecation/deprecation\n this.bindClient(client);\n }\n\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Checks if this hub's version is older than the given version.\n *\n * @param version A version number to compare to.\n * @return True if the given version is newer; otherwise false.\n *\n * @deprecated This will be removed in v8.\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * This binds the given client to the current scope.\n * @param client An SDK client (client) instance.\n *\n * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead.\n */\n public bindClient(client?: Client): void {\n // eslint-disable-next-line deprecation/deprecation\n const top = this.getStackTop();\n top.client = client;\n top.scope.setClient(client);\n // eslint-disable-next-line deprecation/deprecation\n if (client && client.setupIntegrations) {\n // eslint-disable-next-line deprecation/deprecation\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.getScope().clone();\n // eslint-disable-next-line deprecation/deprecation\n this.getStack().push({\n // eslint-disable-next-line deprecation/deprecation\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `withScope` instead.\n */\n public popScope(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n if (this.getStack().length <= 1) return false;\n // eslint-disable-next-line deprecation/deprecation\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.withScope()` instead.\n */\n public withScope<T>(callback: (scope: Scope) => T): T {\n // eslint-disable-next-line deprecation/deprecation\n const scope = this.pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return res;\n },\n e => {\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n throw e;\n },\n );\n }\n\n // eslint-disable-next-line deprecation/deprecation\n this.popScope();\n return maybePromiseResult;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.getClient()` instead.\n */\n public getClient<C extends Client>(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n *\n * @deprecated Use `Sentry.getCurrentScope()` instead.\n */\n public getScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return this.getStackTop().scope;\n }\n\n /**\n * @deprecated Use `Sentry.getIsolationScope()` instead.\n */\n public getIsolationScope(): Scope {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n * @deprecated This will be removed in v8.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n * @deprecated This will be removed in v8.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureException()` instead.\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureException(exception, {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureMessage()` instead.\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n ): string {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureMessage(message, level, {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n });\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.captureEvent()` instead.\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().captureEvent(event, { ...hint, event_id: eventId });\n return eventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated This will be removed in v8.\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `Sentry.addBreadcrumb()` instead.\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to\n // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would\n // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope\n // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would\n // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout\n // the event processing pipeline.\n // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope.\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setUser()` instead.\n */\n public setUser(user: User | null): void {\n // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setUser(user);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTags()` instead.\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTags(tags);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtras()` instead.\n */\n public setExtras(extras: Extras): void {\n // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtras(extras);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setTag()` instead.\n */\n public setTag(key: string, value: Primitive): void {\n // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setTag(key, value);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setExtra()` instead.\n */\n public setExtra(key: string, extra: Extra): void {\n // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setExtra(key, extra);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.setContext()` instead.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope.\n // eslint-disable-next-line deprecation/deprecation\n this.getScope().setContext(name, context);\n // eslint-disable-next-line deprecation/deprecation\n this.getIsolationScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use `getScope()` directly.\n */\n public configureScope(callback: (scope: Scope) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line deprecation/deprecation\n public run(callback: (hub: Hub) => void): void {\n // eslint-disable-next-line deprecation/deprecation\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n // eslint-disable-next-line deprecation/deprecation\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead.\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) return null;\n try {\n // eslint-disable-next-line deprecation/deprecation\n return client.getIntegration(integration);\n } catch (_oO) {\n DEBUG_BUILD && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n const result = this._callExtensionMethod<Transaction>('startTransaction', context, customSamplingContext);\n\n if (DEBUG_BUILD && !result) {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n if (!client) {\n logger.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n * @deprecated Use `spanToTraceHeader()` instead.\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n *\n * @deprecated Use top level `captureSession` instead.\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n // eslint-disable-next-line deprecation/deprecation\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `endSession` instead.\n */\n public endSession(): void {\n // eslint-disable-next-line deprecation/deprecation\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n * @deprecated Use top level `startSession` instead.\n */\n public startSession(context?: SessionContext): Session {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n // eslint-disable-next-line deprecation/deprecation\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n *\n * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function\n * only unnecessarily increased API surface but only wrapped accessing the option.\n */\n public shouldSendDefaultPii(): boolean {\n // eslint-disable-next-line deprecation/deprecation\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n // eslint-disable-next-line deprecation/deprecation\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod<T>(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n DEBUG_BUILD && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n *\n * @deprecated Use `setCurrentClient()` instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n *\n * @deprecated Use the respective replacement method directly instead.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context,\n * meaning that it will remain stable for the same Hub.\n */\nexport function getIsolationScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getIsolationScope();\n}\n\n// eslint-disable-next-line deprecation/deprecation\nfunction getGlobalHub(registry: Carrier = getMainCarrier()): Hub {\n // If there's no hub, or its an old API, assign a new one\n\n if (\n !hasHubOnCarrier(registry) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(registry).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function ensureHubOnCarrier(carrier: Carrier, parent: Hub = getGlobalHub()): void {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (\n !hasHubOnCarrier(carrier) ||\n // eslint-disable-next-line deprecation/deprecation\n getHubFromCarrier(carrier).isOlderThan(API_VERSION)\n ) {\n // eslint-disable-next-line deprecation/deprecation\n const client = parent.getClient();\n // eslint-disable-next-line deprecation/deprecation\n const scope = parent.getScope();\n // eslint-disable-next-line deprecation/deprecation\n const isolationScope = parent.getIsolationScope();\n // eslint-disable-next-line deprecation/deprecation\n setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone()));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nexport function runWithAsyncContext<T>(callback: () => T, options: RunWithAsyncContextOptions = {}): T {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n // eslint-disable-next-line deprecation/deprecation\n return getGlobalSingleton<Hub>('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n","import type { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { consoleSandbox, logger } from './logger';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol?: string): protocol is DsnProtocol {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nexport function dsnToString(dsn: DsnComponents, withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nexport function dsnFromString(str: string): DsnComponents | undefined {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n}\n\nfunction dsnFromComponents(components: DsnComponents): DsnComponents {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn: DsnComponents): boolean {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents: ReadonlyArray<keyof DsnComponents> = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nexport function makeDsn(from: DsnLike): DsnComponents | undefined {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n","import type {\n Attachment,\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n DataCategory,\n DsnComponents,\n Envelope,\n EnvelopeItemType,\n Event,\n EventEnvelopeHeaders,\n SdkInfo,\n SdkMetadata,\n TextEncoderInternal,\n} from '@sentry/types';\n\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { dropUndefinedKeys } from './object';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function createEnvelope<E extends Envelope>(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nexport function addItemToEnvelope<E extends Envelope>(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nexport function forEachEnvelopeItem<E extends Envelope>(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input: string, textEncoder?: TextEncoderInternal): Uint8Array {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nexport function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderInternal): string | Uint8Array {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload: string;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers: Uint8Array[]): Uint8Array {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\nexport interface TextDecoderInternal {\n decode(input?: Uint8Array): string;\n}\n\n/**\n * Parses an envelope\n */\nexport function parseEnvelope(\n env: string | Uint8Array,\n textEncoder: TextEncoderInternal,\n textDecoder: TextDecoderInternal,\n): Envelope {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length: number): Uint8Array {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson<T>(): T {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) as T;\n }\n\n const envelopeHeader = readJson<BaseEnvelopeHeaders>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson<BaseEnvelopeItemHeaders>();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(\n attachment: Attachment,\n textEncoder?: TextEncoderInternal,\n): AttachmentItem {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP: Record<EnvelopeItemType, DataCategory> = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n statsd: 'metric_bucket',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n","import type { Event, StackParser } from '@sentry/types';\nimport { GLOBAL_OBJ } from '@sentry/utils';\n\n/** Keys are source filename/url, values are metadata objects. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst filenameMetadataMap = new Map<string, any>();\n/** Set of stack strings that have already been parsed. */\nconst parsedStacks = new Set<string>();\n\nfunction ensureMetadataStacksAreParsed(parser: StackParser): void {\n if (!GLOBAL_OBJ._sentryModuleMetadata) {\n return;\n }\n\n for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) {\n const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack];\n\n if (parsedStacks.has(stack)) {\n continue;\n }\n\n // Ensure this stack doesn't get parsed again\n parsedStacks.add(stack);\n\n const frames = parser(stack);\n\n // Go through the frames starting from the top of the stack and find the first one with a filename\n for (const frame of frames.reverse()) {\n if (frame.filename) {\n // Save the metadata for this filename\n filenameMetadataMap.set(frame.filename, metadata);\n break;\n }\n }\n }\n}\n\n/**\n * Retrieve metadata for a specific JavaScript file URL.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getMetadataForUrl(parser: StackParser, filename: string): any | undefined {\n ensureMetadataStacksAreParsed(parser);\n return filenameMetadataMap.get(filename);\n}\n\n/**\n * Adds metadata to stack frames.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\nexport function addMetadataToStackFrames(parser: StackParser, event: Event): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n if (!exception.stacktrace) {\n return;\n }\n\n for (const frame of exception.stacktrace.frames || []) {\n if (!frame.filename) {\n continue;\n }\n\n const metadata = getMetadataForUrl(parser, frame.filename);\n\n if (metadata) {\n frame.module_metadata = metadata;\n }\n }\n });\n } catch (_) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Strips metadata from stack frames.\n */\nexport function stripMetadataFromStackFrames(event: Event): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n if (!exception.stacktrace) {\n return;\n }\n\n for (const frame of exception.stacktrace.frames || []) {\n delete frame.module_metadata;\n }\n });\n } catch (_) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n","import type { EventItem, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { forEachEnvelopeItem } from '@sentry/utils';\n\nimport { addMetadataToStackFrames, stripMetadataFromStackFrames } from '../metadata';\n\n/**\n * Adds module metadata to stack frames.\n *\n * Metadata can be injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n *\n * When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events\n * under the `module_metadata` property. This can be used to help in tagging or routing of events from different teams\n * our sources\n */\nexport class ModuleMetadata implements Integration {\n /*\n * @inheritDoc\n */\n public static id: string = 'ModuleMetadata';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n public constructor() {\n this.name = ModuleMetadata.id;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (processor: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const client = getCurrentHub().getClient();\n\n if (!client || typeof client.on !== 'function') {\n return;\n }\n\n // We need to strip metadata from stack frames before sending them to Sentry since these are client side only.\n client.on('beforeEnvelope', envelope => {\n forEachEnvelopeItem(envelope, (item, type) => {\n if (type === 'event') {\n const event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n\n if (event) {\n stripMetadataFromStackFrames(event);\n item[1] = event;\n }\n }\n });\n });\n\n const stackParser = client.getOptions().stackParser;\n\n addGlobalEventProcessor(event => {\n addMetadataToStackFrames(stackParser, event);\n return event;\n });\n }\n}\n","export const SDK_VERSION = '7.120.4';\n","import type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n CheckIn,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Scope as ScopeInterface,\n Session,\n SessionContext,\n Severity,\n SeverityLevel,\n Span,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { Hub } from './hub';\nimport { runWithAsyncContext } from './hub';\nimport { getCurrentHub, getIsolationScope } from './hub';\nimport type { Scope } from './scope';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n captureContext?: CaptureContext | Severity | SeverityLevel,\n): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n *\n * @deprecated Use getCurrentScope() directly.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function configureScope(callback: (scope: Scope) => void): ReturnType<Hub['configureScope']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): ReturnType<Hub['addBreadcrumb']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().addBreadcrumb(breadcrumb, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation\nexport function setContext(name: string, context: { [key: string]: any } | null): ReturnType<Hub['setContext']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtras(extras: Extras): ReturnType<Hub['setExtras']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setExtra(key: string, extra: Extra): ReturnType<Hub['setExtra']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTags(tags: { [key: string]: Primitive }): ReturnType<Hub['setTags']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setTag(key: string, value: Primitive): ReturnType<Hub['setTag']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function setUser(user: User | null): ReturnType<Hub['setUser']> {\n // eslint-disable-next-line deprecation/deprecation\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n */\nexport function withScope<T>(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope<T>(scope: ScopeInterface | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope<T>(\n ...rest: [callback: (scope: Scope) => T] | [scope: ScopeInterface | undefined, callback: (scope: Scope) => T]\n): T {\n // eslint-disable-next-line deprecation/deprecation\n const hub = getCurrentHub();\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n if (!scope) {\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(callback);\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(() => {\n // eslint-disable-next-line deprecation/deprecation\n hub.getStackTop().scope = scope as Scope;\n return callback(scope as Scope);\n });\n }\n\n // eslint-disable-next-line deprecation/deprecation\n return hub.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async\n * context strategy, the currently active isolation scope may change within execution of the callback.)\n * @returns The same value that `callback` returns.\n */\nexport function withIsolationScope<T>(callback: (isolationScope: Scope) => T): T {\n return runWithAsyncContext(() => {\n return callback(getIsolationScope());\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback.\n *\n * @param span Spans started in the context of the provided callback will be children of this span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan<T>(span: Span, callback: (scope: Scope) => T): T {\n return withScope(scope => {\n // eslint-disable-next-line deprecation/deprecation\n scope.setSpan(span);\n return callback(scope);\n });\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n *\n * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead.\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n // eslint-disable-next-line deprecation/deprecation\n): ReturnType<Hub['startTransaction']> {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor<T>(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise<boolean> {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise<boolean> {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient<C extends Client>(): C | undefined {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getClient<C>();\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n // eslint-disable-next-line deprecation/deprecation\n return getCurrentHub().getScope();\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n","import type { Options } from '@sentry/types';\n\nimport { getCurrentHub } from '../hub';\n\n// Treeshakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean | undefined;\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n maybeOptions?: Pick<Options, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'> | undefined,\n): boolean {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getCurrentHub().getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n","import { DEBUG_BUILD } from './debug-build';\nimport { logger } from './logger';\nimport { getGlobalObject } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject<Window>();\n\ndeclare const EdgeRuntime: string | undefined;\n\nexport { supportsHistory } from './vendor/supportsHistory';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n","// Based on https://github.com/angular/angular.js/pull/13945/files\n// The MIT License\n\n// Copyright (c) 2010-2016 Google, Inc. http://angularjs.org\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport { getGlobalObject } from '../worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject<Window>();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chromeVar = (WINDOW as any).chrome;\n const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n","/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type {\n HandlerDataFetch,\n HandlerDataXhr,\n SentryWrappedXMLHttpRequest,\n SentryXhrData,\n WrappedFunction,\n} from '@sentry/types';\n\nimport { isString } from './is';\nimport type { ConsoleLevel } from './logger';\nimport { CONSOLE_LEVELS, logger, originalConsoleMethods } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\nimport { getGlobalObject, GLOBAL_OBJ } from './worldwide';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject<Window>();\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v2__';\n\nexport type InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n __DEBUG_BUILD__ && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(callback);\n instrument(type);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp<T extends string>(obj: unknown, prop: T): obj is Record<string, string> {\n return !!obj && typeof obj === 'object' && !!(obj as Record<string, string>)[prop];\n}\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\n/** JSDoc */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const url = args[1];\n const xhrInfo: SentryXhrData = (this[SENTRY_XHR_DATA_KEY] = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n request_headers: {},\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args: args as [string, string],\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr: this,\n } as HandlerDataXhr);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs as [string, string];\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n if (sentryXhrData && args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler: (typeof WINDOW)['onerror'] | null = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg: unknown, url: unknown, line: unknown, column: unknown, error: unknown): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n WINDOW.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nlet _oldOnUnhandledRejectionHandler: (typeof WINDOW)['onunhandledrejection'] | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n WINDOW.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","import type { Transaction } from '@sentry/types';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * TODO(v7): Reorganize these exports\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n */\nexport { TRACEPARENT_REGEXP, extractTraceparentData } from '@sentry/utils';\n\n/** Grabs active transaction off scope, if any */\nexport function getActiveTransaction<T extends Transaction>(maybeHub?: Hub): T | undefined {\n const hub = maybeHub || getCurrentHub();\n const scope = hub.getScope();\n return scope.getTransaction() as T | undefined;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n","import { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport type { SpanStatusType } from './span';\nimport { getActiveTransaction } from './utils';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addInstrumentationHandler('error', errorCallback);\n addInstrumentationHandler('unhandledrejection', errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status: SpanStatusType = 'internal_error';\n __DEBUG_BUILD__ && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n","import type { DynamicSamplingContext } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { isString } from './is';\nimport { logger } from './logger';\n\nexport const BAGGAGE_HEADER_NAME = 'baggage';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nexport const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nexport const MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nexport function baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader: string | string[] | number | null | undefined | boolean,\n): Partial<DynamicSamplingContext> | undefined {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject: Readonly<Record<string, string>> = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce<Record<string, string>>((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n for (const key of Object.keys(currBaggageObject)) {\n acc[key] = currBaggageObject[key];\n }\n return acc;\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce<Record<string, string>>((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext as Partial<DynamicSamplingContext>;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nexport function dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext?: Partial<DynamicSamplingContext>,\n): string | undefined {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce<Record<string, string>>(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader: string): Record<string, string> {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce<Record<string, string>>((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object: Record<string, string>): string | undefined {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n","import type { PropagationContext, TraceparentData } from '@sentry/types';\n\nimport { baggageHeaderToDynamicSamplingContext } from './baggage';\nimport { uuid4 } from './misc';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent?: string): TraceparentData | undefined {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create tracing context from incoming headers.\n *\n * @deprecated Use `propagationContextFromHeaders` instead.\n */\n// TODO(v8): Remove this function\nexport function tracingContextFromHeaders(\n sentryTrace: Parameters<typeof extractTraceparentData>[0],\n baggage: Parameters<typeof baggageHeaderToDynamicSamplingContext>[0],\n): {\n traceparentData: ReturnType<typeof extractTraceparentData>;\n dynamicSamplingContext: ReturnType<typeof baggageHeaderToDynamicSamplingContext>;\n propagationContext: PropagationContext;\n} {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceparentData,\n dynamicSamplingContext: undefined,\n propagationContext: {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n },\n };\n } else {\n return {\n traceparentData,\n dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n propagationContext: {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n },\n };\n }\n}\n\n/**\n * Create a propagation context from incoming headers.\n */\nexport function propagationContextFromHeaders(\n sentryTrace: string | undefined,\n baggage: string | number | boolean | string[] | null | undefined,\n): PropagationContext {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n if (!traceparentData) {\n return {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n };\n } else {\n return {\n traceId: traceId || uuid4(),\n parentSpanId: parentSpanId || uuid4().substring(16),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n };\n }\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nexport function generateSentryTraceHeader(\n traceId: string = uuid4(),\n spanId: string = uuid4().substring(16),\n sampled?: boolean,\n): string {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n","/* eslint-disable max-lines */\nimport type {\n Instrumenter,\n Primitive,\n Span as SpanInterface,\n SpanContext,\n SpanOrigin,\n TraceContext,\n Transaction,\n} from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n this.spans = [];\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * @inheritDoc\n */\n public traceId: string;\n\n /**\n * @inheritDoc\n */\n public spanId: string;\n\n /**\n * @inheritDoc\n */\n public parentSpanId?: string;\n\n /**\n * Internal keeper of the status\n */\n public status?: SpanStatusType | string;\n\n /**\n * @inheritDoc\n */\n public sampled?: boolean;\n\n /**\n * Timestamp in seconds when the span was created.\n */\n public startTimestamp: number;\n\n /**\n * Timestamp in seconds when the span ended.\n */\n public endTimestamp?: number;\n\n /**\n * @inheritDoc\n */\n public op?: string;\n\n /**\n * @inheritDoc\n */\n public description?: string;\n\n /**\n * @inheritDoc\n */\n public tags: { [key: string]: Primitive };\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any };\n\n /**\n * List of spans that were finalized\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n */\n public transaction?: Transaction;\n\n /**\n * The instrumenter that created this span.\n */\n public instrumenter: Instrumenter;\n\n /**\n * The origin of the span, giving context about what created the span.\n */\n public origin?: SpanOrigin;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext: SpanContext = {}) {\n this.traceId = spanContext.traceId || uuid4();\n this.spanId = spanContext.spanId || uuid4().substring(16);\n this.startTimestamp = spanContext.startTimestamp || timestampInSeconds();\n this.tags = spanContext.tags || {};\n this.data = spanContext.data || {};\n this.instrumenter = spanContext.instrumenter || 'sentry';\n this.origin = spanContext.origin || 'manual';\n\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.name) {\n this.description = spanContext.name;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n }\n\n /** An alias for `description` of the Span. */\n public get name(): string {\n return this.description || '';\n }\n /** Update the name of the span. */\n public set name(name: string) {\n this.setName(name);\n }\n\n /**\n * @inheritDoc\n */\n public startChild(\n spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'sampled' | 'traceId' | 'parentSpanId'>>,\n ): Span {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n if (__DEBUG_BUILD__ && childSpan.transaction) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = childSpan.transaction.name || '< unknown name >';\n const idStr = childSpan.transaction.spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };\n logger.log(logMessage);\n }\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public setData(key: string, value: any): this {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatusType): this {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setHttpStatus(httpStatus: number): this {\n this.setTag('http.status_code', String(httpStatus));\n this.setData('http.response.status_code', httpStatus);\n const spanStatus = spanStatusfromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setName(name: string): void {\n this.description = name;\n }\n\n /**\n * @inheritDoc\n */\n public isSuccess(): boolean {\n return this.status === 'ok';\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): void {\n if (\n __DEBUG_BUILD__ &&\n // Don't call this for transactions\n this.transaction &&\n this.transaction.spanId !== this.spanId\n ) {\n const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];\n if (logMessage) {\n logger.log((logMessage as string).replace('Starting', 'Finishing'));\n }\n }\n\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n }\n\n /**\n * @inheritDoc\n */\n public toTraceparent(): string {\n return generateSentryTraceHeader(this.traceId, this.spanId, this.sampled);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(spanContext: SpanContext): this {\n this.data = spanContext.data || {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId || this.spanId;\n this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags || {};\n this.traceId = spanContext.traceId || this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getTraceContext(): TraceContext {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public toJSON(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n start_timestamp: number;\n status?: string;\n tags?: { [key: string]: Primitive };\n timestamp?: number;\n trace_id: string;\n origin?: SpanOrigin;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n origin: this.origin,\n });\n }\n}\n\nexport type SpanStatusType =\n /** The operation completed successfully. */\n | 'ok'\n /** Deadline expired before operation could complete. */\n | 'deadline_exceeded'\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n | 'unauthenticated'\n /** 403 Forbidden */\n | 'permission_denied'\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n | 'not_found'\n /** 429 Too Many Requests */\n | 'resource_exhausted'\n /** Client specified an invalid argument. 4xx. */\n | 'invalid_argument'\n /** 501 Not Implemented */\n | 'unimplemented'\n /** 503 Service Unavailable */\n | 'unavailable'\n /** Other/generic 5xx. */\n | 'internal_error'\n /** Unknown. Any non-standard HTTP status code. */\n | 'unknown_error'\n /** The operation was cancelled (typically by the user). */\n | 'cancelled'\n /** Already exists (409) */\n | 'already_exists'\n /** Operation was rejected because the system is not in a state required for the operation's */\n | 'failed_precondition'\n /** The operation was aborted, typically due to a concurrency issue. */\n | 'aborted'\n /** Operation was attempted past the valid range. */\n | 'out_of_range'\n /** Unrecoverable data loss or corruption */\n | 'data_loss';\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nexport function spanStatusfromHttpCode(httpStatus: number): SpanStatusType {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n","import type { Client, DynamicSamplingContext, Scope, Span, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getClient, getCurrentScope } from '../exports';\nimport { getRootSpan } from '../utils/getRootSpan';\nimport { spanIsSampled, spanToJSON } from '../utils/spanUtils';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nexport function getDynamicSamplingContextFromClient(\n trace_id: string,\n client: Client,\n scope?: Scope,\n): DynamicSamplingContext {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n // TODO(v8): Remove segment from User\n // eslint-disable-next-line deprecation/deprecation\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) as DynamicSamplingContext;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * A Span with a frozen dynamic sampling context.\n */\ntype TransactionWithV7FrozenDsc = Transaction & { _frozenDynamicSamplingContext?: DynamicSamplingContext };\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nexport function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<DynamicSamplingContext>> {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n // passing emit=false here to only emit later once the DSC is actually populated\n const dsc = getDynamicSamplingContextFromClient(spanToJSON(span).trace_id || '', client, getCurrentScope());\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n const txn = getRootSpan(span) as TransactionWithV7FrozenDsc | undefined;\n if (!txn) {\n return dsc;\n }\n\n // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext\n // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set.\n // @see Transaction class constructor\n const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext;\n if (v7FrozenDsc) {\n return v7FrozenDsc;\n }\n\n // TODO (v8): Replace txn.metadata with txn.attributes[]\n // We can't do this yet because attributes aren't always set yet.\n // eslint-disable-next-line deprecation/deprecation\n const { sampleRate: maybeSampleRate, source } = txn.metadata;\n if (maybeSampleRate != null) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const jsonSpan = spanToJSON(txn);\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n if (source && source !== 'url') {\n dsc.transaction = jsonSpan.description;\n }\n\n dsc.sampled = String(spanIsSampled(txn));\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n","import type {\n Context,\n Contexts,\n DynamicSamplingContext,\n Event,\n Measurements,\n MeasurementUnit,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getCurrentHub } from '../hub';\nimport { getDynamicSamplingContextFromClient } from './dynamicSamplingContext';\nimport { Span as SpanClass, SpanRecorder } from './span';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n public metadata: TransactionMetadata;\n\n /**\n * The reference to the current hub.\n */\n public _hub: Hub;\n\n private _name: string;\n\n private _measurements: Measurements;\n\n private _contexts: Contexts;\n\n private _trimEnd?: boolean;\n\n private _frozenDynamicSamplingContext: Readonly<Partial<DynamicSamplingContext>> | undefined;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n // We need to delete description since it's set by the Span class constructor\n // but not needed for transactions.\n delete this.description;\n\n this._measurements = {};\n this._contexts = {};\n\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this.metadata = {\n source: 'custom',\n ...transactionContext.metadata,\n spanMetadata: {},\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n /** Getter for `name` property */\n public get name(): string {\n return this._name;\n }\n\n /** Setter for `name` property, which also sets `source` as custom */\n public set name(newName: string) {\n this.setName(newName);\n }\n\n /**\n * JSDoc\n */\n public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {\n this._name = name;\n this.metadata.source = source;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): void {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * @inheritDoc\n */\n public setMetadata(newMetadata: Partial<TransactionMetadata>): void {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): string | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n __DEBUG_BUILD__ && logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.');\n this.name = '<unlabeled transaction>';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n __DEBUG_BUILD__ && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const metadata = this.metadata;\n\n const transaction: Event = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n dynamicSamplingContext: this.getDynamicSamplingContext(),\n },\n ...(metadata.source && {\n transaction_info: {\n source: metadata.source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n __DEBUG_BUILD__ &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name || '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n */\n public getDynamicSamplingContext(): Readonly<Partial<DynamicSamplingContext>> {\n if (this._frozenDynamicSamplingContext) {\n return this._frozenDynamicSamplingContext;\n }\n\n const hub = this._hub || getCurrentHub();\n const client = hub.getClient();\n\n if (!client) return {};\n\n const scope = hub.getScope();\n const dsc = getDynamicSamplingContextFromClient(this.traceId, client, scope);\n\n const maybeSampleRate = this.metadata.sampleRate;\n if (maybeSampleRate !== undefined) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const source = this.metadata.source;\n if (source && source !== 'url') {\n dsc.transaction = this.name;\n }\n\n if (this.sampled !== undefined) {\n dsc.sampled = String(this.sampled);\n }\n\n // Uncomment if we want to make DSC immutable\n // this._frozenDynamicSamplingContext = dsc;\n\n return dsc;\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n public setHub(hub: Hub): void {\n this._hub = hub;\n }\n}\n","/* eslint-disable max-lines */\nimport type { TransactionContext } from '@sentry/types';\nimport { logger, timestampInSeconds } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport type { Span } from './span';\nimport { SpanRecorder } from './span';\nimport { Transaction } from './transaction';\n\nexport const TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string,\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp?: number) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record<string, boolean>;\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean;\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n private _idleTimeoutCanceledPermanently: boolean;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[];\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n private _idleTimeoutID: ReturnType<typeof setTimeout> | undefined;\n\n private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number];\n\n public constructor(\n transactionContext: TransactionContext,\n private readonly _idleHub: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n private readonly _idleTimeout: number = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n private readonly _finalTimeout: number = TRACING_DEFAULTS.finalTimeout,\n private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n private readonly _onScope: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n this.activities = {};\n this._heartbeatCounter = 0;\n this._finished = false;\n this._idleTimeoutCanceledPermanently = false;\n this._beforeFinishCallbacks = [];\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n __DEBUG_BUILD__ && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._restartIdleTimeout();\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.finish();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n public finish(endTimestamp: number = timestampInSeconds()): string | undefined {\n this._finished = true;\n this.activities = {};\n\n if (this.op === 'ui.action.click') {\n this.setTag(FINISH_REASON_TAG, this._finishReason);\n }\n\n if (this.spanRecorder) {\n __DEBUG_BUILD__ &&\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus('cancelled');\n __DEBUG_BUILD__ &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const spanStartedBeforeTransactionFinish = span.startTimestamp < endTimestamp;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = span.endTimestamp - this.startTimestamp < timeoutWithMarginOfError;\n\n if (__DEBUG_BUILD__) {\n const stringifiedSpan = JSON.stringify(span, undefined, 2);\n if (!spanStartedBeforeTransactionFinish) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);\n }\n }\n\n return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;\n });\n\n __DEBUG_BUILD__ && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n __DEBUG_BUILD__ && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n const scope = this._idleHub.getScope();\n if (scope.getTransaction() === this) {\n scope.setSpan(undefined);\n }\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n __DEBUG_BUILD__ && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n public cancelIdleTimeout(\n endTimestamp?: Parameters<IdleTransaction['finish']>[0],\n {\n restartOnChildSpanChange,\n }: {\n restartOnChildSpanChange?: boolean;\n } = {\n restartOnChildSpanChange: true,\n },\n ): void {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n public setFinishReason(reason: string): void {\n this._finishReason = reason;\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n private _restartIdleTimeout(endTimestamp?: Parameters<IdleTransaction['finish']>[0]): void {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.finish(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n __DEBUG_BUILD__ && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n __DEBUG_BUILD__ && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n __DEBUG_BUILD__ && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n __DEBUG_BUILD__ && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n __DEBUG_BUILD__ && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n __DEBUG_BUILD__ && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n","import type { ClientOptions, CustomSamplingContext, Options, SamplingContext, TransactionContext } from '@sentry/types';\nimport { isNaN, logger } from '@sentry/utils';\n\nimport type { Hub } from '../hub';\nimport { getMainCarrier } from '../hub';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { Transaction } from './transaction';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n const scope = this.getScope();\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': span.toTraceparent(),\n }\n : {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param transaction: The transaction needing a sampling decision\n * @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler`\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample<T extends Transaction>(\n transaction: T,\n options: Pick<Options, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'>,\n samplingContext: SamplingContext,\n): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n sampleRate: Number(transaction.sampled),\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setMetadata({\n sampleRate,\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n __DEBUG_BUILD__ && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n const client = this.getClient();\n const options: Partial<ClientOptions> = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n __DEBUG_BUILD__ &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n transactionContext.sampled = false;\n }\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout: number,\n finalTimeout: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n heartbeatInterval?: number,\n): IdleTransaction {\n const client = hub.getClient();\n const options: Partial<ClientOptions> = (client && client.getOptions()) || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nexport function addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n","import type { ConsoleLevel } from './logger';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public logLevel: ConsoleLevel;\n\n public constructor(public message: string, logLevel: ConsoleLevel = 'warn') {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n","import { SentryError } from './error';\nimport { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';\n\nexport interface PromiseBuffer<T> {\n // exposes the internal array so tests can assert on the state of it.\n // XXX: this really should not be public api.\n $: Array<PromiseLike<T>>;\n add(taskProducer: () => PromiseLike<T>): PromiseLike<T>;\n drain(timeout?: number): PromiseLike<boolean>;\n}\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nexport function makePromiseBuffer<T>(limit?: number): PromiseBuffer<T> {\n const buffer: Array<PromiseLike<T>> = [];\n\n function isReady(): boolean {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike<T>\n * @returns Removed promise.\n */\n function remove(task: PromiseLike<T>): PromiseLike<T> {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task:\n * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer: () => PromiseLike<T>): PromiseLike<T> {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise<boolean>((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n","import type { TransportMakeRequestResponse } from '@sentry/types';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\nexport type RateLimits = Record<string, number>;\n\nexport const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nexport function parseRetryAfterHeader(header: string, now: number = Date.now()): number {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nexport function disabledUntil(limits: RateLimits, category: string): number {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nexport function isRateLimited(limits: RateLimits, category: string, now: number = Date.now()): boolean {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nexport function updateRateLimits(\n limits: RateLimits,\n { statusCode, headers }: TransportMakeRequestResponse,\n now: number = Date.now(),\n): RateLimits {\n const updatedRateLimits: RateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n * <header>,<header>,..\n * where each <header> is of the form\n * <retry_after>: <categories>: <scope>: <reason_code>\n * where\n * <retry_after> is a delay in seconds\n * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * <category>;<category>;...\n * <scope> is what's being limited (org, project, or key) - ignored by SDK\n * <reason_code> is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n","import type {\n Envelope,\n EnvelopeItem,\n EnvelopeItemType,\n Event,\n EventDropReason,\n EventItem,\n InternalBaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport type { PromiseBuffer, RateLimits } from '@sentry/utils';\nimport {\n createEnvelope,\n envelopeItemTypeToDataCategory,\n forEachEnvelopeItem,\n isRateLimited,\n logger,\n makePromiseBuffer,\n resolvedSyncPromise,\n SentryError,\n serializeEnvelope,\n updateRateLimits,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nexport function createTransport(\n options: InternalBaseTransportOptions,\n makeRequest: TransportRequestExecutor,\n buffer: PromiseBuffer<void | TransportMakeRequestResponse> = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n): Transport {\n let rateLimits: RateLimits = {};\n const flush = (timeout?: number): PromiseLike<boolean> => buffer.drain(timeout);\n\n function send(envelope: Envelope): PromiseLike<void | TransportMakeRequestResponse> {\n const filteredEnvelopeItems: EnvelopeItem[] = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope: Envelope = createEnvelope(envelope[0], filteredEnvelopeItems as any);\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason: EventDropReason): void => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event: Event | undefined = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = (): PromiseLike<void | TransportMakeRequestResponse> =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n __DEBUG_BUILD__ && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n __DEBUG_BUILD__ && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item: Envelope[1][number], type: EnvelopeItemType): Event | undefined {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item as EventItem)[1] : undefined;\n}\n","import type { ClientOptions, DsnComponents, DsnLike, SdkInfo } from '@sentry/types';\nimport { dsnToString, makeDsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn: DsnComponents): string {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn: DsnComponents): string {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn: DsnComponents, sdkInfo: SdkInfo | undefined): string {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nexport function getEnvelopeEndpointWithUrlEncodedAuth(\n dsn: DsnComponents,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions: string | ClientOptions = {} as ClientOptions,\n): string {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nexport function getReportDialogEndpoint(\n dsnLike: DsnLike,\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n },\n): string {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n","import type {\n BaseTransportOptions,\n Envelope,\n EnvelopeItemType,\n Event,\n EventItem,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport { dsnFromString, forEachEnvelopeItem } from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from '../api';\n\ninterface MatchParam {\n /** The envelope to be sent */\n envelope: Envelope;\n /**\n * A function that returns an event from the envelope if one exists. You can optionally pass an array of envelope item\n * types to filter by - only envelopes matching the given types will be multiplexed.\n * Allowed values are: 'event', 'transaction', 'profile', 'replay_event'\n *\n * @param types Defaults to ['event']\n */\n getEvent(types?: EnvelopeItemType[]): Event | undefined;\n}\n\ntype RouteTo = { dsn: string; release: string };\ntype Matcher = (param: MatchParam) => (string | RouteTo)[];\n\n/**\n * Gets an event from an envelope.\n *\n * This is only exported for use in the tests\n */\nexport function eventFromEnvelope(env: Envelope, types: EnvelopeItemType[]): Event | undefined {\n let event: Event | undefined;\n\n forEachEnvelopeItem(env, (item, type) => {\n if (types.includes(type)) {\n event = Array.isArray(item) ? (item as EventItem)[1] : undefined;\n }\n // bail out if we found an event\n return !!event;\n });\n\n return event;\n}\n\n/**\n * Creates a transport that overrides the release on all events.\n */\nfunction makeOverrideReleaseTransport<TO extends BaseTransportOptions>(\n createTransport: (options: TO) => Transport,\n release: string,\n): (options: TO) => Transport {\n return options => {\n const transport = createTransport(options);\n\n return {\n send: async (envelope: Envelope): Promise<void | TransportMakeRequestResponse> => {\n const event = eventFromEnvelope(envelope, ['event', 'transaction', 'profile', 'replay_event']);\n\n if (event) {\n event.release = release;\n }\n return transport.send(envelope);\n },\n flush: timeout => transport.flush(timeout),\n };\n };\n}\n\n/**\n * Creates a transport that can send events to different DSNs depending on the envelope contents.\n */\nexport function makeMultiplexedTransport<TO extends BaseTransportOptions>(\n createTransport: (options: TO) => Transport,\n matcher: Matcher,\n): (options: TO) => Transport {\n return options => {\n const fallbackTransport = createTransport(options);\n const otherTransports: Record<string, Transport> = {};\n\n function getTransport(dsn: string, release: string | undefined): Transport | undefined {\n // We create a transport for every unique dsn/release combination as there may be code from multiple releases in\n // use at the same time\n const key = release ? `${dsn}:${release}` : dsn;\n\n if (!otherTransports[key]) {\n const validatedDsn = dsnFromString(dsn);\n if (!validatedDsn) {\n return undefined;\n }\n const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn);\n\n otherTransports[key] = release\n ? makeOverrideReleaseTransport(createTransport, release)({ ...options, url })\n : createTransport({ ...options, url });\n }\n\n return otherTransports[key];\n }\n\n async function send(envelope: Envelope): Promise<void | TransportMakeRequestResponse> {\n function getEvent(types?: EnvelopeItemType[]): Event | undefined {\n const eventTypes: EnvelopeItemType[] = types && types.length ? types : ['event'];\n return eventFromEnvelope(envelope, eventTypes);\n }\n\n const transports = matcher({ envelope, getEvent })\n .map(result => {\n if (typeof result === 'string') {\n return getTransport(result, undefined);\n } else {\n return getTransport(result.dsn, result.release);\n }\n })\n .filter((t): t is Transport => !!t);\n\n // If we have no transports to send to, use the fallback transport\n if (transports.length === 0) {\n transports.push(fallbackTransport);\n }\n\n const results = await Promise.all(transports.map(transport => transport.send(envelope)));\n\n return results[0];\n }\n\n async function flush(timeout: number | undefined): Promise<boolean> {\n const allTransports = [...Object.keys(otherTransports).map(dsn => otherTransports[dsn]), fallbackTransport];\n const results = await Promise.all(allTransports.map(transport => transport.flush(timeout)));\n return results.every(r => r);\n }\n\n return {\n send,\n flush,\n };\n };\n}\n","import type { MeasurementUnit } from '@sentry/types';\n\nimport { getActiveTransaction } from './utils';\n\n/**\n * Adds a measurement to the current active transaction.\n */\nexport function setMeasurement(name: string, value: number, unit: MeasurementUnit): void {\n const transaction = getActiveTransaction();\n if (transaction) {\n transaction.setMeasurement(name, value, unit);\n }\n}\n","import type { TransactionContext } from '@sentry/types';\nimport { isThenable } from '@sentry/utils';\n\nimport { getCurrentHub } from '../hub';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled';\nimport type { Span } from './span';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n *\n * This function is meant to be used internally and may break at any time. Use at your own risk.\n *\n * @internal\n * @private\n */\nexport function trace<T>(\n context: TransactionContext,\n callback: (span?: Span) => T,\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n onError: (error: unknown) => void = () => {},\n): T {\n const ctx = { ...context };\n // If a name is set and a description is not, set the description to the name.\n if (ctx.name !== undefined && ctx.description === undefined) {\n ctx.description = ctx.name;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n\n const parentSpan = scope.getSpan();\n\n function startActiveSpan(): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n return parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);\n }\n\n const activeSpan = startActiveSpan();\n scope.setSpan(activeSpan);\n\n function finishAndSetSpan(): void {\n activeSpan && activeSpan.finish();\n hub.getScope().setSpan(parentSpan);\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(activeSpan);\n } catch (e) {\n activeSpan && activeSpan.setStatus('internal_error');\n onError(e);\n finishAndSetSpan();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishAndSetSpan();\n },\n e => {\n activeSpan && activeSpan.setStatus('internal_error');\n onError(e);\n finishAndSetSpan();\n },\n );\n } else {\n finishAndSetSpan();\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startActiveSpan<T>(context: TransactionContext, callback: (span: Span | undefined) => T): T {\n const ctx = { ...context };\n // If a name is set and a description is not, set the description to the name.\n if (ctx.name !== undefined && ctx.description === undefined) {\n ctx.description = ctx.name;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n\n const parentSpan = scope.getSpan();\n\n function startActiveSpan(): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n return parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);\n }\n\n const activeSpan = startActiveSpan();\n scope.setSpan(activeSpan);\n\n function finishAndSetSpan(): void {\n activeSpan && activeSpan.finish();\n hub.getScope().setSpan(parentSpan);\n }\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(activeSpan);\n } catch (e) {\n activeSpan && activeSpan.setStatus('internal_error');\n finishAndSetSpan();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishAndSetSpan();\n },\n () => {\n activeSpan && activeSpan.setStatus('internal_error');\n finishAndSetSpan();\n },\n );\n } else {\n finishAndSetSpan();\n }\n\n return maybePromiseResult;\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startActiveSpan}.\n *\n * Note that if you have not enabled tracing extensions via `addTracingExtensions`\n * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans\n * and the `span` returned from the callback will be undefined.\n */\nexport function startSpan(context: TransactionContext): Span | undefined {\n if (!hasTracingEnabled()) {\n return undefined;\n }\n\n const ctx = { ...context };\n // If a name is set and a description is not, set the description to the name.\n if (ctx.name !== undefined && ctx.description === undefined) {\n ctx.description = ctx.name;\n }\n\n const hub = getCurrentHub();\n const parentSpan = getActiveSpan();\n return parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);\n}\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n return getCurrentHub().getScope().getSpan();\n}\n","import { captureException, withScope } from '@sentry/core';\nimport type { DsnLike, Event as SentryEvent, Mechanism, Scope, WrappedFunction } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n} from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap(\n fn: WrappedFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n before?: WrappedFunction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped: WrappedFunction = function (this: unknown): void {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg: any) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope: Scope) => {\n scope.addEventProcessor((event: SentryEvent) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') as PropertyDescriptor;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\nexport interface ReportDialogOptions {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n eventId?: string;\n dsn?: DsnLike;\n user?: {\n email?: string;\n name?: string;\n };\n lang?: string;\n title?: string;\n subtitle?: string;\n subtitle2?: string;\n labelName?: string;\n labelEmail?: string;\n labelComments?: string;\n labelClose?: string;\n labelSubmit?: string;\n errorGeneric?: string;\n errorFormEntry?: string;\n successMessage?: string;\n /** Callback after reportDialog showed up */\n onLoad?(this: void): void;\n}\n","import type { Integration, Options } from '@sentry/types';\nimport { arrayify, logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\nimport { addGlobalEventProcessor } from './scope';\n\ndeclare module '@sentry/types' {\n interface Integration {\n isDefaultInstance?: boolean;\n }\n}\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n};\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n const integrationsByName: { [key: string]: Integration } = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations: Integration[];\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations(integrations: Integration[]): IntegrationIndex {\n const integrationIndex: IntegrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nexport function setupIntegration(integration: Integration, integrationIndex: IntegrationIndex): void {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n __DEBUG_BUILD__ && logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex<T>(arr: T[], callback: (item: T) => boolean): number {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n","import type {\n CaptureContext,\n Client,\n ClientOptions,\n Event,\n EventHint,\n Scope as ScopeInterface,\n ScopeContext,\n StackFrame,\n StackParser,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, addExceptionMechanism, dateTimestampInSeconds, normalize, truncate, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from '../constants';\nimport { getGlobalEventProcessors, notifyEventProcessors } from '../eventProcessors';\nimport { Scope, getGlobalScope } from '../scope';\nimport { applyScopeDataToEvent, mergeScopeData } from './applyScopeDataToEvent';\nimport { spanToJSON } from './spanUtils';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\nexport type ExclusiveEventHintOrCaptureContext =\n | (CaptureContext & Partial<{ [key in keyof EventHint]: never }>)\n | (EventHint & Partial<{ [key in keyof ScopeContext]: never }>);\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nexport function prepareEvent(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n scope?: Scope,\n client?: Client,\n isolationScope?: Scope,\n): PromiseLike<Event | null> {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1_000 } = options;\n const prepared: Event = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n const eventProcessors = [\n ...clientEventProcessors,\n // eslint-disable-next-line deprecation/deprecation\n ...getGlobalEventProcessors(),\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event: Event, options: ClientOptions): void {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap<StackParser, Map<string, StackFrame[]>>();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nexport function applyDebugIds(event: Event, stackParser: StackParser): void {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache: Map<string, StackFrame[]>;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map<string, StackFrame[]>();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce<Record<string, string>>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event!.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nexport function applyDebugMeta(event: Event): void {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap: Record<string, string> = {};\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception!.values!.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace!.frames!.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event: Event, integrationNames: string[]): void {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event: Event | null, depth: number, maxBreadth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized: Event = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n const data = spanToJSON(span).data;\n\n if (data) {\n // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so\n // eslint-disable-next-line deprecation/deprecation\n span.data = normalize(data, depth, maxBreadth);\n }\n\n return span;\n });\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope: Scope | undefined, captureContext: CaptureContext | undefined): Scope | undefined {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nexport function parseEventHintOrCaptureContext(\n hint: ExclusiveEventHintOrCaptureContext | undefined,\n): EventHint | undefined {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(\n hint: CaptureContext | EventHint,\n): hint is ScopeInterface | ((scope: ScopeInterface) => ScopeInterface) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\ntype ScopeContextProperty = keyof ScopeContext;\nconst captureContextKeys: readonly ScopeContextProperty[] = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'requestSession',\n 'propagationContext',\n] as const;\n\nfunction hintIsScopeContext(hint: Partial<ScopeContext> | EventHint): hint is Partial<ScopeContext> {\n return Object.keys(hint).some(key => captureContextKeys.includes(key as ScopeContextProperty));\n}\n","/* eslint-disable max-lines */\nimport type {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n ClientOptions,\n DataCategory,\n DsnComponents,\n DynamicSamplingContext,\n Envelope,\n ErrorEvent,\n Event,\n EventDropReason,\n EventHint,\n Integration,\n IntegrationClass,\n Outcome,\n PropagationContext,\n SdkMetadata,\n Session,\n SessionAggregates,\n Severity,\n SeverityLevel,\n Transaction,\n TransactionEvent,\n Transport,\n TransportMakeRequestResponse,\n} from '@sentry/types';\nimport {\n addItemToEnvelope,\n checkOrSetAlreadyCaught,\n createAttachmentEnvelopeItem,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n makeDsn,\n rejectedSyncPromise,\n resolvedSyncPromise,\n SentryError,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope';\nimport type { IntegrationIndex } from './integration';\nimport { setupIntegration, setupIntegrations } from './integration';\nimport type { Scope } from './scope';\nimport { updateSession } from './session';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext';\nimport { prepareEvent } from './utils/prepareEvent';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient<NodeOptions> {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient<O extends ClientOptions> implements Client<O> {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: DsnComponents;\n\n protected readonly _transport?: Transport;\n\n /** Array of set up integrations. */\n protected _integrations: IntegrationIndex;\n\n /** Indicates whether this client's integrations have been set up. */\n protected _integrationsInitialized: boolean;\n\n /** Number of calls being processed */\n protected _numProcessing: number;\n\n /** Holds flushable */\n private _outcomes: { [key: string]: number };\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _hooks: Record<string, Function[]>;\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n protected constructor(options: O) {\n this._options = options;\n this._integrations = {};\n this._integrationsInitialized = false;\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n __DEBUG_BUILD__ && logger.warn('No DSN provided, client will not do anything.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level?: Severity | SeverityLevel,\n hint?: EventHint,\n scope?: Scope,\n ): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n __DEBUG_BUILD__ && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n __DEBUG_BUILD__ && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): DsnComponents | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n public getSdkMetadata(): SdkMetadata | undefined {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike<boolean> {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n public getIntegrationById(integrationId: string): Integration | undefined {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n __DEBUG_BUILD__ && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public addIntegration(integration: Integration): void {\n setupIntegration(integration, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event, hint: EventHint = {}): void {\n this.emit('beforeSendEvent', event, hint);\n\n if (this._dsn) {\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): void {\n if (this._dsn) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n void this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n public recordDroppedEvent(reason: EventDropReason, category: DataCategory, _event?: Event): void {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n __DEBUG_BUILD__ && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n\n /** @inheritdoc */\n public on(hook: 'startTransaction' | 'finishTransaction', callback: (transaction: Transaction) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void): void;\n\n /** @inheritdoc */\n public on(\n hook: 'afterSendEvent',\n callback: (event: Event, sendResponse: TransportMakeRequestResponse | void) => void,\n ): void;\n\n /** @inheritdoc */\n public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;\n\n /** @inheritdoc */\n public on(hook: 'otelSpanEnd', callback: (otelSpan: unknown, mutableOptions: { drop: boolean }) => void): void;\n\n /** @inheritdoc */\n public on(hook: string, callback: unknown): void {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-ignore We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n public emit(hook: 'startTransaction' | 'finishTransaction', transaction: Transaction): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeEnvelope', envelope: Envelope): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeSendEvent', event: Event, hint?: EventHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;\n\n /** @inheritdoc */\n public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;\n\n /** @inheritdoc */\n public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;\n\n /** @inheritdoc */\n public emit(hook: 'otelSpanEnd', otelSpan: unknown, mutableOptions: { drop: boolean }): void;\n\n /** @inheritdoc */\n public emit(hook: string, ...rest: unknown[]): void {\n if (this._hooks[hook]) {\n // @ts-ignore we cannot enforce the callback to match the hook\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike<Event | null> {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent(options, event, hint, scope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n // If a trace context is not set on the event, we use the propagationContext set on the event to\n // generate a trace context. If the propagationContext does not have a dynamic sampling context, we\n // also generate one for it.\n const { propagationContext } = evt.sdkProcessingMetadata || {};\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext as PropagationContext;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n }\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint: EventHint = {}, scope?: Scope): PromiseLike<string | undefined> {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (__DEBUG_BUILD__) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason as SentryError;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike<Event> {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory: DataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process<T>(promise: PromiseLike<T>): void {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n protected _sendEnvelope(envelope: Envelope): PromiseLike<void | TransportMakeRequestResponse> | void {\n if (this._transport && this._dsn) {\n this.emit('beforeEnvelope', envelope);\n\n return this._transport.send(envelope).then(null, reason => {\n __DEBUG_BUILD__ && logger.error('Error while sending event:', reason);\n });\n } else {\n __DEBUG_BUILD__ && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n protected _clearOutcomes(): Outcome[] {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') as [EventDropReason, DataCategory];\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public abstract eventFromException(_exception: any, _hint?: EventHint): PromiseLike<Event>;\n\n /**\n * @inheritDoc\n */\n public abstract eventFromMessage(\n _message: string,\n // eslint-disable-next-line deprecation/deprecation\n _level?: Severity | SeverityLevel,\n _hint?: EventHint,\n ): PromiseLike<Event>;\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult: PromiseLike<Event | null> | Event | null,\n beforeSendLabel: string,\n): PromiseLike<Event | null> | Event | null {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options: ClientOptions,\n event: Event,\n hint: EventHint,\n): PromiseLike<Event | null> | Event | null {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event: Event): event is ErrorEvent {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event: Event): event is TransactionEvent {\n return event.type === 'transaction';\n}\n","import { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Exception, Severity, SeverityLevel, StackFrame, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n extractExceptionKeysForMessage,\n isDOMError,\n isDOMException,\n isError,\n isErrorEvent,\n isEvent,\n isPlainObject,\n normalizeToSize,\n resolvedSyncPromise,\n} from '@sentry/utils';\n\ntype Prototype = { constructor: (...args: unknown[]) => unknown };\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nexport function exceptionFromError(stackParser: StackParser, ex: Error): Exception {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception: Exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nexport function eventFromPlainObject(\n stackParser: StackParser,\n exception: Record<string, unknown>,\n syntheticException?: Error,\n isUnhandledRejection?: boolean,\n): Event {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event: Event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception as { values: Exception[] }).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromError(stackParser: StackParser, ex: Error): Event {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nexport function parseStackFrames(\n stackParser: StackParser,\n ex: Error & { framesToPop?: number; stacktrace?: string },\n): StackFrame[] {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex: Error & { framesToPop?: number }): number {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex: Error & { message: { error?: Error } }): string {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nexport function eventFromException(\n stackParser: StackParser,\n exception: unknown,\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike<Event> {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nexport function eventFromMessage(\n stackParser: StackParser,\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n attachStacktrace?: boolean,\n): PromiseLike<Event> {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nexport function eventFromUnknownInput(\n stackParser: StackParser,\n exception: unknown,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n isUnhandledRejection?: boolean,\n): Event {\n let event: Event;\n\n if (isErrorEvent(exception as ErrorEvent) && (exception as ErrorEvent).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception as ErrorEvent;\n return eventFromError(stackParser, errorEvent.error as Error);\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception as DOMException)) {\n const domException = exception as DOMException;\n\n if ('stack' in (exception as Error)) {\n event = eventFromError(stackParser, exception as Error);\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception as Record<string, unknown>;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception as string, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nexport function eventFromString(\n stackParser: StackParser,\n input: string,\n syntheticException?: Error,\n attachStacktrace?: boolean,\n): Event {\n const event: Event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception: Record<string, unknown>,\n { isUnhandledRejection }: { isUnhandledRejection?: boolean },\n): string {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj: unknown): string | undefined | void {\n try {\n const prototype: Prototype | null = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n","import type { DsnComponents, EventEnvelope, SdkMetadata, UserFeedback, UserFeedbackItem } from '@sentry/types';\nimport { createEnvelope, dsnToString } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nexport function createUserFeedbackEnvelope(\n feedback: UserFeedback,\n {\n metadata,\n tunnel,\n dsn,\n }: {\n metadata: SdkMetadata | undefined;\n tunnel: string | undefined;\n dsn: DsnComponents | undefined;\n },\n): EventEnvelope {\n const headers: EventEnvelope[0] = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback: UserFeedback): UserFeedbackItem {\n const feedbackHeaders: UserFeedbackItem[0] = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n","import type { Scope } from '@sentry/core';\nimport { BaseClient, SDK_VERSION } from '@sentry/core';\nimport type {\n BrowserClientProfilingOptions,\n BrowserClientReplayOptions,\n ClientOptions,\n Event,\n EventHint,\n Options,\n Severity,\n SeverityLevel,\n UserFeedback,\n} from '@sentry/types';\nimport { createClientReportEnvelope, dsnToString, getSDKSource, logger } from '@sentry/utils';\n\nimport { eventFromException, eventFromMessage } from './eventbuilder';\nimport { WINDOW } from './helpers';\nimport type { BrowserTransportOptions } from './transports/types';\nimport { createUserFeedbackEnvelope } from './userfeedback';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\nexport type BrowserOptions = Options<BrowserTransportOptions> &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * Configuration options for the Sentry Browser SDK Client class\n * @see BrowserClient for more information.\n */\nexport type BrowserClientOptions = ClientOptions<BrowserTransportOptions> &\n BrowserClientReplayOptions &\n BrowserClientProfilingOptions;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class BrowserClient extends BaseClient<BrowserClientOptions> {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n public constructor(options: BrowserClientOptions) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n public eventFromException(exception: unknown, hint?: EventHint): PromiseLike<Event> {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(\n message: string,\n // eslint-disable-next-line deprecation/deprecation\n level: Severity | SeverityLevel = 'info',\n hint?: EventHint,\n ): PromiseLike<Event> {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n public captureUserFeedback(feedback: UserFeedback): void {\n if (!this._isEnabled()) {\n __DEBUG_BUILD__ && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n void this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, hint: EventHint, scope?: Scope): PromiseLike<Event | null> {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n private _flushOutcomes(): void {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n __DEBUG_BUILD__ && logger.log('No outcomes to send');\n return;\n }\n\n if (!this._dsn) {\n __DEBUG_BUILD__ && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n void this._sendEnvelope(envelope);\n }\n}\n","import type { ClientReport, ClientReportEnvelope, ClientReportItem } from '@sentry/types';\n\nimport { createEnvelope } from './envelope';\nimport { dateTimestampInSeconds } from './time';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nexport function createClientReportEnvelope(\n discarded_events: ClientReport['discarded_events'],\n dsn?: string,\n timestamp?: number,\n): ClientReportEnvelope {\n const clientReportItem: ClientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope<ClientReportEnvelope>(dsn ? { dsn } : {}, [clientReportItem]);\n}\n","import { isNativeFetch, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\nlet cachedFetchImpl: FetchImpl | undefined = undefined;\n\nexport type FetchImpl = typeof fetch;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nexport function getNativeFetchImplementation(): FetchImpl {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n __DEBUG_BUILD__ &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nexport function clearCachedFetchImplementation(): void {\n cachedFetchImpl = undefined;\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { rejectedSyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\nimport type { FetchImpl } from './utils';\nimport { clearCachedFetchImplementation, getNativeFetchImplementation } from './utils';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nexport function makeFetchTransport(\n options: BrowserTransportOptions,\n nativeFetch: FetchImpl = getNativeFetchImplementation(),\n): Transport {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions: RequestInit = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60_000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n","import { createTransport } from '@sentry/core';\nimport type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/types';\nimport { SyncPromise } from '@sentry/utils';\n\nimport type { BrowserTransportOptions } from './types';\n\n/**\n * The DONE ready state for XmlHttpRequest\n *\n * Defining it here as a constant b/c XMLHttpRequest.DONE is not always defined\n * (e.g. during testing, it is `undefined`)\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState}\n */\nconst XHR_READYSTATE_DONE = 4;\n\n/**\n * Creates a Transport that uses the XMLHttpRequest API to send events to Sentry.\n */\nexport function makeXHRTransport(options: BrowserTransportOptions): Transport {\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n return new SyncPromise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.onerror = reject;\n\n xhr.onreadystatechange = (): void => {\n if (xhr.readyState === XHR_READYSTATE_DONE) {\n resolve({\n statusCode: xhr.status,\n headers: {\n 'x-sentry-rate-limits': xhr.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': xhr.getResponseHeader('Retry-After'),\n },\n });\n }\n };\n\n xhr.open('POST', options.url);\n\n for (const header in options.headers) {\n if (Object.prototype.hasOwnProperty.call(options.headers, header)) {\n xhr.setRequestHeader(header, options.headers[header]);\n }\n }\n\n xhr.send(request.body);\n });\n }\n\n return createTransport(options, makeRequest);\n}\n","// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n// Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this\n// software and associated documentation files(the 'Software'), to deal in the Software\n// without restriction, including without limitation the rights to use, copy, modify,\n// merge, publish, distribute, sublicense, and / or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies\n// or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { StackFrame, StackLineParser, StackLineParserFn } from '@sentry/types';\nimport { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename: string, func: string, lineno?: number, colno?: number): StackFrame {\n const frame: StackFrame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome: StackLineParserFn = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nexport const chromeStackLineParser: StackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko: StackLineParserFn = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nexport const geckoStackLineParser: StackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs: StackLineParserFn = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nexport const winjsStackLineParser: StackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10: StackLineParserFn = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nexport const opera10StackLineParser: StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11: StackLineParserFn = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nexport const opera11StackLineParser: StackLineParser = [OPERA11_PRIORITY, opera11];\n\nexport const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nexport const defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func: string, filename: string): [string, string] => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event, EventHint, Hub, Integration, Primitive, StackParser } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addInstrumentationHandler,\n getLocationHref,\n isErrorEvent,\n isPrimitive,\n isString,\n logger,\n} from '@sentry/utils';\n\nimport type { BrowserClient } from '../client';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\n/** JSDoc */\ntype GlobalHandlersIntegrations = Record<GlobalHandlersIntegrationsOptionKeys, boolean>;\n\n/** Global handlers */\nexport class GlobalHandlers implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'GlobalHandlers';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /** JSDoc */\n private readonly _options: GlobalHandlersIntegrations;\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n private _installFunc: Record<GlobalHandlersIntegrationsOptionKeys, (() => void) | undefined>;\n\n /** JSDoc */\n public constructor(options?: GlobalHandlersIntegrations) {\n this.name = GlobalHandlers.id;\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n this._installFunc = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n }\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key as GlobalHandlersIntegrationsOptionKeys];\n if (installFunc && options[key as GlobalHandlersIntegrationsOptionKeys]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key as GlobalHandlersIntegrationsOptionKeys] = undefined;\n }\n }\n }\n}\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler(): void {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data: { msg: any; url: any; line: any; column: any; error: any }) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler(): void {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e: any) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg: any, url: any, line: any, column: any): Event {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column: any): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n __DEBUG_BUILD__ && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions(): [Hub, StackParser, boolean | undefined] {\n const hub = getCurrentHub();\n const client = hub.getClient<BrowserClient>();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n","import type { Integration, WrappedFunction } from '@sentry/types';\nimport { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\n\nimport { WINDOW, wrap } from '../helpers';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\ntype XMLHttpRequestProp = 'onload' | 'onerror' | 'onprogress' | 'onreadystatechange';\n\n/** JSDoc */\ninterface TryCatchOptions {\n setTimeout: boolean;\n setInterval: boolean;\n requestAnimationFrame: boolean;\n XMLHttpRequest: boolean;\n eventTarget: boolean | string[];\n}\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nexport class TryCatch implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'TryCatch';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /** JSDoc */\n private readonly _options: TryCatchOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial<TryCatchOptions>) {\n this.name = TryCatch.id;\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n public setupOnce(): void {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n}\n\n/** JSDoc */\nfunction _wrapTimeFunction(original: () => void): () => number {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, ...args: any[]): number {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original: any): (callback: () => void) => any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: any, callback: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend: () => void): () => void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: XMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps: XMLHttpRequestProp[] = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original: WrappedFunction): () => any {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target: string): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW as { [key: string]: any };\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original: () => void): (\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ) => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): (eventName: string, fn: EventListenerObject, capture?: boolean, secure?: boolean) => void {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn as any as WrappedFunction, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener: () => void,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): (this: any, eventName: string, fn: EventListenerObject, options?: boolean | EventListenerOptions) => () => void {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n eventName: string,\n fn: EventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn as unknown as WrappedFunction;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n","/* eslint-disable deprecation/deprecation */\nimport type { Severity, SeverityLevel } from '@sentry/types';\n\n// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nexport const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nexport function severityFromString(level: Severity | SeverityLevel | string): Severity {\n return severityLevelFromString(level) as Severity;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nexport function severityLevelFromString(level: SeverityLevel | string): SeverityLevel {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') as SeverityLevel;\n}\n","type PartialURL = {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n search?: string;\n hash?: string;\n};\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not <a/> href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url: string): PartialURL {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nexport function getNumberOfUrlSegments(url: string): number {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nexport function getSanitizedUrlString(url: PartialURL): string {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n .replace(':80', '')\n .replace(':443', '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable max-lines */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Event as SentryEvent, HandlerDataFetch, HandlerDataXhr, Integration } from '@sentry/types';\nimport type {\n FetchBreadcrumbData,\n FetchBreadcrumbHint,\n XhrBreadcrumbData,\n XhrBreadcrumbHint,\n} from '@sentry/types/build/types/breadcrumb';\nimport {\n addInstrumentationHandler,\n getEventDescription,\n htmlTreeAsString,\n logger,\n parseUrl,\n safeJoin,\n SENTRY_XHR_DATA_KEY,\n severityLevelFromString,\n} from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\n\ntype HandlerData = Record<string, unknown>;\n\n/** JSDoc */\ninterface BreadcrumbsOptions {\n console: boolean;\n dom:\n | boolean\n | {\n serializeAttribute?: string | string[];\n maxStringLength?: number;\n };\n fetch: boolean;\n history: boolean;\n sentry: boolean;\n xhr: boolean;\n}\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nexport class Breadcrumbs implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Breadcrumbs';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n public readonly options: Readonly<BreadcrumbsOptions>;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: Partial<BreadcrumbsOptions>) {\n this.name = Breadcrumbs.id;\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n public setupOnce(): void {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n if (this.options.sentry) {\n const client = getCurrentHub().getClient();\n client && client.on && client.on('beforeSendEvent', addSentryBreadcrumb);\n }\n }\n}\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction addSentryBreadcrumb(event: SentryEvent): void {\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n}\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerData) => void {\n function _innerDomBreadcrumb(handlerData: HandlerData): void {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event as Event | Node;\n target = _isEvent(event)\n ? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })\n : htmlTreeAsString(event, { keyAttrs, maxStringLength });\n } catch (e) {\n target = '<unknown>';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _consoleBreadcrumb(handlerData: HandlerData & { args: unknown[]; level: string }): void {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/6010\n // see: https://github.com/getsentry/sentry-javascript/issues/5916\n for (let i = 0; i < handlerData.args.length; i++) {\n if (handlerData.args[i] === 'ref=Ref<') {\n handlerData.args[i + 1] = 'viewRef';\n break;\n }\n }\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _xhrBreadcrumb(handlerData: HandlerData & HandlerDataXhr): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data: XhrBreadcrumbData = {\n method,\n url,\n status_code,\n };\n\n const hint: XhrBreadcrumbHint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _fetchBreadcrumb(handlerData: HandlerData & HandlerDataFetch & { response?: Response }): void {\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data: FetchBreadcrumbData = handlerData.fetchData;\n const hint: FetchBreadcrumbHint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const data: FetchBreadcrumbData = {\n ...handlerData.fetchData,\n status_code: handlerData.response && handlerData.response.status,\n };\n const hint: FetchBreadcrumbHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp,\n endTimestamp,\n };\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _historyBreadcrumb(handlerData: HandlerData & { from: string; to: string }): void {\n let from: string | undefined = handlerData.from;\n let to: string | undefined = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nfunction _isEvent(event: unknown): event is Event {\n return !!event && !!(event as Record<string, unknown>).target;\n}\n","import type { Event, EventHint, Exception, ExtendedError, StackParser } from '@sentry/types';\n\nimport { isInstanceOf } from './is';\nimport { truncate } from './string';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nexport function applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n maxValueLimit: number = 250,\n key: string,\n limit: number,\n event: Event,\n hint?: EventHint,\n): void {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException: Exception | undefined =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException as ExtendedError,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation: (stackParser: StackParser, ex: Error) => Exception,\n parser: StackParser,\n limit: number,\n error: ExtendedError,\n key: string,\n prevExceptions: Exception[],\n exception: Exception,\n exceptionId: number,\n): Exception[] {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception: Exception, exceptionId: number): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n is_exception_group: true,\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception: Exception,\n source: string,\n exceptionId: number,\n parentId: number | undefined,\n): void {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions: Exception[], maxValueLength: number): Exception[] {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n","import type { Event, EventHint, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { applyAggregateErrorsToEvent } from '@sentry/utils';\n\nimport { exceptionFromError } from '../eventbuilder';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\ninterface LinkedErrorsOptions {\n key: string;\n limit: number;\n}\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string;\n\n /**\n * @inheritDoc\n */\n private readonly _key: LinkedErrorsOptions['key'];\n\n /**\n * @inheritDoc\n */\n private readonly _limit: LinkedErrorsOptions['limit'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: Partial<LinkedErrorsOptions> = {}) {\n this.name = LinkedErrors.id;\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const self = hub.getIntegration(LinkedErrors);\n\n if (!client || !self) {\n return event;\n }\n\n const options = client.getOptions();\n applyAggregateErrorsToEvent(\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n self._key,\n self._limit,\n event,\n hint,\n );\n\n return event;\n });\n }\n}\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport type { Event, Integration } from '@sentry/types';\n\nimport { WINDOW } from '../helpers';\n\n/** HttpContext integration collects information about HTTP request headers */\nexport class HttpContext implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'HttpContext';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n public constructor() {\n this.name = HttpContext.id;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n if (getCurrentHub().getIntegration(HttpContext)) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n}\n","import type { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n public constructor() {\n this.name = Dedupe.id;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const eventProcessor: EventProcessor = currentEvent => {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n __DEBUG_BUILD__ && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n","import type { Hub } from '@sentry/core';\nimport {\n getCurrentHub,\n getIntegrationsToSetup,\n getReportDialogEndpoint,\n initAndBind,\n Integrations as CoreIntegrations,\n} from '@sentry/core';\nimport type { UserFeedback } from '@sentry/types';\nimport { addInstrumentationHandler, logger, stackParserFromStackParserOptions, supportsFetch } from '@sentry/utils';\n\nimport type { BrowserClientOptions, BrowserOptions } from './client';\nimport { BrowserClient } from './client';\nimport type { ReportDialogOptions } from './helpers';\nimport { WINDOW, wrap as internalWrap } from './helpers';\nimport { Breadcrumbs, Dedupe, GlobalHandlers, HttpContext, LinkedErrors, TryCatch } from './integrations';\nimport { defaultStackParser } from './stack-parsers';\nimport { makeFetchTransport, makeXHRTransport } from './transports';\n\nexport const defaultIntegrations = [\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\n];\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\ndeclare const __SENTRY_RELEASE__: string | undefined;\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nexport function init(options: BrowserOptions = {}): void {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions: BrowserClientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nexport function showReportDialog(options: ReportDialogOptions = {}, hub: Hub = getCurrentHub()): void {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n __DEBUG_BUILD__ && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n __DEBUG_BUILD__ && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n __DEBUG_BUILD__ && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function forceLoad(): void {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nexport function onLoad(callback: () => void): void {\n callback();\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function wrap(fn: (...args: any) => any): any {\n return internalWrap(fn)();\n}\n\nfunction startSessionOnHub(hub: Hub): void {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking(): void {\n if (typeof WINDOW.document === 'undefined') {\n __DEBUG_BUILD__ &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nexport function captureUserFeedback(feedback: UserFeedback): void {\n const client = getCurrentHub().getClient<BrowserClient>();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n","import type { Client, ClientOptions } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass<F extends Client, O extends ClientOptions> = new (options: O) => F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind<F extends Client, O extends ClientOptions>(\n clientClass: ClientClass<F, O>,\n options: O,\n): void {\n if (options.debug === true) {\n if (__DEBUG_BUILD__) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n }\n }\n const hub = getCurrentHub();\n const scope = hub.getScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n","import type { Event, EventHint, EventProcessor } from '@sentry/types';\nimport { SyncPromise, getGlobalSingleton, isThenable, logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from './debug-build';\n\n/**\n * Returns the global event processors.\n * @deprecated Global event processors will be removed in v8.\n */\nexport function getGlobalEventProcessors(): EventProcessor[] {\n return getGlobalSingleton<EventProcessor[]>('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8.\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n // eslint-disable-next-line deprecation/deprecation\n getGlobalEventProcessors().push(callback);\n}\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nexport function notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint: EventHint,\n index: number = 0,\n): PromiseLike<Event | null> {\n return new SyncPromise<Event | null>((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n","import type { Span, SpanJSON, SpanTimeInput, TraceContext } from '@sentry/types';\nimport { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';\nimport type { Span as SpanClass } from '../tracing/span';\n\n// These are aligned with OpenTelemetry trace flags\nexport const TRACE_FLAG_NONE = 0x0;\nexport const TRACE_FLAG_SAMPLED = 0x1;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n */\nexport function spanToTraceContext(span: Span): TraceContext {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n data,\n op,\n parent_span_id,\n span_id,\n status,\n tags,\n trace_id,\n origin,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nexport function spanToTraceHeader(span: Span): string {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a span time input intp a timestamp in seconds.\n */\nexport function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp: number): number {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n * Note that all fields returned here are optional and need to be guarded against.\n *\n * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n * And `spanToJSON` needs the Span class from `span.ts` to check here.\n * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again.\n */\nexport function spanToJSON(span: Span): Partial<SpanJSON> {\n if (spanIsSpanClass(span)) {\n return span.getSpanJSON();\n }\n\n // Fallback: We also check for `.toJSON()` here...\n // eslint-disable-next-line deprecation/deprecation\n if (typeof span.toJSON === 'function') {\n // eslint-disable-next-line deprecation/deprecation\n return span.toJSON();\n }\n\n return {};\n}\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSpanClass(span: Span): span is SpanClass {\n return typeof (span as SpanClass).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nexport function spanIsSampled(span: Span): boolean {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n // eslint-disable-next-line no-bitwise\n return Boolean(traceFlags & TRACE_FLAG_SAMPLED);\n}\n","import type { Span } from '@sentry/types';\n\n/**\n * Returns the root span of a given span.\n *\n * As long as we use `Transaction`s internally, the returned root span\n * will be a `Transaction` but be aware that this might change in the future.\n *\n * If the given span has no root span or transaction, `undefined` is returned.\n */\nexport function getRootSpan(span: Span): Span | undefined {\n // TODO (v8): Remove this check and just return span\n // eslint-disable-next-line deprecation/deprecation\n return span.transaction;\n}\n","import type { Breadcrumb, Event, ScopeData, Span } from '@sentry/types';\nimport { arrayify, dropUndefinedKeys } from '@sentry/utils';\nimport { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext';\nimport { getRootSpan } from './getRootSpan';\nimport { spanToJSON, spanToTraceContext } from './spanUtils';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nexport function applyScopeDataToEvent(event: Event, data: ScopeData): void {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nexport function mergeScopeData(data: ScopeData, mergeData: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n // eslint-disable-next-line deprecation/deprecation\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nexport function mergeAndOverwriteScopeData<\n Prop extends 'extra' | 'tags' | 'user' | 'contexts' | 'sdkProcessingMetadata',\n Data extends ScopeData,\n>(data: Data, prop: Prop, mergeVal: Data[Prop]): void {\n if (mergeVal && Object.keys(mergeVal).length) {\n // Clone object\n data[prop] = { ...data[prop] };\n for (const key in mergeVal) {\n if (Object.prototype.hasOwnProperty.call(mergeVal, key)) {\n data[prop][key] = mergeVal[key];\n }\n }\n }\n}\n\n/** Exported only for tests */\nexport function mergeArray<Prop extends 'breadcrumbs' | 'fingerprint'>(\n event: Event,\n prop: Prop,\n mergeVal: ScopeData[Prop],\n): void {\n const prevVal = event[prop];\n // If we are not merging any new values,\n // we only need to proceed if there was an empty array before (as we want to replace it with undefined)\n if (!mergeVal.length && (!prevVal || prevVal.length)) {\n return;\n }\n\n const merged = [...(prevVal || []), ...mergeVal] as ScopeData[Prop];\n event[prop] = merged.length ? merged : undefined;\n}\n\nfunction applyDataToEvent(event: Event, data: ScopeData): void {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n // eslint-disable-next-line deprecation/deprecation\n transactionName,\n } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (cleanedExtra && Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (cleanedTags && Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (cleanedUser && Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (cleanedContexts && Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n if (transactionName) {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event: Event, breadcrumbs: Breadcrumb[]): void {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event: Event, sdkProcessingMetadata: ScopeData['sdkProcessingMetadata']): void {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event: Event, span: Span): void {\n event.contexts = { trace: spanToTraceContext(span), ...event.contexts };\n const rootSpan = getRootSpan(span);\n if (rootSpan) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event: Event, fingerprint: ScopeData['fingerprint'] | undefined): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n","import { DEBUG_BUILD } from '../debug-build';\nimport { logger } from '../logger';\nimport { getFunctionName } from '../stacktrace';\n\nexport type InstrumentHandlerType = 'console' | 'dom' | 'fetch' | 'history' | 'xhr' | 'error' | 'unhandledrejection';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type InstrumentHandlerCallback = (data: any) => void;\n\n// We keep the handlers globally\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Add a handler function. */\nexport function addHandler(type: InstrumentHandlerType, handler: InstrumentHandlerCallback): void {\n handlers[type] = handlers[type] || [];\n (handlers[type] as InstrumentHandlerCallback[]).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nexport function resetInstrumentationHandlers(): void {\n Object.keys(handlers).forEach(key => {\n handlers[key as InstrumentHandlerType] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nexport function maybeInstrument(type: InstrumentHandlerType, instrumentFn: () => void): void {\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nexport function triggerHandlers(type: InstrumentHandlerType, data: unknown): void {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { ConsoleLevel, HandlerDataConsole } from '@sentry/types';\n\nimport { CONSOLE_LEVELS, originalConsoleMethods } from '../logger';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addConsoleInstrumentationHandler(handler: (data: HandlerDataConsole) => void): void {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole(): void {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level: ConsoleLevel): void {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod: () => any): Function {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args: any[]): void {\n const handlerData: HandlerDataConsole = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataDom } from '@sentry/types';\n\nimport { uuid4 } from '../misc';\nimport { addNonEnumerableProperty, fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype SentryWrappedTarget = HTMLElement & { _sentryId?: string };\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID: number | undefined;\nlet lastCapturedEventType: string | undefined;\nlet lastCapturedEventTargetId: string | undefined;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addClickKeypressInstrumentationHandler(handler: (data: HandlerDataDom) => void): void {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nexport function instrumentDOM(): void {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW as any)[target] && (WINDOW as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener: AddEventListener): AddEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function (\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event: Event): boolean {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target as SentryWrappedTarget)._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType: string, target: SentryWrappedTarget | null): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler: (data: HandlerDataDom) => void,\n globalListener: boolean = false,\n): (event: Event) => void {\n return (event: Event & { _sentryCaptured?: true }): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData: HandlerDataDom = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event: Event): SentryWrappedTarget | null {\n try {\n return event.target as SentryWrappedTarget | null;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataFetch } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsNativeFetch } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\ntype FetchResource = string | { toString(): string } | { url: string };\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addFetchInstrumentationHandler(handler: (data: HandlerDataFetch) => void): void {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, instrumentFetch);\n}\n\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch: () => void): () => void {\n return function (...args: any[]): void {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData: HandlerDataFetch = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response: Response) => {\n const finishedHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n };\n\n triggerHandlers('fetch', finishedHandlerData);\n return response;\n },\n (error: Error) => {\n const erroredHandlerData: HandlerDataFetch = {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n };\n\n triggerHandlers('fetch', erroredHandlerData);\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp<T extends string>(obj: unknown, prop: T): obj is Record<string, string> {\n return !!obj && typeof obj === 'object' && !!(obj as Record<string, string>)[prop];\n}\n\nfunction getUrlFromResource(resource: FetchResource): string {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nexport function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: string } {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs as [FetchResource, object];\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg as FetchResource),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n","import type { HandlerDataError } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnErrorHandler: (typeof GLOBAL_OBJ)['onerror'] | null = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalErrorInstrumentationHandler(handler: (data: HandlerDataError) => void): void {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError(): void {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n GLOBAL_OBJ.onerror = function (\n msg: string | object,\n url?: string,\n line?: number,\n column?: number,\n error?: Error,\n ): boolean {\n const handlerData: HandlerDataError = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { HandlerDataUnhandledRejection } from '@sentry/types';\n\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nlet _oldOnUnhandledRejectionHandler: (typeof GLOBAL_OBJ)['onunhandledrejection'] | null = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addGlobalUnhandledRejectionInstrumentationHandler(\n handler: (data: HandlerDataUnhandledRejection) => void,\n): void {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n GLOBAL_OBJ.onunhandledrejection = function (e: any): boolean {\n const handlerData: HandlerDataUnhandledRejection = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataHistory } from '@sentry/types';\n\nimport { fill } from '../object';\nimport { supportsHistory } from '../supports';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nlet lastHref: string | undefined;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addHistoryInstrumentationHandler(handler: (data: HandlerDataHistory) => void): void {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function (this: WindowEventHandlers, ...args: any[]): any {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function (this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n const handlerData: HandlerDataHistory = { from, to };\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n","// TODO(v8): Move everything in this file into the browser package. Nothing here is generic and we run risk of leaking browser types into non-browser packages.\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport type { HandlerDataXhr, SentryWrappedXMLHttpRequest, WrappedFunction } from '@sentry/types';\n\nimport { isString } from '../is';\nimport { fill } from '../object';\nimport { GLOBAL_OBJ } from '../worldwide';\nimport { addHandler, maybeInstrument, triggerHandlers } from './_handlers';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nexport const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addXhrInstrumentationHandler(handler: (data: HandlerDataXhr) => void): void {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nexport function instrumentXHR(): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW as any).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const startTimestamp = Date.now();\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(args[0]) ? args[0].toUpperCase() : undefined;\n const url = parseUrl(args[1]);\n\n if (!method || !url) {\n return originalOpen.apply(this, args);\n }\n\n this[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler: () => void = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData: HandlerDataXhr = {\n args: [method, url],\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original: WrappedFunction): Function {\n return function (this: SentryWrappedXMLHttpRequest, ...setRequestHeaderArgs: unknown[]): void {\n const [header, value] = setRequestHeaderArgs;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend: () => void): () => void {\n return function (this: XMLHttpRequest & SentryWrappedXMLHttpRequest, ...args: any[]): void {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(this, args);\n }\n\n if (args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n const handlerData: HandlerDataXhr = {\n args: [sentryXhrData.method, sentryXhrData.url],\n startTimestamp: Date.now(),\n xhr: this,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nfunction parseUrl(url: string | unknown): string | undefined {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url as URL).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n","// TODO(v8): Consider moving this file (or at least parts of it) into the browser package. The registered handlers are mostly non-generic and we risk leaking runtime specific code into generic packages.\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport { logger } from './../logger';\nimport type {\n InstrumentHandlerCallback as _InstrumentHandlerCallback,\n InstrumentHandlerType as _InstrumentHandlerType,\n} from './_handlers';\nimport { resetInstrumentationHandlers } from './_handlers';\nimport { addConsoleInstrumentationHandler } from './console';\nimport { addClickKeypressInstrumentationHandler } from './dom';\nimport { addFetchInstrumentationHandler } from './fetch';\nimport { addGlobalErrorInstrumentationHandler } from './globalError';\nimport { addGlobalUnhandledRejectionInstrumentationHandler } from './globalUnhandledRejection';\nimport { addHistoryInstrumentationHandler } from './history';\nimport { SENTRY_XHR_DATA_KEY, addXhrInstrumentationHandler } from './xhr';\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n * @deprecated Use the proper function per instrumentation type instead!\n */\nexport function addInstrumentationHandler(type: _InstrumentHandlerType, callback: _InstrumentHandlerCallback): void {\n switch (type) {\n case 'console':\n return addConsoleInstrumentationHandler(callback);\n case 'dom':\n return addClickKeypressInstrumentationHandler(callback);\n case 'xhr':\n return addXhrInstrumentationHandler(callback);\n case 'fetch':\n return addFetchInstrumentationHandler(callback);\n case 'history':\n return addHistoryInstrumentationHandler(callback);\n case 'error':\n return addGlobalErrorInstrumentationHandler(callback);\n case 'unhandledrejection':\n return addGlobalUnhandledRejectionInstrumentationHandler(callback);\n default:\n DEBUG_BUILD && logger.warn('unknown instrumentation type:', type);\n }\n}\n\n/**\n * @deprecated Use the specific handler data types from @sentry/types instead, e.g. HandlerDataFetch, HandlerDataConsole, ...\n */\ntype InstrumentHandlerCallback = _InstrumentHandlerCallback;\n\n/**\n * @deprecated Use the specific handler functions instead, e.g. addConsoleInstrumentationHandler, ...\n */\ntype InstrumentHandlerType = _InstrumentHandlerType;\n\n// eslint-disable-next-line deprecation/deprecation\nexport type { InstrumentHandlerCallback, InstrumentHandlerType };\n\nexport {\n addConsoleInstrumentationHandler,\n addClickKeypressInstrumentationHandler,\n addXhrInstrumentationHandler,\n addFetchInstrumentationHandler,\n addHistoryInstrumentationHandler,\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n SENTRY_XHR_DATA_KEY,\n // Only exported for tests\n resetInstrumentationHandlers,\n};\n","var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n var _a;\n var host = (_a = n) === null || _a === void 0 ? void 0 : _a.host;\n return Boolean(host && host.shadowRoot && host.shadowRoot === n);\n}\nfunction maskInputValue(_a) {\n var maskInputOptions = _a.maskInputOptions, tagName = _a.tagName, type = _a.type, value = _a.value, maskInputFn = _a.maskInputFn;\n var text = value || '';\n if (maskInputOptions[tagName.toLowerCase()] ||\n maskInputOptions[type]) {\n if (maskInputFn) {\n text = maskInputFn(text);\n }\n else {\n text = '*'.repeat(text.length);\n }\n }\n return text;\n}\nvar ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\nfunction is2DCanvasBlank(canvas) {\n var ctx = canvas.getContext('2d');\n if (!ctx)\n return true;\n var chunkSize = 50;\n for (var x = 0; x < canvas.width; x += chunkSize) {\n for (var y = 0; y < canvas.height; y += chunkSize) {\n var getImageData = ctx.getImageData;\n var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n var pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some(function (pixel) { return pixel !== 0; }))\n return false;\n }\n }\n return true;\n}\n\nvar _id = 1;\nvar tagNameRegex = new RegExp('[^a-z0-9-_:]');\nvar IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return 'form';\n }\n var processedTagName = element.tagName.toLowerCase().trim();\n if (tagNameRegex.test(processedTagName)) {\n return 'div';\n }\n return processedTagName;\n}\nfunction getCssRulesString(s) {\n try {\n var rules = s.rules || s.cssRules;\n return rules ? Array.from(rules).map(getCssRuleString).join('') : null;\n }\n catch (error) {\n return null;\n }\n}\nfunction getCssRuleString(rule) {\n var cssStringified = rule.cssText;\n if (isCSSImportRule(rule)) {\n try {\n cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;\n }\n catch (_a) {\n }\n }\n return cssStringified;\n}\nfunction isCSSImportRule(rule) {\n return 'styleSheet' in rule;\n}\nfunction stringifyStyleSheet(sheet) {\n return sheet.cssRules\n ? Array.from(sheet.cssRules)\n .map(function (rule) { return rule.cssText || ''; })\n .join('')\n : '';\n}\nfunction extractOrigin(url) {\n var origin = '';\n if (url.indexOf('//') > -1) {\n origin = url.split('/').slice(0, 3).join('/');\n }\n else {\n origin = url.split('/')[0];\n }\n origin = origin.split('?')[0];\n return origin;\n}\nvar canvasService;\nvar canvasCtx;\nvar URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nvar RELATIVE_PATH = /^(?!www\\.|(?:http|ftp)s?:\\/\\/|[A-Za-z]:\\\\|\\/\\/|#).*/;\nvar DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, function (origin, quote1, path1, quote2, path2, path3) {\n var filePath = path1 || path2 || path3;\n var maybeQuote = quote1 || quote2 || '';\n if (!filePath) {\n return origin;\n }\n if (!RELATIVE_PATH.test(filePath)) {\n return \"url(\" + maybeQuote + filePath + maybeQuote + \")\";\n }\n if (DATA_URI.test(filePath)) {\n return \"url(\" + maybeQuote + filePath + maybeQuote + \")\";\n }\n if (filePath[0] === '/') {\n return \"url(\" + maybeQuote + (extractOrigin(href) + filePath) + maybeQuote + \")\";\n }\n var stack = href.split('/');\n var parts = filePath.split('/');\n stack.pop();\n for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {\n var part = parts_1[_i];\n if (part === '.') {\n continue;\n }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return \"url(\" + maybeQuote + stack.join('/') + maybeQuote + \")\";\n });\n}\nvar SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nvar SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === '') {\n return attributeValue;\n }\n var pos = 0;\n function collectCharacters(regEx) {\n var chars;\n var match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return '';\n }\n var output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n var url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === ',') {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n }\n else {\n var descriptorsStr = '';\n url = absoluteToDoc(doc, url);\n var inParens = false;\n while (true) {\n var c = attributeValue.charAt(pos);\n if (c === '') {\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\n }\n else {\n if (c === ')') {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(', ');\n}\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === '') {\n return attributeValue;\n }\n var a = doc.createElement('a');\n a.href = attributeValue;\n return a.href;\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\n}\nfunction getHref() {\n var a = document.createElement('a');\n a.href = '';\n return a.href;\n}\nfunction transformAttribute(doc, tagName, name, value) {\n if (name === 'src' || (name === 'href' && value)) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n value &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset' && value) {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style' && value) {\n return absoluteToStylesheet(value, getHref());\n }\n else if (tagName === 'object' && name === 'data' && value) {\n return absoluteToDoc(doc, value);\n }\n else {\n return value;\n }\n}\nfunction _isBlockedElement(element, blockClass, blockSelector) {\n if (typeof blockClass === 'string') {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n }\n else {\n for (var eIndex = 0; eIndex < element.classList.length; eIndex++) {\n var className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n return false;\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector) {\n if (!node) {\n return false;\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n if (typeof maskTextClass === 'string') {\n if (node.classList.contains(maskTextClass)) {\n return true;\n }\n }\n else {\n for (var eIndex = 0; eIndex < node.classList.length; eIndex++) {\n var className = node.classList[eIndex];\n if (maskTextClass.test(className)) {\n return true;\n }\n }\n }\n if (maskTextSelector) {\n if (node.matches(maskTextSelector)) {\n return true;\n }\n }\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector);\n }\n if (node.nodeType === node.TEXT_NODE) {\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector);\n }\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector);\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n var win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n var fired = false;\n var readyState;\n try {\n readyState = win.document.readyState;\n }\n catch (error) {\n return;\n }\n if (readyState !== 'complete') {\n var timer_1 = setTimeout(function () {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener('load', function () {\n clearTimeout(timer_1);\n fired = true;\n listener();\n });\n return;\n }\n var blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n iframeEl.src === '') {\n setTimeout(listener, 0);\n return;\n }\n iframeEl.addEventListener('load', listener);\n}\nfunction serializeNode(n, options) {\n var _a;\n var doc = options.doc, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, inlineStylesheet = options.inlineStylesheet, _b = options.maskInputOptions, maskInputOptions = _b === void 0 ? {} : _b, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, _c = options.dataURLOptions, dataURLOptions = _c === void 0 ? {} : _c, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn;\n var rootId;\n if (doc.__sn) {\n var docId = doc.__sn.id;\n rootId = docId === 1 ? undefined : docId;\n }\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== 'CSS1Compat') {\n return {\n type: NodeType.Document,\n childNodes: [],\n compatMode: n.compatMode,\n rootId: rootId\n };\n }\n else {\n return {\n type: NodeType.Document,\n childNodes: [],\n rootId: rootId\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId: rootId\n };\n case n.ELEMENT_NODE:\n var needBlock = _isBlockedElement(n, blockClass, blockSelector);\n var tagName = getValidTagName(n);\n var attributes_1 = {};\n for (var _i = 0, _d = Array.from(n.attributes); _i < _d.length; _i++) {\n var _e = _d[_i], name_1 = _e.name, value = _e.value;\n attributes_1[name_1] = transformAttribute(doc, tagName, name_1, value);\n }\n if (tagName === 'link' && inlineStylesheet) {\n var stylesheet = Array.from(doc.styleSheets).find(function (s) {\n return s.href === n.href;\n });\n var cssText = null;\n if (stylesheet) {\n cssText = getCssRulesString(stylesheet);\n }\n if (cssText) {\n delete attributes_1.rel;\n delete attributes_1.href;\n attributes_1._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText ||\n n.textContent ||\n '').trim().length) {\n var cssText = getCssRulesString(n.sheet);\n if (cssText) {\n attributes_1._cssText = absoluteToStylesheet(cssText, getHref());\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select') {\n var value = n.value;\n if (attributes_1.type !== 'radio' &&\n attributes_1.type !== 'checkbox' &&\n attributes_1.type !== 'submit' &&\n attributes_1.type !== 'button' &&\n value) {\n attributes_1.value = maskInputValue({\n type: attributes_1.type,\n tagName: tagName,\n value: value,\n maskInputOptions: maskInputOptions,\n maskInputFn: maskInputFn\n });\n }\n else if (n.checked) {\n attributes_1.checked = n.checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes_1.selected = true;\n }\n else {\n delete attributes_1.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes_1.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n var canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n var blankCanvas = document.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes_1.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === 'img' && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement('canvas');\n canvasCtx = canvasService.getContext('2d');\n }\n var image_1 = n;\n var oldValue_1 = image_1.crossOrigin;\n image_1.crossOrigin = 'anonymous';\n var recordInlineImage = function () {\n try {\n canvasService.width = image_1.naturalWidth;\n canvasService.height = image_1.naturalHeight;\n canvasCtx.drawImage(image_1, 0, 0);\n attributes_1.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n catch (err) {\n console.warn(\"Cannot inline img src=\" + image_1.currentSrc + \"! Error: \" + err);\n }\n oldValue_1\n ? (attributes_1.crossOrigin = oldValue_1)\n : delete attributes_1.crossOrigin;\n };\n if (image_1.complete && image_1.naturalWidth !== 0)\n recordInlineImage();\n else\n image_1.onload = recordInlineImage;\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes_1.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes_1.rr_mediaCurrentTime = n.currentTime;\n }\n if (n.scrollLeft) {\n attributes_1.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes_1.rr_scrollTop = n.scrollTop;\n }\n if (needBlock) {\n var _f = n.getBoundingClientRect(), width = _f.width, height = _f.height;\n attributes_1 = {\n \"class\": attributes_1[\"class\"],\n rr_width: width + \"px\",\n rr_height: height + \"px\"\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes_1.src)) {\n if (!n.contentDocument) {\n attributes_1.rr_src = attributes_1.src;\n }\n delete attributes_1.src;\n }\n return {\n type: NodeType.Element,\n tagName: tagName,\n attributes: attributes_1,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock: needBlock,\n rootId: rootId\n };\n case n.TEXT_NODE:\n var parentTagName = n.parentNode && n.parentNode.tagName;\n var textContent = n.textContent;\n var isStyle = parentTagName === 'STYLE' ? true : undefined;\n var isScript = parentTagName === 'SCRIPT' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\n textContent = stringifyStyleSheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(\"Cannot get CSS styles from text's parentNode. Error: \" + err, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref());\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n if (!isStyle &&\n !isScript &&\n needMaskingText(n, maskTextClass, maskTextSelector) &&\n textContent) {\n textContent = maskTextFn\n ? maskTextFn(textContent)\n : textContent.replace(/[\\S]/g, '*');\n }\n return {\n type: NodeType.Text,\n textContent: textContent || '',\n isStyle: isStyle,\n rootId: rootId\n };\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType.CDATA,\n textContent: '',\n rootId: rootId\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType.Comment,\n textContent: n.textContent || '',\n rootId: rootId\n };\n default:\n return false;\n }\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType.Comment) {\n return true;\n }\n else if (sn.type === NodeType.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'preload' &&\n sn.attributes.as === 'script') ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n sn.attributes.href.endsWith('.js')))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n var doc = options.doc, map = options.map, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, _a = options.skipChild, skipChild = _a === void 0 ? false : _a, _b = options.inlineStylesheet, inlineStylesheet = _b === void 0 ? true : _b, _c = options.maskInputOptions, maskInputOptions = _c === void 0 ? {} : _c, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, slimDOMOptions = options.slimDOMOptions, _d = options.dataURLOptions, dataURLOptions = _d === void 0 ? {} : _d, _e = options.inlineImages, inlineImages = _e === void 0 ? false : _e, _f = options.recordCanvas, recordCanvas = _f === void 0 ? false : _f, onSerialize = options.onSerialize, onIframeLoad = options.onIframeLoad, _g = options.iframeLoadTimeout, iframeLoadTimeout = _g === void 0 ? 5000 : _g, _h = options.keepIframeSrcFn, keepIframeSrcFn = _h === void 0 ? function () { return false; } : _h;\n var _j = options.preserveWhiteSpace, preserveWhiteSpace = _j === void 0 ? true : _j;\n var _serializedNode = serializeNode(n, {\n doc: doc,\n blockClass: blockClass,\n blockSelector: blockSelector,\n maskTextClass: maskTextClass,\n maskTextSelector: maskTextSelector,\n inlineStylesheet: inlineStylesheet,\n maskInputOptions: maskInputOptions,\n maskTextFn: maskTextFn,\n maskInputFn: maskInputFn,\n dataURLOptions: dataURLOptions,\n inlineImages: inlineImages,\n recordCanvas: recordCanvas,\n keepIframeSrcFn: keepIframeSrcFn\n });\n if (!_serializedNode) {\n console.warn(n, 'not serialized');\n return null;\n }\n var id;\n if ('__sn' in n) {\n id = n.__sn.id;\n }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n var serializedNode = Object.assign(_serializedNode, { id: id });\n n.__sn = serializedNode;\n if (id === IGNORED_NODE) {\n return null;\n }\n map[id] = n;\n if (onSerialize) {\n onSerialize(n);\n }\n var recordChild = !skipChild;\n if (serializedNode.type === NodeType.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n if (n.shadowRoot)\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType.Document ||\n serializedNode.type === NodeType.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n _serializedNode.type === NodeType.Element &&\n _serializedNode.tagName === 'head') {\n preserveWhiteSpace = false;\n }\n var bypassOptions = {\n doc: doc,\n map: map,\n blockClass: blockClass,\n blockSelector: blockSelector,\n maskTextClass: maskTextClass,\n maskTextSelector: maskTextSelector,\n skipChild: skipChild,\n inlineStylesheet: inlineStylesheet,\n maskInputOptions: maskInputOptions,\n maskTextFn: maskTextFn,\n maskInputFn: maskInputFn,\n slimDOMOptions: slimDOMOptions,\n dataURLOptions: dataURLOptions,\n inlineImages: inlineImages,\n recordCanvas: recordCanvas,\n preserveWhiteSpace: preserveWhiteSpace,\n onSerialize: onSerialize,\n onIframeLoad: onIframeLoad,\n iframeLoadTimeout: iframeLoadTimeout,\n keepIframeSrcFn: keepIframeSrcFn\n };\n for (var _i = 0, _k = Array.from(n.childNodes); _i < _k.length; _i++) {\n var childN = _k[_i];\n var serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n) && n.shadowRoot) {\n for (var _l = 0, _m = Array.from(n.shadowRoot.childNodes); _l < _m.length; _l++) {\n var childN = _m[_l];\n var serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedChildNode.isShadow = true;\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode && isShadowRoot(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(n, function () {\n var iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n var serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n map: map,\n blockClass: blockClass,\n blockSelector: blockSelector,\n maskTextClass: maskTextClass,\n maskTextSelector: maskTextSelector,\n skipChild: false,\n inlineStylesheet: inlineStylesheet,\n maskInputOptions: maskInputOptions,\n maskTextFn: maskTextFn,\n maskInputFn: maskInputFn,\n slimDOMOptions: slimDOMOptions,\n dataURLOptions: dataURLOptions,\n inlineImages: inlineImages,\n recordCanvas: recordCanvas,\n preserveWhiteSpace: preserveWhiteSpace,\n onSerialize: onSerialize,\n onIframeLoad: onIframeLoad,\n iframeLoadTimeout: iframeLoadTimeout,\n keepIframeSrcFn: keepIframeSrcFn\n });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n var _a = options || {}, _b = _a.blockClass, blockClass = _b === void 0 ? 'rr-block' : _b, _c = _a.blockSelector, blockSelector = _c === void 0 ? null : _c, _d = _a.maskTextClass, maskTextClass = _d === void 0 ? 'rr-mask' : _d, _e = _a.maskTextSelector, maskTextSelector = _e === void 0 ? null : _e, _f = _a.inlineStylesheet, inlineStylesheet = _f === void 0 ? true : _f, _g = _a.inlineImages, inlineImages = _g === void 0 ? false : _g, _h = _a.recordCanvas, recordCanvas = _h === void 0 ? false : _h, _j = _a.maskAllInputs, maskAllInputs = _j === void 0 ? false : _j, maskTextFn = _a.maskTextFn, maskInputFn = _a.maskInputFn, _k = _a.slimDOM, slimDOM = _k === void 0 ? false : _k, dataURLOptions = _a.dataURLOptions, preserveWhiteSpace = _a.preserveWhiteSpace, onSerialize = _a.onSerialize, onIframeLoad = _a.onIframeLoad, iframeLoadTimeout = _a.iframeLoadTimeout, _l = _a.keepIframeSrcFn, keepIframeSrcFn = _l === void 0 ? function () { return false; } : _l;\n var idNodeMap = {};\n var maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true\n }\n : maskAllInputs === false\n ? {\n password: true\n }\n : maskAllInputs;\n var slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true\n }\n : slimDOM === false\n ? {}\n : slimDOM;\n return [\n serializeNodeWithId(n, {\n doc: n,\n map: idNodeMap,\n blockClass: blockClass,\n blockSelector: blockSelector,\n maskTextClass: maskTextClass,\n maskTextSelector: maskTextSelector,\n skipChild: false,\n inlineStylesheet: inlineStylesheet,\n maskInputOptions: maskInputOptions,\n maskTextFn: maskTextFn,\n maskInputFn: maskInputFn,\n slimDOMOptions: slimDOMOptions,\n dataURLOptions: dataURLOptions,\n inlineImages: inlineImages,\n recordCanvas: recordCanvas,\n preserveWhiteSpace: preserveWhiteSpace,\n onSerialize: onSerialize,\n onIframeLoad: onIframeLoad,\n iframeLoadTimeout: iframeLoadTimeout,\n keepIframeSrcFn: keepIframeSrcFn\n }),\n idNodeMap,\n ];\n}\n\nvar commentre = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\nfunction parse(css, options) {\n if (options === void 0) { options = {}; }\n var lineno = 1;\n var column = 1;\n function updatePosition(str) {\n var lines = str.match(/\\n/g);\n if (lines) {\n lineno += lines.length;\n }\n var i = str.lastIndexOf('\\n');\n column = i === -1 ? column + str.length : str.length - i;\n }\n function position() {\n var start = { line: lineno, column: column };\n return function (node) {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n var Position = (function () {\n function Position(start) {\n this.start = start;\n this.end = { line: lineno, column: column };\n this.source = options.source;\n }\n return Position;\n }());\n Position.prototype.content = css;\n var errorsList = [];\n function error(msg) {\n var err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = css;\n if (options.silent) {\n errorsList.push(err);\n }\n else {\n throw err;\n }\n }\n function stylesheet() {\n var rulesList = rules();\n return {\n type: 'stylesheet',\n stylesheet: {\n source: options.source,\n rules: rulesList,\n parsingErrors: errorsList\n }\n };\n }\n function open() {\n return match(/^{\\s*/);\n }\n function close() {\n return match(/^}/);\n }\n function rules() {\n var node;\n var rules = [];\n whitespace();\n comments(rules);\n while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {\n if (node !== false) {\n rules.push(node);\n comments(rules);\n }\n }\n return rules;\n }\n function match(re) {\n var m = re.exec(css);\n if (!m) {\n return;\n }\n var str = m[0];\n updatePosition(str);\n css = css.slice(str.length);\n return m;\n }\n function whitespace() {\n match(/^\\s*/);\n }\n function comments(rules) {\n if (rules === void 0) { rules = []; }\n var c;\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n c = comment();\n }\n return rules;\n }\n function comment() {\n var pos = position();\n if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {\n return;\n }\n var i = 2;\n while ('' !== css.charAt(i) &&\n ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {\n ++i;\n }\n i += 2;\n if ('' === css.charAt(i - 1)) {\n return error('End of comment missing');\n }\n var str = css.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n css = css.slice(i);\n column += 2;\n return pos({\n type: 'comment',\n comment: str\n });\n }\n function selector() {\n var m = match(/^([^{]+)/);\n if (!m) {\n return;\n }\n return trim(m[0])\n .replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/g, '')\n .replace(/\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'/g, function (m) {\n return m.replace(/,/g, '\\u200C');\n })\n .split(/\\s*(?![^(]*\\)),\\s*/)\n .map(function (s) {\n return s.replace(/\\u200C/g, ',');\n });\n }\n function declaration() {\n var pos = position();\n var propMatch = match(/^(\\*?[-#\\/\\*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/);\n if (!propMatch) {\n return;\n }\n var prop = trim(propMatch[0]);\n if (!match(/^:\\s*/)) {\n return error(\"property missing ':'\");\n }\n var val = match(/^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^\\)]*?\\)|[^};])+)/);\n var ret = pos({\n type: 'declaration',\n property: prop.replace(commentre, ''),\n value: val ? trim(val[0]).replace(commentre, '') : ''\n });\n match(/^[;\\s]*/);\n return ret;\n }\n function declarations() {\n var decls = [];\n if (!open()) {\n return error(\"missing '{'\");\n }\n comments(decls);\n var decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n decl = declaration();\n }\n if (!close()) {\n return error(\"missing '}'\");\n }\n return decls;\n }\n function keyframe() {\n var m;\n var vals = [];\n var pos = position();\n while ((m = match(/^((\\d+\\.\\d+|\\.\\d+|\\d+)%?|[a-z]+)\\s*/))) {\n vals.push(m[1]);\n match(/^,\\s*/);\n }\n if (!vals.length) {\n return;\n }\n return pos({\n type: 'keyframe',\n values: vals,\n declarations: declarations()\n });\n }\n function atkeyframes() {\n var pos = position();\n var m = match(/^@([-\\w]+)?keyframes\\s*/);\n if (!m) {\n return;\n }\n var vendor = m[1];\n m = match(/^([-\\w]+)\\s*/);\n if (!m) {\n return error('@keyframes missing name');\n }\n var name = m[1];\n if (!open()) {\n return error(\"@keyframes missing '{'\");\n }\n var frame;\n var frames = comments();\n while ((frame = keyframe())) {\n frames.push(frame);\n frames = frames.concat(comments());\n }\n if (!close()) {\n return error(\"@keyframes missing '}'\");\n }\n return pos({\n type: 'keyframes',\n name: name,\n vendor: vendor,\n keyframes: frames\n });\n }\n function atsupports() {\n var pos = position();\n var m = match(/^@supports *([^{]+)/);\n if (!m) {\n return;\n }\n var supports = trim(m[1]);\n if (!open()) {\n return error(\"@supports missing '{'\");\n }\n var style = comments().concat(rules());\n if (!close()) {\n return error(\"@supports missing '}'\");\n }\n return pos({\n type: 'supports',\n supports: supports,\n rules: style\n });\n }\n function athost() {\n var pos = position();\n var m = match(/^@host\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(\"@host missing '{'\");\n }\n var style = comments().concat(rules());\n if (!close()) {\n return error(\"@host missing '}'\");\n }\n return pos({\n type: 'host',\n rules: style\n });\n }\n function atmedia() {\n var pos = position();\n var m = match(/^@media *([^{]+)/);\n if (!m) {\n return;\n }\n var media = trim(m[1]);\n if (!open()) {\n return error(\"@media missing '{'\");\n }\n var style = comments().concat(rules());\n if (!close()) {\n return error(\"@media missing '}'\");\n }\n return pos({\n type: 'media',\n media: media,\n rules: style\n });\n }\n function atcustommedia() {\n var pos = position();\n var m = match(/^@custom-media\\s+(--[^\\s]+)\\s*([^{;]+);/);\n if (!m) {\n return;\n }\n return pos({\n type: 'custom-media',\n name: trim(m[1]),\n media: trim(m[2])\n });\n }\n function atpage() {\n var pos = position();\n var m = match(/^@page */);\n if (!m) {\n return;\n }\n var sel = selector() || [];\n if (!open()) {\n return error(\"@page missing '{'\");\n }\n var decls = comments();\n var decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(\"@page missing '}'\");\n }\n return pos({\n type: 'page',\n selectors: sel,\n declarations: decls\n });\n }\n function atdocument() {\n var pos = position();\n var m = match(/^@([-\\w]+)?document *([^{]+)/);\n if (!m) {\n return;\n }\n var vendor = trim(m[1]);\n var doc = trim(m[2]);\n if (!open()) {\n return error(\"@document missing '{'\");\n }\n var style = comments().concat(rules());\n if (!close()) {\n return error(\"@document missing '}'\");\n }\n return pos({\n type: 'document',\n document: doc,\n vendor: vendor,\n rules: style\n });\n }\n function atfontface() {\n var pos = position();\n var m = match(/^@font-face\\s*/);\n if (!m) {\n return;\n }\n if (!open()) {\n return error(\"@font-face missing '{'\");\n }\n var decls = comments();\n var decl;\n while ((decl = declaration())) {\n decls.push(decl);\n decls = decls.concat(comments());\n }\n if (!close()) {\n return error(\"@font-face missing '}'\");\n }\n return pos({\n type: 'font-face',\n declarations: decls\n });\n }\n var atimport = _compileAtrule('import');\n var atcharset = _compileAtrule('charset');\n var atnamespace = _compileAtrule('namespace');\n function _compileAtrule(name) {\n var re = new RegExp('^@' + name + '\\\\s*([^;]+);');\n return function () {\n var pos = position();\n var m = match(re);\n if (!m) {\n return;\n }\n var ret = { type: name };\n ret[name] = m[1].trim();\n return pos(ret);\n };\n }\n function atrule() {\n if (css[0] !== '@') {\n return;\n }\n return (atkeyframes() ||\n atmedia() ||\n atcustommedia() ||\n atsupports() ||\n atimport() ||\n atcharset() ||\n atnamespace() ||\n atdocument() ||\n atpage() ||\n athost() ||\n atfontface());\n }\n function rule() {\n var pos = position();\n var sel = selector();\n if (!sel) {\n return error('selector missing');\n }\n comments();\n return pos({\n type: 'rule',\n selectors: sel,\n declarations: declarations()\n });\n }\n return addParent(stylesheet());\n}\nfunction trim(str) {\n return str ? str.replace(/^\\s+|\\s+$/g, '') : '';\n}\nfunction addParent(obj, parent) {\n var isNode = obj && typeof obj.type === 'string';\n var childParent = isNode ? obj : parent;\n for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {\n var k = _a[_i];\n var value = obj[k];\n if (Array.isArray(value)) {\n value.forEach(function (v) {\n addParent(v, childParent);\n });\n }\n else if (value && typeof value === 'object') {\n addParent(value, childParent);\n }\n }\n if (isNode) {\n Object.defineProperty(obj, 'parent', {\n configurable: true,\n writable: true,\n enumerable: false,\n value: parent || null\n });\n }\n return obj;\n}\n\nvar tagMap = {\n script: 'noscript',\n altglyph: 'altGlyph',\n altglyphdef: 'altGlyphDef',\n altglyphitem: 'altGlyphItem',\n animatecolor: 'animateColor',\n animatemotion: 'animateMotion',\n animatetransform: 'animateTransform',\n clippath: 'clipPath',\n feblend: 'feBlend',\n fecolormatrix: 'feColorMatrix',\n fecomponenttransfer: 'feComponentTransfer',\n fecomposite: 'feComposite',\n feconvolvematrix: 'feConvolveMatrix',\n fediffuselighting: 'feDiffuseLighting',\n fedisplacementmap: 'feDisplacementMap',\n fedistantlight: 'feDistantLight',\n fedropshadow: 'feDropShadow',\n feflood: 'feFlood',\n fefunca: 'feFuncA',\n fefuncb: 'feFuncB',\n fefuncg: 'feFuncG',\n fefuncr: 'feFuncR',\n fegaussianblur: 'feGaussianBlur',\n feimage: 'feImage',\n femerge: 'feMerge',\n femergenode: 'feMergeNode',\n femorphology: 'feMorphology',\n feoffset: 'feOffset',\n fepointlight: 'fePointLight',\n fespecularlighting: 'feSpecularLighting',\n fespotlight: 'feSpotLight',\n fetile: 'feTile',\n feturbulence: 'feTurbulence',\n foreignobject: 'foreignObject',\n glyphref: 'glyphRef',\n lineargradient: 'linearGradient',\n radialgradient: 'radialGradient'\n};\nfunction getTagName(n) {\n var tagName = tagMap[n.tagName] ? tagMap[n.tagName] : n.tagName;\n if (tagName === 'link' && n.attributes._cssText) {\n tagName = 'style';\n }\n return tagName;\n}\nfunction escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\nvar HOVER_SELECTOR = /([^\\\\]):hover/;\nvar HOVER_SELECTOR_GLOBAL = new RegExp(HOVER_SELECTOR.source, 'g');\nfunction addHoverClass(cssText, cache) {\n var cachedStyle = cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.get(cssText);\n if (cachedStyle)\n return cachedStyle;\n var ast = parse(cssText, {\n silent: true\n });\n if (!ast.stylesheet) {\n return cssText;\n }\n var selectors = [];\n ast.stylesheet.rules.forEach(function (rule) {\n if ('selectors' in rule) {\n (rule.selectors || []).forEach(function (selector) {\n if (HOVER_SELECTOR.test(selector)) {\n selectors.push(selector);\n }\n });\n }\n });\n if (selectors.length === 0) {\n return cssText;\n }\n var selectorMatcher = new RegExp(selectors\n .filter(function (selector, index) { return selectors.indexOf(selector) === index; })\n .sort(function (a, b) { return b.length - a.length; })\n .map(function (selector) {\n return escapeRegExp(selector);\n })\n .join('|'), 'g');\n var result = cssText.replace(selectorMatcher, function (selector) {\n var newSelector = selector.replace(HOVER_SELECTOR_GLOBAL, '$1.\\\\:hover');\n return selector + \", \" + newSelector;\n });\n cache === null || cache === void 0 ? void 0 : cache.stylesWithHoverClass.set(cssText, result);\n return result;\n}\nfunction createCache() {\n var stylesWithHoverClass = new Map();\n return {\n stylesWithHoverClass: stylesWithHoverClass\n };\n}\nfunction buildNode(n, options) {\n var doc = options.doc, hackCss = options.hackCss, cache = options.cache;\n switch (n.type) {\n case NodeType.Document:\n return doc.implementation.createDocument(null, '', null);\n case NodeType.DocumentType:\n return doc.implementation.createDocumentType(n.name || 'html', n.publicId, n.systemId);\n case NodeType.Element:\n var tagName = getTagName(n);\n var node_1;\n if (n.isSVG) {\n node_1 = doc.createElementNS('http://www.w3.org/2000/svg', tagName);\n }\n else {\n node_1 = doc.createElement(tagName);\n }\n var _loop_1 = function (name_1) {\n if (!n.attributes.hasOwnProperty(name_1)) {\n return \"continue\";\n }\n var value = n.attributes[name_1];\n if (tagName === 'option' && name_1 === 'selected' && value === false) {\n return \"continue\";\n }\n value =\n typeof value === 'boolean' || typeof value === 'number' ? '' : value;\n if (!name_1.startsWith('rr_')) {\n var isTextarea = tagName === 'textarea' && name_1 === 'value';\n var isRemoteOrDynamicCss = tagName === 'style' && name_1 === '_cssText';\n if (isRemoteOrDynamicCss && hackCss) {\n value = addHoverClass(value, cache);\n }\n if (isTextarea || isRemoteOrDynamicCss) {\n var child = doc.createTextNode(value);\n for (var _i = 0, _a = Array.from(node_1.childNodes); _i < _a.length; _i++) {\n var c = _a[_i];\n if (c.nodeType === node_1.TEXT_NODE) {\n node_1.removeChild(c);\n }\n }\n node_1.appendChild(child);\n return \"continue\";\n }\n try {\n if (n.isSVG && name_1 === 'xlink:href') {\n node_1.setAttributeNS('http://www.w3.org/1999/xlink', name_1, value);\n }\n else if (name_1 === 'onload' ||\n name_1 === 'onclick' ||\n name_1.substring(0, 7) === 'onmouse') {\n node_1.setAttribute('_' + name_1, value);\n }\n else if (tagName === 'meta' &&\n n.attributes['http-equiv'] === 'Content-Security-Policy' &&\n name_1 === 'content') {\n node_1.setAttribute('csp-content', value);\n return \"continue\";\n }\n else if (tagName === 'link' &&\n n.attributes.rel === 'preload' &&\n n.attributes.as === 'script') {\n }\n else if (tagName === 'link' &&\n n.attributes.rel === 'prefetch' &&\n typeof n.attributes.href === 'string' &&\n n.attributes.href.endsWith('.js')) {\n }\n else if (tagName === 'img' &&\n n.attributes.srcset &&\n n.attributes.rr_dataURL) {\n node_1.setAttribute('rrweb-original-srcset', n.attributes.srcset);\n }\n else {\n node_1.setAttribute(name_1, value);\n }\n }\n catch (error) {\n }\n }\n else {\n if (tagName === 'canvas' && name_1 === 'rr_dataURL') {\n var image_1 = document.createElement('img');\n image_1.src = value;\n image_1.onload = function () {\n var ctx = node_1.getContext('2d');\n if (ctx) {\n ctx.drawImage(image_1, 0, 0, image_1.width, image_1.height);\n }\n };\n }\n else if (tagName === 'img' && name_1 === 'rr_dataURL') {\n var image = node_1;\n if (!image.currentSrc.startsWith('data:')) {\n image.setAttribute('rrweb-original-src', n.attributes.src);\n image.src = value;\n }\n }\n if (name_1 === 'rr_width') {\n node_1.style.width = value;\n }\n else if (name_1 === 'rr_height') {\n node_1.style.height = value;\n }\n else if (name_1 === 'rr_mediaCurrentTime') {\n node_1.currentTime = n.attributes\n .rr_mediaCurrentTime;\n }\n else if (name_1 === 'rr_mediaState') {\n switch (value) {\n case 'played':\n node_1\n .play()[\"catch\"](function (e) { return console.warn('media playback error', e); });\n break;\n case 'paused':\n node_1.pause();\n break;\n }\n }\n }\n };\n for (var name_1 in n.attributes) {\n _loop_1(name_1);\n }\n if (n.isShadowHost) {\n if (!node_1.shadowRoot) {\n node_1.attachShadow({ mode: 'open' });\n }\n else {\n while (node_1.shadowRoot.firstChild) {\n node_1.shadowRoot.removeChild(node_1.shadowRoot.firstChild);\n }\n }\n }\n return node_1;\n case NodeType.Text:\n return doc.createTextNode(n.isStyle && hackCss\n ? addHoverClass(n.textContent, cache)\n : n.textContent);\n case NodeType.CDATA:\n return doc.createCDATASection(n.textContent);\n case NodeType.Comment:\n return doc.createComment(n.textContent);\n default:\n return null;\n }\n}\nfunction buildNodeWithSN(n, options) {\n var doc = options.doc, map = options.map, _a = options.skipChild, skipChild = _a === void 0 ? false : _a, _b = options.hackCss, hackCss = _b === void 0 ? true : _b, afterAppend = options.afterAppend, cache = options.cache;\n var node = buildNode(n, { doc: doc, hackCss: hackCss, cache: cache });\n if (!node) {\n return null;\n }\n if (n.rootId) {\n console.assert(map[n.rootId] === doc, 'Target document should has the same root id.');\n }\n if (n.type === NodeType.Document) {\n doc.close();\n doc.open();\n if (n.compatMode === 'BackCompat' &&\n n.childNodes &&\n n.childNodes[0].type !== NodeType.DocumentType) {\n if (n.childNodes[0].type === NodeType.Element &&\n 'xmlns' in n.childNodes[0].attributes &&\n n.childNodes[0].attributes.xmlns === 'http://www.w3.org/1999/xhtml') {\n doc.write('<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"\">');\n }\n else {\n doc.write('<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"\">');\n }\n }\n node = doc;\n }\n node.__sn = n;\n map[n.id] = node;\n if ((n.type === NodeType.Document || n.type === NodeType.Element) &&\n !skipChild) {\n for (var _i = 0, _c = n.childNodes; _i < _c.length; _i++) {\n var childN = _c[_i];\n var childNode = buildNodeWithSN(childN, {\n doc: doc,\n map: map,\n skipChild: false,\n hackCss: hackCss,\n afterAppend: afterAppend,\n cache: cache\n });\n if (!childNode) {\n console.warn('Failed to rebuild', childN);\n continue;\n }\n if (childN.isShadow && isElement(node) && node.shadowRoot) {\n node.shadowRoot.appendChild(childNode);\n }\n else {\n node.appendChild(childNode);\n }\n if (afterAppend) {\n afterAppend(childNode);\n }\n }\n }\n return node;\n}\nfunction visit(idNodeMap, onVisit) {\n function walk(node) {\n onVisit(node);\n }\n for (var key in idNodeMap) {\n if (idNodeMap[key]) {\n walk(idNodeMap[key]);\n }\n }\n}\nfunction handleScroll(node) {\n var n = node.__sn;\n if (n.type !== NodeType.Element) {\n return;\n }\n var el = node;\n for (var name_2 in n.attributes) {\n if (!(n.attributes.hasOwnProperty(name_2) && name_2.startsWith('rr_'))) {\n continue;\n }\n var value = n.attributes[name_2];\n if (name_2 === 'rr_scrollLeft') {\n el.scrollLeft = value;\n }\n if (name_2 === 'rr_scrollTop') {\n el.scrollTop = value;\n }\n }\n}\nfunction rebuild(n, options) {\n var doc = options.doc, onVisit = options.onVisit, _a = options.hackCss, hackCss = _a === void 0 ? true : _a, afterAppend = options.afterAppend, cache = options.cache;\n var idNodeMap = {};\n var node = buildNodeWithSN(n, {\n doc: doc,\n map: idNodeMap,\n skipChild: false,\n hackCss: hackCss,\n afterAppend: afterAppend,\n cache: cache\n });\n visit(idNodeMap, function (visitedNode) {\n if (onVisit) {\n onVisit(visitedNode);\n }\n handleScroll(visitedNode);\n });\n return [node, idNodeMap];\n}\n\nexport { IGNORED_NODE, NodeType, addHoverClass, buildNodeWithSN, createCache, is2DCanvasBlank, isElement, isShadowRoot, maskInputValue, needMaskingText, rebuild, serializeNodeWithId, snapshot, transformAttribute };\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nfunction __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\n\nexport { __assign, __read, __rest, __spreadArray, __values };\n","var EventType;\n(function (EventType) {\n EventType[EventType[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType[EventType[\"Load\"] = 1] = \"Load\";\n EventType[EventType[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType[EventType[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType[EventType[\"Meta\"] = 4] = \"Meta\";\n EventType[EventType[\"Custom\"] = 5] = \"Custom\";\n EventType[EventType[\"Plugin\"] = 6] = \"Plugin\";\n})(EventType || (EventType = {}));\nvar IncrementalSource;\n(function (IncrementalSource) {\n IncrementalSource[IncrementalSource[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource[IncrementalSource[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource[IncrementalSource[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource[IncrementalSource[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource[IncrementalSource[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource[IncrementalSource[\"Input\"] = 5] = \"Input\";\n IncrementalSource[IncrementalSource[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource[IncrementalSource[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource[IncrementalSource[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource[IncrementalSource[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource[IncrementalSource[\"Font\"] = 10] = \"Font\";\n IncrementalSource[IncrementalSource[\"Log\"] = 11] = \"Log\";\n IncrementalSource[IncrementalSource[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource[IncrementalSource[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n})(IncrementalSource || (IncrementalSource = {}));\nvar MouseInteractions;\n(function (MouseInteractions) {\n MouseInteractions[MouseInteractions[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions[MouseInteractions[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions[MouseInteractions[\"Click\"] = 2] = \"Click\";\n MouseInteractions[MouseInteractions[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions[MouseInteractions[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions[MouseInteractions[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions[MouseInteractions[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions[MouseInteractions[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions[MouseInteractions[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions[MouseInteractions[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions[MouseInteractions[\"TouchCancel\"] = 10] = \"TouchCancel\";\n})(MouseInteractions || (MouseInteractions = {}));\nvar CanvasContext;\n(function (CanvasContext) {\n CanvasContext[CanvasContext[\"2D\"] = 0] = \"2D\";\n CanvasContext[CanvasContext[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext[CanvasContext[\"WebGL2\"] = 2] = \"WebGL2\";\n})(CanvasContext || (CanvasContext = {}));\nvar MediaInteractions;\n(function (MediaInteractions) {\n MediaInteractions[MediaInteractions[\"Play\"] = 0] = \"Play\";\n MediaInteractions[MediaInteractions[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions[MediaInteractions[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions[MediaInteractions[\"VolumeChange\"] = 3] = \"VolumeChange\";\n})(MediaInteractions || (MediaInteractions = {}));\nvar ReplayerEvents;\n(function (ReplayerEvents) {\n ReplayerEvents[\"Start\"] = \"start\";\n ReplayerEvents[\"Pause\"] = \"pause\";\n ReplayerEvents[\"Resume\"] = \"resume\";\n ReplayerEvents[\"Resize\"] = \"resize\";\n ReplayerEvents[\"Finish\"] = \"finish\";\n ReplayerEvents[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents[\"EventCast\"] = \"event-cast\";\n ReplayerEvents[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents[\"Flush\"] = \"flush\";\n ReplayerEvents[\"StateChange\"] = \"state-change\";\n ReplayerEvents[\"PlayBack\"] = \"play-back\";\n})(ReplayerEvents || (ReplayerEvents = {}));\n\nexport { CanvasContext, EventType, IncrementalSource, MediaInteractions, MouseInteractions, ReplayerEvents };\n","import { __values } from '../ext/tslib/tslib.es6.js';\nimport { IncrementalSource } from './types.js';\nimport { IGNORED_NODE, isShadowRoot, NodeType } from '../../rrweb-snapshot/es/rrweb-snapshot.js';\n\nfunction on(type, fn, target) {\n if (target === void 0) { target = document; }\n var options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return function () { return target.removeEventListener(type, fn, options); };\n}\nfunction createMirror() {\n return {\n map: {},\n getId: function (n) {\n if (!n || !n.__sn) {\n return -1;\n }\n return n.__sn.id;\n },\n getNode: function (id) {\n return this.map[id] || null;\n },\n removeNodeFromMap: function (n) {\n var _this = this;\n var id = n.__sn && n.__sn.id;\n delete this.map[id];\n if (n.childNodes) {\n n.childNodes.forEach(function (child) {\n return _this.removeNodeFromMap(child);\n });\n }\n },\n has: function (id) {\n return this.map.hasOwnProperty(id);\n },\n reset: function () {\n this.map = {};\n },\n };\n}\nvar DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\n '\\r\\n' +\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n '\\r\\n' +\n 'or you can use record.mirror to access the mirror instance during recording.';\nvar _mirror = {\n map: {},\n getId: function () {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode: function () {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap: function () {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has: function () {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset: function () {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n};\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get: function (target, prop, receiver) {\n if (prop === 'map') {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n}\nfunction throttle(func, wait, options) {\n if (options === void 0) { options = {}; }\n var timeout = null;\n var previous = 0;\n return function (arg) {\n var now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n var remaining = wait - (now - previous);\n var context = this;\n var args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n }\n else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(function () {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win) {\n if (win === void 0) { win = window; }\n var original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(target, key, isRevoked\n ? d\n : {\n set: function (value) {\n var _this = this;\n setTimeout(function () {\n d.set.call(_this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n },\n });\n return function () { return hookSetter(target, key, original || {}, true); };\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return function () { };\n }\n var original_1 = source[name];\n var wrapped = replacement(original_1);\n if (typeof wrapped === 'function') {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original_1,\n },\n });\n }\n source[name] = wrapped;\n return function () {\n source[name] = original_1;\n };\n }\n catch (_a) {\n return function () { };\n }\n}\nfunction getWindowHeight() {\n return (window.innerHeight ||\n (document.documentElement && document.documentElement.clientHeight) ||\n (document.body && document.body.clientHeight));\n}\nfunction getWindowWidth() {\n return (window.innerWidth ||\n (document.documentElement && document.documentElement.clientWidth) ||\n (document.body && document.body.clientWidth));\n}\nfunction isBlocked(node, blockClass) {\n if (!node) {\n return false;\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n var needBlock_1 = false;\n if (typeof blockClass === 'string') {\n if (node.closest !== undefined) {\n return node.closest('.' + blockClass) !== null;\n }\n else {\n needBlock_1 = node.classList.contains(blockClass);\n }\n }\n else {\n node.classList.forEach(function (className) {\n if (blockClass.test(className)) {\n needBlock_1 = true;\n }\n });\n }\n return needBlock_1 || isBlocked(node.parentNode, blockClass);\n }\n if (node.nodeType === node.TEXT_NODE) {\n return isBlocked(node.parentNode, blockClass);\n }\n return isBlocked(node.parentNode, blockClass);\n}\nfunction isIgnored(n) {\n if ('__sn' in n) {\n return n.__sn.id === IGNORED_NODE;\n }\n return false;\n}\nfunction isAncestorRemoved(target, mirror) {\n if (isShadowRoot(target)) {\n return false;\n }\n var id = mirror.getId(target);\n if (!mirror.has(id)) {\n return true;\n }\n if (target.parentNode &&\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror);\n}\nfunction isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win) {\n if (win === void 0) { win = window; }\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype\n .forEach;\n }\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype\n .forEach;\n }\n if (!Node.prototype.contains) {\n Node.prototype.contains = function contains(node) {\n if (!(0 in arguments)) {\n throw new TypeError('1 argument is required');\n }\n do {\n if (this === node) {\n return true;\n }\n } while ((node = node && node.parentNode));\n return false;\n };\n }\n}\nvar TreeIndex = (function () {\n function TreeIndex() {\n this.reset();\n }\n TreeIndex.prototype.add = function (mutation) {\n var parentTreeNode = this.indexes.get(mutation.parentId);\n var treeNode = {\n id: mutation.node.id,\n mutation: mutation,\n children: [],\n texts: [],\n attributes: [],\n };\n if (!parentTreeNode) {\n this.tree[treeNode.id] = treeNode;\n }\n else {\n treeNode.parent = parentTreeNode;\n parentTreeNode.children[treeNode.id] = treeNode;\n }\n this.indexes.set(treeNode.id, treeNode);\n };\n TreeIndex.prototype.remove = function (mutation, mirror) {\n var _this = this;\n var parentTreeNode = this.indexes.get(mutation.parentId);\n var treeNode = this.indexes.get(mutation.id);\n var deepRemoveFromMirror = function (id) {\n _this.removeIdSet.add(id);\n var node = mirror.getNode(id);\n node === null || node === void 0 ? void 0 : node.childNodes.forEach(function (childNode) {\n if ('__sn' in childNode) {\n deepRemoveFromMirror(childNode.__sn.id);\n }\n });\n };\n var deepRemoveFromTreeIndex = function (node) {\n _this.removeIdSet.add(node.id);\n Object.values(node.children).forEach(function (n) { return deepRemoveFromTreeIndex(n); });\n var _treeNode = _this.indexes.get(node.id);\n if (_treeNode) {\n var _parentTreeNode = _treeNode.parent;\n if (_parentTreeNode) {\n delete _treeNode.parent;\n delete _parentTreeNode.children[_treeNode.id];\n _this.indexes.delete(mutation.id);\n }\n }\n };\n if (!treeNode) {\n this.removeNodeMutations.push(mutation);\n deepRemoveFromMirror(mutation.id);\n }\n else if (!parentTreeNode) {\n delete this.tree[treeNode.id];\n this.indexes.delete(treeNode.id);\n deepRemoveFromTreeIndex(treeNode);\n }\n else {\n delete treeNode.parent;\n delete parentTreeNode.children[treeNode.id];\n this.indexes.delete(mutation.id);\n deepRemoveFromTreeIndex(treeNode);\n }\n };\n TreeIndex.prototype.text = function (mutation) {\n var treeNode = this.indexes.get(mutation.id);\n if (treeNode) {\n treeNode.texts.push(mutation);\n }\n else {\n this.textMutations.push(mutation);\n }\n };\n TreeIndex.prototype.attribute = function (mutation) {\n var treeNode = this.indexes.get(mutation.id);\n if (treeNode) {\n treeNode.attributes.push(mutation);\n }\n else {\n this.attributeMutations.push(mutation);\n }\n };\n TreeIndex.prototype.scroll = function (d) {\n this.scrollMap.set(d.id, d);\n };\n TreeIndex.prototype.input = function (d) {\n this.inputMap.set(d.id, d);\n };\n TreeIndex.prototype.flush = function () {\n var e_1, _a, e_2, _b;\n var _this = this;\n var _c = this, tree = _c.tree, removeNodeMutations = _c.removeNodeMutations, textMutations = _c.textMutations, attributeMutations = _c.attributeMutations;\n var batchMutationData = {\n source: IncrementalSource.Mutation,\n removes: removeNodeMutations,\n texts: textMutations,\n attributes: attributeMutations,\n adds: [],\n };\n var walk = function (treeNode, removed) {\n if (removed) {\n _this.removeIdSet.add(treeNode.id);\n }\n batchMutationData.texts = batchMutationData.texts\n .concat(removed ? [] : treeNode.texts)\n .filter(function (m) { return !_this.removeIdSet.has(m.id); });\n batchMutationData.attributes = batchMutationData.attributes\n .concat(removed ? [] : treeNode.attributes)\n .filter(function (m) { return !_this.removeIdSet.has(m.id); });\n if (!_this.removeIdSet.has(treeNode.id) &&\n !_this.removeIdSet.has(treeNode.mutation.parentId) &&\n !removed) {\n batchMutationData.adds.push(treeNode.mutation);\n if (treeNode.children) {\n Object.values(treeNode.children).forEach(function (n) { return walk(n, false); });\n }\n }\n else {\n Object.values(treeNode.children).forEach(function (n) { return walk(n, true); });\n }\n };\n Object.values(tree).forEach(function (n) { return walk(n, false); });\n try {\n for (var _d = __values(this.scrollMap.keys()), _e = _d.next(); !_e.done; _e = _d.next()) {\n var id = _e.value;\n if (this.removeIdSet.has(id)) {\n this.scrollMap.delete(id);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_e && !_e.done && (_a = _d.return)) _a.call(_d);\n }\n finally { if (e_1) throw e_1.error; }\n }\n try {\n for (var _f = __values(this.inputMap.keys()), _g = _f.next(); !_g.done; _g = _f.next()) {\n var id = _g.value;\n if (this.removeIdSet.has(id)) {\n this.inputMap.delete(id);\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_g && !_g.done && (_b = _f.return)) _b.call(_f);\n }\n finally { if (e_2) throw e_2.error; }\n }\n var scrollMap = new Map(this.scrollMap);\n var inputMap = new Map(this.inputMap);\n this.reset();\n return {\n mutationData: batchMutationData,\n scrollMap: scrollMap,\n inputMap: inputMap,\n };\n };\n TreeIndex.prototype.reset = function () {\n this.tree = [];\n this.indexes = new Map();\n this.removeNodeMutations = [];\n this.textMutations = [];\n this.attributeMutations = [];\n this.removeIdSet = new Set();\n this.scrollMap = new Map();\n this.inputMap = new Map();\n };\n TreeIndex.prototype.idRemoved = function (id) {\n return this.removeIdSet.has(id);\n };\n return TreeIndex;\n}());\nfunction queueToResolveTrees(queue) {\n var e_3, _a;\n var queueNodeMap = {};\n var putIntoMap = function (m, parent) {\n var nodeInTree = {\n value: m,\n parent: parent,\n children: [],\n };\n queueNodeMap[m.node.id] = nodeInTree;\n return nodeInTree;\n };\n var queueNodeTrees = [];\n try {\n for (var queue_1 = __values(queue), queue_1_1 = queue_1.next(); !queue_1_1.done; queue_1_1 = queue_1.next()) {\n var mutation = queue_1_1.value;\n var nextId = mutation.nextId, parentId = mutation.parentId;\n if (nextId && nextId in queueNodeMap) {\n var nextInTree = queueNodeMap[nextId];\n if (nextInTree.parent) {\n var idx = nextInTree.parent.children.indexOf(nextInTree);\n nextInTree.parent.children.splice(idx, 0, putIntoMap(mutation, nextInTree.parent));\n }\n else {\n var idx = queueNodeTrees.indexOf(nextInTree);\n queueNodeTrees.splice(idx, 0, putIntoMap(mutation, null));\n }\n continue;\n }\n if (parentId in queueNodeMap) {\n var parentInTree = queueNodeMap[parentId];\n parentInTree.children.push(putIntoMap(mutation, parentInTree));\n continue;\n }\n queueNodeTrees.push(putIntoMap(mutation, null));\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (queue_1_1 && !queue_1_1.done && (_a = queue_1.return)) _a.call(queue_1);\n }\n finally { if (e_3) throw e_3.error; }\n }\n return queueNodeTrees;\n}\nfunction iterateResolveTree(tree, cb) {\n cb(tree.value);\n for (var i = tree.children.length - 1; i >= 0; i--) {\n iterateResolveTree(tree.children[i], cb);\n }\n}\nfunction isIframeINode(node) {\n if ('__sn' in node) {\n return (node.__sn.type === NodeType.Element && node.__sn.tagName === 'iframe');\n }\n return false;\n}\nfunction getBaseDimension(node, rootIframe) {\n var _a, _b;\n var frameElement = (_b = (_a = node.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) === null || _b === void 0 ? void 0 : _b.frameElement;\n if (!frameElement || frameElement === rootIframe) {\n return {\n x: 0,\n y: 0,\n relativeScale: 1,\n absoluteScale: 1,\n };\n }\n var frameDimension = frameElement.getBoundingClientRect();\n var frameBaseDimension = getBaseDimension(frameElement, rootIframe);\n var relativeScale = frameDimension.height / frameElement.clientHeight;\n return {\n x: frameDimension.x * frameBaseDimension.relativeScale +\n frameBaseDimension.x,\n y: frameDimension.y * frameBaseDimension.relativeScale +\n frameBaseDimension.y,\n relativeScale: relativeScale,\n absoluteScale: frameBaseDimension.absoluteScale * relativeScale,\n };\n}\nfunction hasShadowRoot(n) {\n return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);\n}\n\nexport { TreeIndex, _mirror, createMirror, getBaseDimension, getWindowHeight, getWindowWidth, hasShadowRoot, hookSetter, isAncestorRemoved, isBlocked, isIframeINode, isIgnored, isTouchEvent, iterateResolveTree, on, patch, polyfill, queueToResolveTrees, throttle };\n","import { __values } from '../../ext/tslib/tslib.es6.js';\nimport { isShadowRoot, maskInputValue, transformAttribute, needMaskingText, IGNORED_NODE, serializeNodeWithId } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { isIgnored, isBlocked, isAncestorRemoved, isIframeINode, hasShadowRoot } from '../utils.js';\n\nfunction isNodeInLinkedList(n) {\n return '__ln' in n;\n}\nvar DoubleLinkedList = (function () {\n function DoubleLinkedList() {\n this.length = 0;\n this.head = null;\n }\n DoubleLinkedList.prototype.get = function (position) {\n if (position >= this.length) {\n throw new Error('Position outside of list range');\n }\n var current = this.head;\n for (var index = 0; index < position; index++) {\n current = (current === null || current === void 0 ? void 0 : current.next) || null;\n }\n return current;\n };\n DoubleLinkedList.prototype.addNode = function (n) {\n var node = {\n value: n,\n previous: null,\n next: null,\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n var current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n }\n else if (n.nextSibling &&\n isNodeInLinkedList(n.nextSibling) &&\n n.nextSibling.__ln.previous) {\n var current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n }\n else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n this.length++;\n };\n DoubleLinkedList.prototype.removeNode = function (n) {\n var current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n }\n }\n else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n };\n return DoubleLinkedList;\n}());\nvar moveKey = function (id, parentId) { return \"\".concat(id, \"@\").concat(parentId); };\nfunction isINode(n) {\n return '__sn' in n;\n}\nvar MutationBuffer = (function () {\n function MutationBuffer() {\n var _this = this;\n this.frozen = false;\n this.locked = false;\n this.texts = [];\n this.attributes = [];\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.processMutations = function (mutations) {\n mutations.forEach(_this.processMutation);\n _this.emit();\n };\n this.emit = function () {\n var e_1, _a, e_2, _b;\n if (_this.frozen || _this.locked) {\n return;\n }\n var adds = [];\n var addList = new DoubleLinkedList();\n var getNextId = function (n) {\n var ns = n;\n var nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && _this.mirror.getId(ns);\n }\n return nextId;\n };\n var pushAdd = function (n) {\n var _a, _b, _c, _d, _e;\n var shadowHost = n.getRootNode\n ? (_a = n.getRootNode()) === null || _a === void 0 ? void 0 : _a.host\n : null;\n var rootShadowHost = shadowHost;\n while ((_c = (_b = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _b === void 0 ? void 0 : _b.call(rootShadowHost)) === null || _c === void 0 ? void 0 : _c.host)\n rootShadowHost =\n ((_e = (_d = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _d === void 0 ? void 0 : _d.call(rootShadowHost)) === null || _e === void 0 ? void 0 : _e.host) ||\n null;\n var notInDoc = !_this.doc.contains(n) &&\n (rootShadowHost === null || !_this.doc.contains(rootShadowHost));\n if (!n.parentNode || notInDoc) {\n return;\n }\n var parentId = isShadowRoot(n.parentNode)\n ? _this.mirror.getId(shadowHost)\n : _this.mirror.getId(n.parentNode);\n var nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n var sn = serializeNodeWithId(n, {\n doc: _this.doc,\n map: _this.mirror.map,\n blockClass: _this.blockClass,\n blockSelector: _this.blockSelector,\n maskTextClass: _this.maskTextClass,\n maskTextSelector: _this.maskTextSelector,\n skipChild: true,\n inlineStylesheet: _this.inlineStylesheet,\n maskInputOptions: _this.maskInputOptions,\n maskTextFn: _this.maskTextFn,\n maskInputFn: _this.maskInputFn,\n slimDOMOptions: _this.slimDOMOptions,\n recordCanvas: _this.recordCanvas,\n inlineImages: _this.inlineImages,\n onSerialize: function (currentN) {\n if (isIframeINode(currentN)) {\n _this.iframeManager.addIframe(currentN);\n }\n if (hasShadowRoot(n)) {\n _this.shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: function (iframe, childSn) {\n _this.iframeManager.attachIframe(iframe, childSn);\n _this.shadowDomManager.observeAttachShadow(iframe);\n },\n });\n if (sn) {\n adds.push({\n parentId: parentId,\n nextId: nextId,\n node: sn,\n });\n }\n };\n while (_this.mapRemoves.length) {\n _this.mirror.removeNodeFromMap(_this.mapRemoves.shift());\n }\n try {\n for (var _c = __values(_this.movedSet), _d = _c.next(); !_d.done; _d = _c.next()) {\n var n = _d.value;\n if (isParentRemoved(_this.removes, n, _this.mirror) &&\n !_this.movedSet.has(n.parentNode)) {\n continue;\n }\n pushAdd(n);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n }\n finally { if (e_1) throw e_1.error; }\n }\n try {\n for (var _e = __values(_this.addedSet), _f = _e.next(); !_f.done; _f = _e.next()) {\n var n = _f.value;\n if (!isAncestorInSet(_this.droppedSet, n) &&\n !isParentRemoved(_this.removes, n, _this.mirror)) {\n pushAdd(n);\n }\n else if (isAncestorInSet(_this.movedSet, n)) {\n pushAdd(n);\n }\n else {\n _this.droppedSet.add(n);\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n }\n finally { if (e_2) throw e_2.error; }\n }\n var candidate = null;\n while (addList.length) {\n var node = null;\n if (candidate) {\n var parentId = _this.mirror.getId(candidate.value.parentNode);\n var nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n for (var index = addList.length - 1; index >= 0; index--) {\n var _node = addList.get(index);\n if (_node) {\n var parentId = _this.mirror.getId(_node.value.parentNode);\n var nextId = getNextId(_node.value);\n if (parentId !== -1 && nextId !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n var payload = {\n texts: _this.texts\n .map(function (text) { return ({\n id: _this.mirror.getId(text.node),\n value: text.value,\n }); })\n .filter(function (text) { return _this.mirror.has(text.id); }),\n attributes: _this.attributes\n .map(function (attribute) { return ({\n id: _this.mirror.getId(attribute.node),\n attributes: attribute.attributes,\n }); })\n .filter(function (attribute) { return _this.mirror.has(attribute.id); }),\n removes: _this.removes,\n adds: adds,\n };\n if (!payload.texts.length &&\n !payload.attributes.length &&\n !payload.removes.length &&\n !payload.adds.length) {\n return;\n }\n _this.texts = [];\n _this.attributes = [];\n _this.removes = [];\n _this.addedSet = new Set();\n _this.movedSet = new Set();\n _this.droppedSet = new Set();\n _this.movedMap = {};\n _this.mutationCb(payload);\n };\n this.processMutation = function (m) {\n var e_3, _a, e_4, _b;\n if (isIgnored(m.target)) {\n return;\n }\n switch (m.type) {\n case 'characterData': {\n var value = m.target.textContent;\n if (!isBlocked(m.target, _this.blockClass) && value !== m.oldValue) {\n _this.texts.push({\n value: needMaskingText(m.target, _this.maskTextClass, _this.maskTextSelector) && value\n ? _this.maskTextFn\n ? _this.maskTextFn(value)\n : value.replace(/[\\S]/g, '*')\n : value,\n node: m.target,\n });\n }\n break;\n }\n case 'attributes': {\n var target = m.target;\n var value = m.target.getAttribute(m.attributeName);\n if (m.attributeName === 'value') {\n value = maskInputValue({\n maskInputOptions: _this.maskInputOptions,\n tagName: m.target.tagName,\n type: m.target.getAttribute('type'),\n value: value,\n maskInputFn: _this.maskInputFn,\n });\n }\n if (isBlocked(m.target, _this.blockClass) || value === m.oldValue) {\n return;\n }\n var item = _this.attributes.find(function (a) { return a.node === m.target; });\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n };\n _this.attributes.push(item);\n }\n if (m.attributeName === 'style') {\n var old = _this.doc.createElement('span');\n if (m.oldValue) {\n old.setAttribute('style', m.oldValue);\n }\n if (item.attributes.style === undefined ||\n item.attributes.style === null) {\n item.attributes.style = {};\n }\n var styleObj = item.attributes.style;\n try {\n for (var _c = __values(Array.from(target.style)), _d = _c.next(); !_d.done; _d = _c.next()) {\n var pname = _d.value;\n var newValue = target.style.getPropertyValue(pname);\n var newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) ||\n newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === '') {\n styleObj[pname] = newValue;\n }\n else {\n styleObj[pname] = [newValue, newPriority];\n }\n }\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n }\n finally { if (e_3) throw e_3.error; }\n }\n try {\n for (var _e = __values(Array.from(old.style)), _f = _e.next(); !_f.done; _f = _e.next()) {\n var pname = _f.value;\n if (target.style.getPropertyValue(pname) === '') {\n styleObj[pname] = false;\n }\n }\n }\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\n finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n }\n finally { if (e_4) throw e_4.error; }\n }\n }\n else {\n item.attributes[m.attributeName] = transformAttribute(_this.doc, m.target.tagName, m.attributeName, value);\n }\n break;\n }\n case 'childList': {\n m.addedNodes.forEach(function (n) { return _this.genAdds(n, m.target); });\n m.removedNodes.forEach(function (n) {\n var nodeId = _this.mirror.getId(n);\n var parentId = isShadowRoot(m.target)\n ? _this.mirror.getId(m.target.host)\n : _this.mirror.getId(m.target);\n if (isBlocked(m.target, _this.blockClass) || isIgnored(n)) {\n return;\n }\n if (_this.addedSet.has(n)) {\n deepDelete(_this.addedSet, n);\n _this.droppedSet.add(n);\n }\n else if (_this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, _this.mirror)) ;\n else if (_this.movedSet.has(n) &&\n _this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(_this.movedSet, n);\n }\n else {\n _this.removes.push({\n parentId: parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) ? true : undefined,\n });\n }\n _this.mapRemoves.push(n);\n });\n break;\n }\n }\n };\n this.genAdds = function (n, target) {\n if (target && isBlocked(target, _this.blockClass)) {\n return;\n }\n if (isINode(n)) {\n if (isIgnored(n)) {\n return;\n }\n _this.movedSet.add(n);\n var targetId = null;\n if (target && isINode(target)) {\n targetId = target.__sn.id;\n }\n if (targetId) {\n _this.movedMap[moveKey(n.__sn.id, targetId)] = true;\n }\n }\n else {\n _this.addedSet.add(n);\n _this.droppedSet.delete(n);\n }\n if (!isBlocked(n, _this.blockClass))\n n.childNodes.forEach(function (childN) { return _this.genAdds(childN); });\n };\n }\n MutationBuffer.prototype.init = function (options) {\n var _this = this;\n [\n 'mutationCb',\n 'blockClass',\n 'blockSelector',\n 'maskTextClass',\n 'maskTextSelector',\n 'inlineStylesheet',\n 'maskInputOptions',\n 'maskTextFn',\n 'maskInputFn',\n 'recordCanvas',\n 'inlineImages',\n 'slimDOMOptions',\n 'doc',\n 'mirror',\n 'iframeManager',\n 'shadowDomManager',\n 'canvasManager',\n ].forEach(function (key) {\n _this[key] = options[key];\n });\n };\n MutationBuffer.prototype.freeze = function () {\n this.frozen = true;\n this.canvasManager.freeze();\n };\n MutationBuffer.prototype.unfreeze = function () {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n };\n MutationBuffer.prototype.isFrozen = function () {\n return this.frozen;\n };\n MutationBuffer.prototype.lock = function () {\n this.locked = true;\n this.canvasManager.lock();\n };\n MutationBuffer.prototype.unlock = function () {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n };\n MutationBuffer.prototype.reset = function () {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n };\n return MutationBuffer;\n}());\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n n.childNodes.forEach(function (childN) { return deepDelete(addsSet, childN); });\n}\nfunction isParentRemoved(removes, n, mirror) {\n var parentNode = n.parentNode;\n if (!parentNode) {\n return false;\n }\n var parentId = mirror.getId(parentNode);\n if (removes.some(function (r) { return r.id === parentId; })) {\n return true;\n }\n return isParentRemoved(removes, parentNode, mirror);\n}\nfunction isAncestorInSet(set, n) {\n var parentNode = n.parentNode;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return isAncestorInSet(set, parentNode);\n}\n\nexport default MutationBuffer;\n","import { __read, __values, __spreadArray, __assign } from '../../ext/tslib/tslib.es6.js';\nimport { maskInputValue } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { on, throttle, isTouchEvent, isBlocked, getWindowHeight, getWindowWidth, hookSetter, patch } from '../utils.js';\nimport { IncrementalSource, MouseInteractions } from '../types.js';\nimport MutationBuffer from './mutation.js';\n\nvar mutationBuffers = [];\nvar isCSSGroupingRuleSupported = typeof CSSGroupingRule !== 'undefined';\nvar isCSSMediaRuleSupported = typeof CSSMediaRule !== 'undefined';\nvar isCSSSupportsRuleSupported = typeof CSSSupportsRule !== 'undefined';\nvar isCSSConditionRuleSupported = typeof CSSConditionRule !== 'undefined';\nfunction getEventTarget(event) {\n try {\n if ('composedPath' in event) {\n var path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n }\n else if ('path' in event && event.path.length) {\n return event.path[0];\n }\n return event.target;\n }\n catch (_a) {\n return event.target;\n }\n}\nfunction initMutationObserver(options, rootEl) {\n var _a, _b;\n var mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n var mutationObserverCtor = window.MutationObserver ||\n window.__rrMutationObserver;\n var angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');\n if (angularZoneSymbol &&\n window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n var observer = new mutationObserverCtor(mutationBuffer.processMutations.bind(mutationBuffer));\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n });\n return observer;\n}\nfunction initMoveObserver(_a) {\n var mousemoveCb = _a.mousemoveCb, sampling = _a.sampling, doc = _a.doc, mirror = _a.mirror;\n if (sampling.mousemove === false) {\n return function () { };\n }\n var threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\n var callbackThreshold = typeof sampling.mousemoveCallback === 'number'\n ? sampling.mousemoveCallback\n : 500;\n var positions = [];\n var timeBaseline;\n var wrappedCb = throttle(function (source) {\n var totalOffset = Date.now() - timeBaseline;\n mousemoveCb(positions.map(function (p) {\n p.timeOffset -= totalOffset;\n return p;\n }), source);\n positions = [];\n timeBaseline = null;\n }, callbackThreshold);\n var updatePosition = throttle(function (evt) {\n var target = getEventTarget(evt);\n var _a = isTouchEvent(evt)\n ? evt.changedTouches[0]\n : evt, clientX = _a.clientX, clientY = _a.clientY;\n if (!timeBaseline) {\n timeBaseline = Date.now();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror.getId(target),\n timeOffset: Date.now() - timeBaseline,\n });\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n ? IncrementalSource.Drag\n : evt instanceof MouseEvent\n ? IncrementalSource.MouseMove\n : IncrementalSource.TouchMove);\n }, threshold, {\n trailing: false,\n });\n var handlers = [\n on('mousemove', updatePosition, doc),\n on('touchmove', updatePosition, doc),\n on('drag', updatePosition, doc),\n ];\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\nfunction initMouseInteractionObserver(_a) {\n var mouseInteractionCb = _a.mouseInteractionCb, doc = _a.doc, mirror = _a.mirror, blockClass = _a.blockClass, sampling = _a.sampling;\n if (sampling.mouseInteraction === false) {\n return function () { };\n }\n var disableMap = sampling.mouseInteraction === true ||\n sampling.mouseInteraction === undefined\n ? {}\n : sampling.mouseInteraction;\n var handlers = [];\n var getHandler = function (eventKey) {\n return function (event) {\n var target = getEventTarget(event);\n if (isBlocked(target, blockClass)) {\n return;\n }\n var e = isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n var id = mirror.getId(target);\n var clientX = e.clientX, clientY = e.clientY;\n mouseInteractionCb({\n type: MouseInteractions[eventKey],\n id: id,\n x: clientX,\n y: clientY,\n });\n };\n };\n Object.keys(MouseInteractions)\n .filter(function (key) {\n return Number.isNaN(Number(key)) &&\n !key.endsWith('_Departed') &&\n disableMap[key] !== false;\n })\n .forEach(function (eventKey) {\n var eventName = eventKey.toLowerCase();\n var handler = getHandler(eventKey);\n handlers.push(on(eventName, handler, doc));\n });\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\nfunction initScrollObserver(_a) {\n var scrollCb = _a.scrollCb, doc = _a.doc, mirror = _a.mirror, blockClass = _a.blockClass, sampling = _a.sampling;\n var updatePosition = throttle(function (evt) {\n var target = getEventTarget(evt);\n if (!target || isBlocked(target, blockClass)) {\n return;\n }\n var id = mirror.getId(target);\n if (target === doc) {\n var scrollEl = (doc.scrollingElement || doc.documentElement);\n scrollCb({\n id: id,\n x: scrollEl.scrollLeft,\n y: scrollEl.scrollTop,\n });\n }\n else {\n scrollCb({\n id: id,\n x: target.scrollLeft,\n y: target.scrollTop,\n });\n }\n }, sampling.scroll || 100);\n return on('scroll', updatePosition, doc);\n}\nfunction initViewportResizeObserver(_a) {\n var viewportResizeCb = _a.viewportResizeCb;\n var lastH = -1;\n var lastW = -1;\n var updateDimension = throttle(function () {\n var height = getWindowHeight();\n var width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n viewportResizeCb({\n width: Number(width),\n height: Number(height),\n });\n lastH = height;\n lastW = width;\n }\n }, 200);\n return on('resize', updateDimension, window);\n}\nfunction wrapEventWithUserTriggeredFlag(v, enable) {\n var value = __assign({}, v);\n if (!enable)\n delete value.userTriggered;\n return value;\n}\nvar INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nvar lastInputValueMap = new WeakMap();\nfunction initInputObserver(_a) {\n var inputCb = _a.inputCb, doc = _a.doc, mirror = _a.mirror, blockClass = _a.blockClass, ignoreClass = _a.ignoreClass, maskInputOptions = _a.maskInputOptions, maskInputFn = _a.maskInputFn, sampling = _a.sampling, userTriggeredOnInput = _a.userTriggeredOnInput;\n function eventHandler(event) {\n var target = getEventTarget(event);\n var userTriggered = event.isTrusted;\n if (target && target.tagName === 'OPTION')\n target = target.parentElement;\n if (!target ||\n !target.tagName ||\n INPUT_TAGS.indexOf(target.tagName) < 0 ||\n isBlocked(target, blockClass)) {\n return;\n }\n var type = target.type;\n if (target.classList.contains(ignoreClass)) {\n return;\n }\n var text = target.value;\n var isChecked = false;\n if (type === 'radio' || type === 'checkbox') {\n isChecked = target.checked;\n }\n else if (maskInputOptions[target.tagName.toLowerCase()] ||\n maskInputOptions[type]) {\n text = maskInputValue({\n maskInputOptions: maskInputOptions,\n tagName: target.tagName,\n type: type,\n value: text,\n maskInputFn: maskInputFn,\n });\n }\n cbWithDedup(target, wrapEventWithUserTriggeredFlag({ text: text, isChecked: isChecked, userTriggered: userTriggered }, userTriggeredOnInput));\n var name = target.name;\n if (type === 'radio' && name && isChecked) {\n doc\n .querySelectorAll(\"input[type=\\\"radio\\\"][name=\\\"\".concat(name, \"\\\"]\"))\n .forEach(function (el) {\n if (el !== target) {\n cbWithDedup(el, wrapEventWithUserTriggeredFlag({\n text: el.value,\n isChecked: !isChecked,\n userTriggered: false,\n }, userTriggeredOnInput));\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n var lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue ||\n lastInputValue.text !== v.text ||\n lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n var id = mirror.getId(target);\n inputCb(__assign(__assign({}, v), { id: id }));\n }\n }\n var events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n var handlers = events.map(function (eventName) { return on(eventName, eventHandler, doc); });\n var propertyDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');\n var hookProperties = [\n [HTMLInputElement.prototype, 'value'],\n [HTMLInputElement.prototype, 'checked'],\n [HTMLSelectElement.prototype, 'value'],\n [HTMLTextAreaElement.prototype, 'value'],\n [HTMLSelectElement.prototype, 'selectedIndex'],\n [HTMLOptionElement.prototype, 'selected'],\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push.apply(handlers, __spreadArray([], __read(hookProperties.map(function (p) {\n return hookSetter(p[0], p[1], {\n set: function () {\n eventHandler({ target: this });\n },\n });\n })), false));\n }\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\nfunction getNestedCSSRulePositions(rule) {\n var positions = [];\n function recurse(childRule, pos) {\n if ((isCSSGroupingRuleSupported &&\n childRule.parentRule instanceof CSSGroupingRule) ||\n (isCSSMediaRuleSupported &&\n childRule.parentRule instanceof CSSMediaRule) ||\n (isCSSSupportsRuleSupported &&\n childRule.parentRule instanceof CSSSupportsRule) ||\n (isCSSConditionRuleSupported &&\n childRule.parentRule instanceof CSSConditionRule)) {\n var rules = Array.from(childRule.parentRule.cssRules);\n var index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n else {\n var rules = Array.from(childRule.parentStyleSheet.cssRules);\n var index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction initStyleSheetObserver(_a, _b) {\n var styleSheetRuleCb = _a.styleSheetRuleCb, mirror = _a.mirror;\n var win = _b.win;\n var insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = function (rule, index) {\n var id = mirror.getId(this.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id: id,\n adds: [{ rule: rule, index: index }],\n });\n }\n return insertRule.apply(this, arguments);\n };\n var deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = function (index) {\n var id = mirror.getId(this.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id: id,\n removes: [{ index: index }],\n });\n }\n return deleteRule.apply(this, arguments);\n };\n var supportedNestedCSSRuleTypes = {};\n if (isCSSGroupingRuleSupported) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n }\n else {\n if (isCSSMediaRuleSupported) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (isCSSConditionRuleSupported) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (isCSSSupportsRuleSupported) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n var unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(function (_a) {\n var _b = __read(_a, 2), typeKey = _b[0], type = _b[1];\n unmodifiedFunctions[typeKey] = {\n insertRule: type.prototype.insertRule,\n deleteRule: type.prototype.deleteRule,\n };\n type.prototype.insertRule = function (rule, index) {\n var id = mirror.getId(this.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id: id,\n adds: [\n {\n rule: rule,\n index: __spreadArray(__spreadArray([], __read(getNestedCSSRulePositions(this)), false), [\n index || 0,\n ], false),\n },\n ],\n });\n }\n return unmodifiedFunctions[typeKey].insertRule.apply(this, arguments);\n };\n type.prototype.deleteRule = function (index) {\n var id = mirror.getId(this.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id: id,\n removes: [{ index: __spreadArray(__spreadArray([], __read(getNestedCSSRulePositions(this)), false), [index], false) }],\n });\n }\n return unmodifiedFunctions[typeKey].deleteRule.apply(this, arguments);\n };\n });\n return function () {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n Object.entries(supportedNestedCSSRuleTypes).forEach(function (_a) {\n var _b = __read(_a, 2), typeKey = _b[0], type = _b[1];\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n };\n}\nfunction initStyleDeclarationObserver(_a, _b) {\n var styleDeclarationCb = _a.styleDeclarationCb, mirror = _a.mirror;\n var win = _b.win;\n var setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = function (property, value, priority) {\n var _a, _b;\n var id = mirror.getId((_b = (_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id: id,\n set: {\n property: property,\n value: value,\n priority: priority,\n },\n index: getNestedCSSRulePositions(this.parentRule),\n });\n }\n return setProperty.apply(this, arguments);\n };\n var removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = function (property) {\n var _a, _b;\n var id = mirror.getId((_b = (_a = this.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id: id,\n remove: {\n property: property,\n },\n index: getNestedCSSRulePositions(this.parentRule),\n });\n }\n return removeProperty.apply(this, arguments);\n };\n return function () {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n };\n}\nfunction initMediaInteractionObserver(_a) {\n var mediaInteractionCb = _a.mediaInteractionCb, blockClass = _a.blockClass, mirror = _a.mirror, sampling = _a.sampling;\n var handler = function (type) {\n return throttle(function (event) {\n var target = getEventTarget(event);\n if (!target || isBlocked(target, blockClass)) {\n return;\n }\n var _a = target, currentTime = _a.currentTime, volume = _a.volume, muted = _a.muted;\n mediaInteractionCb({\n type: type,\n id: mirror.getId(target),\n currentTime: currentTime,\n volume: volume,\n muted: muted,\n });\n }, sampling.media || 500);\n };\n var handlers = [\n on('play', handler(0)),\n on('pause', handler(1)),\n on('seeked', handler(2)),\n on('volumechange', handler(3)),\n ];\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\nfunction initFontObserver(_a) {\n var fontCb = _a.fontCb, doc = _a.doc;\n var win = doc.defaultView;\n if (!win) {\n return function () { };\n }\n var handlers = [];\n var fontMap = new WeakMap();\n var originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n var fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family: family,\n buffer: typeof source !== 'string',\n descriptors: descriptors,\n fontSource: typeof source === 'string'\n ? source\n :\n JSON.stringify(Array.from(new Uint8Array(source))),\n });\n return fontFace;\n };\n var restoreHandler = patch(doc.fonts, 'add', function (original) {\n return function (fontFace) {\n setTimeout(function () {\n var p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }, 0);\n return original.apply(this, [fontFace]);\n };\n });\n handlers.push(function () {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\nfunction mergeHooks(o, hooks) {\n var mutationCb = o.mutationCb, mousemoveCb = o.mousemoveCb, mouseInteractionCb = o.mouseInteractionCb, scrollCb = o.scrollCb, viewportResizeCb = o.viewportResizeCb, inputCb = o.inputCb, mediaInteractionCb = o.mediaInteractionCb, styleSheetRuleCb = o.styleSheetRuleCb, styleDeclarationCb = o.styleDeclarationCb, canvasMutationCb = o.canvasMutationCb, fontCb = o.fontCb;\n o.mutationCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.mutation) {\n hooks.mutation.apply(hooks, __spreadArray([], __read(p), false));\n }\n mutationCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.mousemoveCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.mousemove) {\n hooks.mousemove.apply(hooks, __spreadArray([], __read(p), false));\n }\n mousemoveCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.mouseInteractionCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.mouseInteraction) {\n hooks.mouseInteraction.apply(hooks, __spreadArray([], __read(p), false));\n }\n mouseInteractionCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.scrollCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.scroll) {\n hooks.scroll.apply(hooks, __spreadArray([], __read(p), false));\n }\n scrollCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.viewportResizeCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.viewportResize) {\n hooks.viewportResize.apply(hooks, __spreadArray([], __read(p), false));\n }\n viewportResizeCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.inputCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.input) {\n hooks.input.apply(hooks, __spreadArray([], __read(p), false));\n }\n inputCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.mediaInteractionCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.mediaInteaction) {\n hooks.mediaInteaction.apply(hooks, __spreadArray([], __read(p), false));\n }\n mediaInteractionCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.styleSheetRuleCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.styleSheetRule) {\n hooks.styleSheetRule.apply(hooks, __spreadArray([], __read(p), false));\n }\n styleSheetRuleCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.styleDeclarationCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.styleDeclaration) {\n hooks.styleDeclaration.apply(hooks, __spreadArray([], __read(p), false));\n }\n styleDeclarationCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.canvasMutationCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.canvasMutation) {\n hooks.canvasMutation.apply(hooks, __spreadArray([], __read(p), false));\n }\n canvasMutationCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n o.fontCb = function () {\n var p = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n p[_i] = arguments[_i];\n }\n if (hooks.font) {\n hooks.font.apply(hooks, __spreadArray([], __read(p), false));\n }\n fontCb.apply(void 0, __spreadArray([], __read(p), false));\n };\n}\nfunction initObservers(o, hooks) {\n var e_1, _a;\n if (hooks === void 0) { hooks = {}; }\n var currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return function () { };\n }\n mergeHooks(o, hooks);\n var mutationObserver = initMutationObserver(o, o.doc);\n var mousemoveHandler = initMoveObserver(o);\n var mouseInteractionHandler = initMouseInteractionObserver(o);\n var scrollHandler = initScrollObserver(o);\n var viewportResizeHandler = initViewportResizeObserver(o);\n var inputHandler = initInputObserver(o);\n var mediaInteractionHandler = initMediaInteractionObserver(o);\n var styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n var styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow,\n });\n var fontObserver = o.collectFonts ? initFontObserver(o) : function () { };\n var pluginHandlers = [];\n try {\n for (var _b = __values(o.plugins), _c = _b.next(); !_c.done; _c = _b.next()) {\n var plugin = _c.value;\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return function () {\n mutationBuffers.forEach(function (b) { return b.reset(); });\n mutationObserver.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n styleSheetObserver();\n styleDeclarationObserver();\n fontObserver();\n pluginHandlers.forEach(function (h) { return h(); });\n };\n}\n\nexport { INPUT_TAGS, initMutationObserver, initObservers, initScrollObserver, mutationBuffers };\n","var IframeManager = (function () {\n function IframeManager(options) {\n this.iframes = new WeakMap();\n this.mutationCb = options.mutationCb;\n }\n IframeManager.prototype.addIframe = function (iframeEl) {\n this.iframes.set(iframeEl, true);\n };\n IframeManager.prototype.addLoadListener = function (cb) {\n this.loadListener = cb;\n };\n IframeManager.prototype.attachIframe = function (iframeEl, childSn) {\n var _a;\n this.mutationCb({\n adds: [\n {\n parentId: iframeEl.__sn.id,\n nextId: null,\n node: childSn,\n },\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true,\n });\n (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);\n };\n return IframeManager;\n}());\n\nexport { IframeManager };\n","import { __assign } from '../../ext/tslib/tslib.es6.js';\nimport { initMutationObserver, initScrollObserver } from './observer.js';\nimport { patch } from '../utils.js';\n\nvar ShadowDomManager = (function () {\n function ShadowDomManager(options) {\n this.restorePatches = [];\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n var manager = this;\n this.restorePatches.push(patch(HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n var shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager.addShadowRoot(this.shadowRoot, this.ownerDocument);\n return shadowRoot;\n };\n }));\n }\n ShadowDomManager.prototype.addShadowRoot = function (shadowRoot, doc) {\n initMutationObserver(__assign(__assign({}, this.bypassOptions), { doc: doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);\n initScrollObserver(__assign(__assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));\n };\n ShadowDomManager.prototype.observeAttachShadow = function (iframeElement) {\n if (iframeElement.contentWindow) {\n var manager_1 = this;\n this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n var shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager_1.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);\n return shadowRoot;\n };\n }));\n }\n };\n ShadowDomManager.prototype.reset = function () {\n this.restorePatches.forEach(function (restorePatch) { return restorePatch(); });\n };\n return ShadowDomManager;\n}());\n\nexport { ShadowDomManager };\n","import { __values, __spreadArray, __read } from '../../../../ext/tslib/tslib.es6.js';\nimport { CanvasContext } from '../../../types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\n\nfunction initCanvas2DMutationObserver(cb, win, blockClass, mirror) {\n var e_1, _a;\n var handlers = [];\n var props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);\n var _loop_1 = function (prop) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {\n return \"continue\";\n }\n var restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {\n return function () {\n var _this = this;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if (!isBlocked(this.canvas, blockClass)) {\n setTimeout(function () {\n var recordArgs = __spreadArray([], __read(args), false);\n if (prop === 'drawImage') {\n if (recordArgs[0] &&\n recordArgs[0] instanceof HTMLCanvasElement) {\n var canvas = recordArgs[0];\n var ctx = canvas.getContext('2d');\n var imgd = ctx === null || ctx === void 0 ? void 0 : ctx.getImageData(0, 0, canvas.width, canvas.height);\n var pix = imgd === null || imgd === void 0 ? void 0 : imgd.data;\n recordArgs[0] = JSON.stringify(pix);\n }\n }\n cb(_this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: recordArgs,\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_b) {\n var hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {\n set: function (v) {\n cb(this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n };\n try {\n for (var props2D_1 = __values(props2D), props2D_1_1 = props2D_1.next(); !props2D_1_1.done; props2D_1_1 = props2D_1.next()) {\n var prop = props2D_1_1.value;\n _loop_1(prop);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (props2D_1_1 && !props2D_1_1.done && (_a = props2D_1.return)) _a.call(props2D_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\n\nexport default initCanvas2DMutationObserver;\n","/*\n * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>\n * Copyright (c) 2021 Niklas von Hertzen <https://hertzen.com>\n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\nvar decode = function (base64) {\n var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n return arraybuffer;\n};\n\nexport { decode, encode };\n","import { __spreadArray, __read } from '../../../../ext/tslib/tslib.es6.js';\nimport { patch, isBlocked } from '../../../utils.js';\n\nfunction initCanvasContextObserver(win, blockClass) {\n var handlers = [];\n try {\n var restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {\n return function (contextType) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (!isBlocked(this, blockClass)) {\n if (!('__context' in this))\n this.__context = contextType;\n }\n return original.apply(this, __spreadArray([contextType], __read(args), false));\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n console.error('failed to patch HTMLCanvasElement.prototype.getContext');\n }\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\n\nexport default initCanvasContextObserver;\n","import { __spreadArray, __read } from '../../../../ext/tslib/tslib.es6.js';\nimport { encode } from '../../../../../../ext/base64-arraybuffer/dist/base64-arraybuffer.es5.js';\n\nvar webGLVarMap = new Map();\nfunction variableListFor(ctx, ctor) {\n var contextMap = webGLVarMap.get(ctx);\n if (!contextMap) {\n contextMap = new Map();\n webGLVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nvar saveWebGLVar = function (value, win, ctx) {\n if (!value ||\n !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))\n return;\n var name = value.constructor.name;\n var list = variableListFor(ctx, name);\n var index = list.indexOf(value);\n if (index === -1) {\n index = list.length;\n list.push(value);\n }\n return index;\n};\nfunction serializeArg(value, win, ctx) {\n if (value instanceof Array) {\n return value.map(function (arg) { return serializeArg(arg, win, ctx); });\n }\n else if (value === null) {\n return value;\n }\n else if (value instanceof Float32Array ||\n value instanceof Float64Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Uint8Array ||\n value instanceof Uint16Array ||\n value instanceof Int16Array ||\n value instanceof Int8Array ||\n value instanceof Uint8ClampedArray) {\n var name_1 = value.constructor.name;\n return {\n rr_type: name_1,\n args: [Object.values(value)],\n };\n }\n else if (value instanceof ArrayBuffer) {\n var name_2 = value.constructor.name;\n var base64 = encode(value);\n return {\n rr_type: name_2,\n base64: base64,\n };\n }\n else if (value instanceof DataView) {\n var name_3 = value.constructor.name;\n return {\n rr_type: name_3,\n args: [\n serializeArg(value.buffer, win, ctx),\n value.byteOffset,\n value.byteLength,\n ],\n };\n }\n else if (value instanceof HTMLImageElement) {\n var name_4 = value.constructor.name;\n var src = value.src;\n return {\n rr_type: name_4,\n src: src,\n };\n }\n else if (value instanceof ImageData) {\n var name_5 = value.constructor.name;\n return {\n rr_type: name_5,\n args: [serializeArg(value.data, win, ctx), value.width, value.height],\n };\n }\n else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\n var name_6 = value.constructor.name;\n var index = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name_6,\n index: index,\n };\n }\n return value;\n}\nvar serializeArgs = function (args, win, ctx) {\n return __spreadArray([], __read(args), false).map(function (arg) { return serializeArg(arg, win, ctx); });\n};\nvar isInstanceOfWebGLObject = function (value, win) {\n var webGLConstructorNames = [\n 'WebGLActiveInfo',\n 'WebGLBuffer',\n 'WebGLFramebuffer',\n 'WebGLProgram',\n 'WebGLRenderbuffer',\n 'WebGLShader',\n 'WebGLShaderPrecisionFormat',\n 'WebGLTexture',\n 'WebGLUniformLocation',\n 'WebGLVertexArrayObject',\n 'WebGLVertexArrayObjectOES',\n ];\n var supportedWebGLConstructorNames = webGLConstructorNames.filter(function (name) { return typeof win[name] === 'function'; });\n return Boolean(supportedWebGLConstructorNames.find(function (name) { return value instanceof win[name]; }));\n};\n\nexport { isInstanceOfWebGLObject, saveWebGLVar, serializeArg, serializeArgs, variableListFor };\n","import { __spreadArray, __read, __values } from '../../../../ext/tslib/tslib.es6.js';\nimport { CanvasContext } from '../../../types.js';\nimport { patch, isBlocked, hookSetter } from '../../../utils.js';\nimport { saveWebGLVar, serializeArgs } from './serialize-args.js';\n\nfunction patchGLPrototype(prototype, type, cb, blockClass, mirror, win) {\n var e_1, _a;\n var handlers = [];\n var props = Object.getOwnPropertyNames(prototype);\n var _loop_1 = function (prop) {\n try {\n if (typeof prototype[prop] !== 'function') {\n return \"continue\";\n }\n var restoreHandler = patch(prototype, prop, function (original) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var result = original.apply(this, args);\n saveWebGLVar(result, win, prototype);\n if (!isBlocked(this.canvas, blockClass)) {\n var id = mirror.getId(this.canvas);\n var recordArgs = serializeArgs(__spreadArray([], __read(args), false), win, prototype);\n var mutation = {\n type: type,\n property: prop,\n args: recordArgs,\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_b) {\n var hookHandler = hookSetter(prototype, prop, {\n set: function (v) {\n cb(this.canvas, {\n type: type,\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n };\n try {\n for (var props_1 = __values(props), props_1_1 = props_1.next(); !props_1_1.done; props_1_1 = props_1.next()) {\n var prop = props_1_1.value;\n _loop_1(prop);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (props_1_1 && !props_1_1.done && (_a = props_1.return)) _a.call(props_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, mirror) {\n var handlers = [];\n handlers.push.apply(handlers, __spreadArray([], __read(patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, mirror, win)), false));\n if (typeof win.WebGL2RenderingContext !== 'undefined') {\n handlers.push.apply(handlers, __spreadArray([], __read(patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, mirror, win)), false));\n }\n return function () {\n handlers.forEach(function (h) { return h(); });\n };\n}\n\nexport default initCanvasWebGLMutationObserver;\n","import { __assign, __read, __values } from '../../ext/tslib/tslib.es6.js';\nimport { snapshot } from '../../../rrweb-snapshot/es/rrweb-snapshot.js';\nimport { initObservers, mutationBuffers } from './observer.js';\nimport { polyfill, on, createMirror, getWindowWidth, getWindowHeight, isIframeINode, hasShadowRoot } from '../utils.js';\nimport { EventType, IncrementalSource } from '../types.js';\nimport { IframeManager } from './iframe-manager.js';\nimport { ShadowDomManager } from './shadow-dom-manager.js';\nimport { CanvasManager } from './observers/canvas/canvas-manager.js';\n\nfunction wrapEvent(e) {\n return __assign(__assign({}, e), { timestamp: Date.now() });\n}\nvar wrappedEmit;\nvar takeFullSnapshot;\nvar mirror = createMirror();\nfunction record(options) {\n if (options === void 0) { options = {}; }\n var emit = options.emit, checkoutEveryNms = options.checkoutEveryNms, checkoutEveryNth = options.checkoutEveryNth, _a = options.blockClass, blockClass = _a === void 0 ? 'rr-block' : _a, _b = options.blockSelector, blockSelector = _b === void 0 ? null : _b, _c = options.ignoreClass, ignoreClass = _c === void 0 ? 'rr-ignore' : _c, _d = options.maskTextClass, maskTextClass = _d === void 0 ? 'rr-mask' : _d, _e = options.maskTextSelector, maskTextSelector = _e === void 0 ? null : _e, _f = options.inlineStylesheet, inlineStylesheet = _f === void 0 ? true : _f, maskAllInputs = options.maskAllInputs, _maskInputOptions = options.maskInputOptions, _slimDOMOptions = options.slimDOMOptions, maskInputFn = options.maskInputFn, maskTextFn = options.maskTextFn, hooks = options.hooks, packFn = options.packFn, _g = options.sampling, sampling = _g === void 0 ? {} : _g, mousemoveWait = options.mousemoveWait, _h = options.recordCanvas, recordCanvas = _h === void 0 ? false : _h, _j = options.userTriggeredOnInput, userTriggeredOnInput = _j === void 0 ? false : _j, _k = options.collectFonts, collectFonts = _k === void 0 ? false : _k, _l = options.inlineImages, inlineImages = _l === void 0 ? false : _l, plugins = options.plugins, _m = options.keepIframeSrcFn, keepIframeSrcFn = _m === void 0 ? function () { return false; } : _m;\n if (!emit) {\n throw new Error('emit function is required');\n }\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\n sampling.mousemove = mousemoveWait;\n }\n var maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n password: true,\n }\n : _maskInputOptions !== undefined\n ? _maskInputOptions\n : { password: true };\n var slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\n ? {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n headMetaAuthorship: _slimDOMOptions === 'all',\n headMetaDescKeywords: _slimDOMOptions === 'all',\n }\n : _slimDOMOptions\n ? _slimDOMOptions\n : {};\n polyfill();\n var lastFullSnapshotEvent;\n var incrementalSnapshotCount = 0;\n var eventProcessor = function (e) {\n var e_1, _a;\n try {\n for (var _b = __values(plugins || []), _c = _b.next(); !_c.done; _c = _b.next()) {\n var plugin = _c.value;\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (packFn) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = function (e, isCheckout) {\n var _a;\n if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&\n e.type !== EventType.FullSnapshot &&\n !(e.type === EventType.IncrementalSnapshot &&\n e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach(function (buf) { return buf.unfreeze(); });\n }\n emit(eventProcessor(e), isCheckout);\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n }\n else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation &&\n e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n var exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n var exceedTime = checkoutEveryNms &&\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n var wrappedMutationEmit = function (m) {\n wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.Mutation }, m),\n }));\n };\n var wrappedScrollEmit = function (p) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.Scroll }, p),\n }));\n };\n var wrappedCanvasMutationEmit = function (p) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.CanvasMutation }, p),\n }));\n };\n var iframeManager = new IframeManager({\n mutationCb: wrappedMutationEmit,\n });\n var canvasManager = new CanvasManager({\n recordCanvas: recordCanvas,\n mutationCb: wrappedCanvasMutationEmit,\n win: window,\n blockClass: blockClass,\n mirror: mirror,\n });\n var shadowDomManager = new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n blockClass: blockClass,\n blockSelector: blockSelector,\n maskTextClass: maskTextClass,\n maskTextSelector: maskTextSelector,\n inlineStylesheet: inlineStylesheet,\n maskInputOptions: maskInputOptions,\n maskTextFn: maskTextFn,\n maskInputFn: maskInputFn,\n recordCanvas: recordCanvas,\n inlineImages: inlineImages,\n sampling: sampling,\n slimDOMOptions: slimDOMOptions,\n iframeManager: iframeManager,\n canvasManager: canvasManager,\n },\n mirror: mirror,\n });\n takeFullSnapshot = function (isCheckout) {\n var _a, _b, _c, _d;\n if (isCheckout === void 0) { isCheckout = false; }\n wrappedEmit(wrapEvent({\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight(),\n },\n }), isCheckout);\n mutationBuffers.forEach(function (buf) { return buf.lock(); });\n var _e = __read(snapshot(document, {\n blockClass: blockClass,\n blockSelector: blockSelector,\n maskTextClass: maskTextClass,\n maskTextSelector: maskTextSelector,\n inlineStylesheet: inlineStylesheet,\n maskAllInputs: maskInputOptions,\n maskTextFn: maskTextFn,\n slimDOM: slimDOMOptions,\n recordCanvas: recordCanvas,\n inlineImages: inlineImages,\n onSerialize: function (n) {\n if (isIframeINode(n)) {\n iframeManager.addIframe(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: function (iframe, childSn) {\n iframeManager.attachIframe(iframe, childSn);\n shadowDomManager.observeAttachShadow(iframe);\n },\n keepIframeSrcFn: keepIframeSrcFn,\n }), 2), node = _e[0], idNodeMap = _e[1];\n if (!node) {\n return console.warn('Failed to snapshot the document');\n }\n mirror.map = idNodeMap;\n wrappedEmit(wrapEvent({\n type: EventType.FullSnapshot,\n data: {\n node: node,\n initialOffset: {\n left: window.pageXOffset !== undefined\n ? window.pageXOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||\n ((_b = (_a = document === null || document === void 0 ? void 0 : document.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollLeft) ||\n 0,\n top: window.pageYOffset !== undefined\n ? window.pageYOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||\n ((_d = (_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.parentElement) === null || _d === void 0 ? void 0 : _d.scrollTop) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollTop) ||\n 0,\n },\n },\n }));\n mutationBuffers.forEach(function (buf) { return buf.unlock(); });\n };\n try {\n var handlers_1 = [];\n handlers_1.push(on('DOMContentLoaded', function () {\n wrappedEmit(wrapEvent({\n type: EventType.DomContentLoaded,\n data: {},\n }));\n }));\n var observe_1 = function (doc) {\n var _a;\n return initObservers({\n mutationCb: wrappedMutationEmit,\n mousemoveCb: function (positions, source) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: {\n source: source,\n positions: positions,\n },\n }));\n },\n mouseInteractionCb: function (d) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.MouseInteraction }, d),\n }));\n },\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: function (d) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.ViewportResize }, d),\n }));\n },\n inputCb: function (v) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.Input }, v),\n }));\n },\n mediaInteractionCb: function (p) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.MediaInteraction }, p),\n }));\n },\n styleSheetRuleCb: function (r) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.StyleSheetRule }, r),\n }));\n },\n styleDeclarationCb: function (r) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.StyleDeclaration }, r),\n }));\n },\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: function (p) {\n return wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: __assign({ source: IncrementalSource.Font }, p),\n }));\n },\n blockClass: blockClass,\n ignoreClass: ignoreClass,\n maskTextClass: maskTextClass,\n maskTextSelector: maskTextSelector,\n maskInputOptions: maskInputOptions,\n inlineStylesheet: inlineStylesheet,\n sampling: sampling,\n recordCanvas: recordCanvas,\n inlineImages: inlineImages,\n userTriggeredOnInput: userTriggeredOnInput,\n collectFonts: collectFonts,\n doc: doc,\n maskInputFn: maskInputFn,\n maskTextFn: maskTextFn,\n blockSelector: blockSelector,\n slimDOMOptions: slimDOMOptions,\n mirror: mirror,\n iframeManager: iframeManager,\n shadowDomManager: shadowDomManager,\n canvasManager: canvasManager,\n plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter(function (p) { return p.observer; })) === null || _a === void 0 ? void 0 : _a.map(function (p) { return ({\n observer: p.observer,\n options: p.options,\n callback: function (payload) {\n return wrappedEmit(wrapEvent({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload: payload,\n },\n }));\n },\n }); })) || [],\n }, hooks);\n };\n iframeManager.addLoadListener(function (iframeEl) {\n handlers_1.push(observe_1(iframeEl.contentDocument));\n });\n var init_1 = function () {\n takeFullSnapshot();\n handlers_1.push(observe_1(document));\n };\n if (document.readyState === 'interactive' ||\n document.readyState === 'complete') {\n init_1();\n }\n else {\n handlers_1.push(on('load', function () {\n wrappedEmit(wrapEvent({\n type: EventType.Load,\n data: {},\n }));\n init_1();\n }, window));\n }\n return function () {\n handlers_1.forEach(function (h) { return h(); });\n };\n }\n catch (error) {\n console.warn(error);\n }\n}\nrecord.addCustomEvent = function (tag, payload) {\n if (!wrappedEmit) {\n throw new Error('please add custom event after start recording');\n }\n wrappedEmit(wrapEvent({\n type: EventType.Custom,\n data: {\n tag: tag,\n payload: payload,\n },\n }));\n};\nrecord.freezePage = function () {\n mutationBuffers.forEach(function (buf) { return buf.freeze(); });\n};\nrecord.takeFullSnapshot = function (isCheckout) {\n if (!takeFullSnapshot) {\n throw new Error('please take full snapshot after start recording');\n }\n takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\n\nexport default record;\n","import { __rest } from '../../../../ext/tslib/tslib.es6.js';\nimport initCanvas2DMutationObserver from './2d.js';\nimport initCanvasContextObserver from './canvas.js';\nimport initCanvasWebGLMutationObserver from './webgl.js';\n\nvar CanvasManager = (function () {\n function CanvasManager(options) {\n this.pendingCanvasMutations = new Map();\n this.rafStamps = { latestId: 0, invokeId: null };\n this.frozen = false;\n this.locked = false;\n this.processMutation = function (target, mutation) {\n var newFrame = this.rafStamps.invokeId &&\n this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n };\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n if (options.recordCanvas === true)\n this.initCanvasMutationObserver(options.win, options.blockClass);\n }\n CanvasManager.prototype.reset = function () {\n this.pendingCanvasMutations.clear();\n this.resetObservers && this.resetObservers();\n };\n CanvasManager.prototype.freeze = function () {\n this.frozen = true;\n };\n CanvasManager.prototype.unfreeze = function () {\n this.frozen = false;\n };\n CanvasManager.prototype.lock = function () {\n this.locked = true;\n };\n CanvasManager.prototype.unlock = function () {\n this.locked = false;\n };\n CanvasManager.prototype.initCanvasMutationObserver = function (win, blockClass) {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n var canvasContextReset = initCanvasContextObserver(win, blockClass);\n var canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, this.mirror);\n var canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, this.mirror);\n this.resetObservers = function () {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n };\n };\n CanvasManager.prototype.startPendingCanvasMutationFlusher = function () {\n var _this = this;\n requestAnimationFrame(function () { return _this.flushPendingCanvasMutations(); });\n };\n CanvasManager.prototype.startRAFTimestamping = function () {\n var _this = this;\n var setLatestRAFTimestamp = function (timestamp) {\n _this.rafStamps.latestId = timestamp;\n requestAnimationFrame(setLatestRAFTimestamp);\n };\n requestAnimationFrame(setLatestRAFTimestamp);\n };\n CanvasManager.prototype.flushPendingCanvasMutations = function () {\n var _this = this;\n this.pendingCanvasMutations.forEach(function (values, canvas) {\n var id = _this.mirror.getId(canvas);\n _this.flushPendingCanvasMutationFor(canvas, id);\n });\n requestAnimationFrame(function () { return _this.flushPendingCanvasMutations(); });\n };\n CanvasManager.prototype.flushPendingCanvasMutationFor = function (canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n var valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1)\n return;\n var values = valuesWithType.map(function (value) {\n value.type; var rest = __rest(value, [\"type\"]);\n return rest;\n });\n var type = valuesWithType[0].type;\n this.mutationCb({ id: id, type: type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n };\n return CanvasManager;\n}());\n\nexport { CanvasManager };\n","import { getCurrentHub, addBreadcrumb, captureException, addGlobalEventProcessor, setContext } from '@sentry/core';\nimport { htmlTreeAsString, logger as logger$1, uuid4, browserPerformanceTimeOrigin, addInstrumentationHandler, createEnvelope } from '@sentry/utils';\nimport debounce from 'lodash.debounce';\nimport { record, EventType } from 'rrweb';\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nfunction __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\n\nfunction createBreadcrumb(breadcrumb) {\n return __assign({ timestamp: new Date().getTime() / 1000, type: 'default' }, breadcrumb);\n}\n\nfunction handleDom(handlerData) {\n // Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112\n var target;\n var targetNode;\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n targetNode =\n handlerData.event.target ||\n handlerData.event;\n target = htmlTreeAsString(targetNode);\n }\n catch (e) {\n target = '<unknown>';\n }\n if (target.length === 0) {\n return null;\n }\n return createBreadcrumb({\n category: \"ui.\".concat(handlerData.name),\n message: target,\n data: __assign({}, (targetNode ? { nodeId: record.mirror.getId(targetNode) } : {})),\n });\n}\n\nvar _LAST_BREADCRUMB = null;\nfunction handleScope(scope) {\n var _a;\n //@ts-expect-error using private val\n var newBreadcrumb = scope._breadcrumbs[scope._breadcrumbs.length - 1];\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n _LAST_BREADCRUMB = newBreadcrumb;\n if (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n ((_a = newBreadcrumb.category) === null || _a === void 0 ? void 0 : _a.startsWith('ui.'))) {\n return null;\n }\n return createBreadcrumb(newBreadcrumb);\n}\n\nfunction getBreadcrumbHandler(type) {\n if (type === 'scope') {\n return handleScope;\n }\n return handleDom;\n}\n\nvar isBrowser$1 = typeof window !== 'undefined';\n/**\n * Returns true if we are currently recording an internal to Sentry replay\n * (e.g. on https://sentry.io )\n */\nfunction isInternal() {\n return (isBrowser$1 &&\n ['sentry.io', 'dev.getsentry.net'].includes(window.location.host));\n}\n\n/**\n * Checks is `targetHost` is a Sentry ingestion host\n */\nfunction isIngestHost(targetHost) {\n var _a;\n var _b = ((_a = getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getDsn()) || {}, protocol = _b.protocol, host = _b.host;\n // XXX: Special case when this integration is used by Sentry on `sentry.io`\n // We would like to capture network requests made to our ingest endpoints for debugging\n if (isInternal()) {\n return false;\n }\n return targetHost.startsWith(\"\".concat(protocol, \"://\").concat(host));\n}\n\nfunction handleFetch(handlerData) {\n if (!handlerData.endTimestamp) {\n return null;\n }\n var startTimestamp = handlerData.startTimestamp, endTimestamp = handlerData.endTimestamp, fetchData = handlerData.fetchData, response = handlerData.response;\n // Do not capture fetches to Sentry ingestion endpoint\n if (isIngestHost(fetchData.url)) {\n return null;\n }\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: fetchData.url,\n data: {\n method: fetchData.method,\n statusCode: response.status,\n },\n };\n}\n\nfunction handleHistory(handlerData) {\n var from = handlerData.from, to = handlerData.to;\n var now = new Date().getTime() / 1000;\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\nfunction handleXhr(handlerData) {\n var _a;\n if (handlerData.xhr.__sentry_own_request__) {\n // Taken from sentry-javascript\n // Only capture non-sentry requests\n return null;\n }\n if (handlerData.startTimestamp) {\n // TODO: See if this is still needed\n handlerData.xhr.__sentry_xhr__ = handlerData.xhr.__sentry_xhr__ || {};\n handlerData.xhr.__sentry_xhr__.startTimestamp = handlerData.startTimestamp;\n }\n if (!handlerData.endTimestamp) {\n return null;\n }\n var _b = handlerData.xhr.__sentry_xhr__ || {}, method = _b.method, url = _b.url, statusCode = _b.status_code;\n // Do not capture fetches to Sentry ingestion endpoint\n if (url === undefined || isIngestHost(url)) {\n return null;\n }\n return {\n type: 'resource.xhr',\n name: url,\n start: (((_a = handlerData.xhr.__sentry_xhr__) === null || _a === void 0 ? void 0 : _a.startTimestamp) || 0) / 1000 ||\n handlerData.endTimestamp / 1000.0,\n end: handlerData.endTimestamp / 1000.0,\n data: {\n method: method,\n statusCode: statusCode,\n },\n };\n}\n\nfunction getSpanHandler(type) {\n if (type === 'fetch') {\n return handleFetch;\n }\n if (type === 'xhr') {\n return handleXhr;\n }\n return handleHistory;\n}\n\nvar REPLAY_SESSION_KEY = 'sentryReplaySession';\nvar REPLAY_EVENT_NAME = 'replay_event';\n// The idle limit for a session\nvar SESSION_IDLE_DURATION = 300000; // 5 minutes in ms\n// Grace period to keep a session when a user changes tabs or hides window\nvar VISIBILITY_CHANGE_TIMEOUT = SESSION_IDLE_DURATION;\n// The maximum length of a session\nvar MAX_SESSION_LIFE = 1800000; // 30 minutes\n/**\n * Defaults for sampling rates\n */\nvar DEFAULT_SESSION_SAMPLE_RATE = 0.1;\nvar DEFAULT_ERROR_SAMPLE_RATE = 1.0;\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession() {\n var hasSessionStorage = 'sessionStorage' in window;\n if (!hasSessionStorage) {\n return;\n }\n try {\n window.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n }\n catch (_a) {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nfunction isExpired(initialTime, expiry, targetTime) {\n if (targetTime === void 0) { targetTime = +new Date(); }\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n return initialTime + expiry <= targetTime;\n}\n\n/**\n * Checks to see if session is expired\n */\nfunction isSessionExpired(session, idleTimeout, targetTime) {\n if (targetTime === void 0) { targetTime = +new Date(); }\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, MAX_SESSION_LIFE, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `idleTimeout` ms)\n isExpired(session === null || session === void 0 ? void 0 : session.lastActivity, idleTimeout, targetTime));\n}\n\nfunction wrapLogger(logFn) {\n return function wrappedLog() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return logFn.call.apply(logFn, __spreadArray([logger$1, '[Replay]'], args, false));\n };\n}\nvar logger = __assign(__assign({}, logger$1), { error: wrapLogger(logger$1.error), warn: wrapLogger(logger$1.warn), log: wrapLogger(logger$1.log) });\n\nfunction saveSession(session) {\n var hasSessionStorage = 'sessionStorage' in window;\n if (!hasSessionStorage) {\n return;\n }\n try {\n window.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n }\n catch (_a) {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nfunction isSampled(sampleRate) {\n if (sampleRate === undefined) {\n return false;\n }\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n\nvar Session = /** @class */ (function () {\n function Session(session, _a) {\n if (session === void 0) { session = {}; }\n var stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;\n var _b, _c, _d, _e;\n var now = new Date().getTime();\n this._id = session.id || uuid4();\n this._started = (_b = session.started) !== null && _b !== void 0 ? _b : now;\n this._lastActivity = (_c = session.lastActivity) !== null && _c !== void 0 ? _c : now;\n this._segmentId = (_d = session.segmentId) !== null && _d !== void 0 ? _d : 0;\n this._sampled =\n (_e = session.sampled) !== null && _e !== void 0 ? _e : (isSampled(sessionSampleRate)\n ? 'session'\n : isSampled(errorSampleRate)\n ? 'error'\n : false);\n this.options = {\n stickySession: stickySession,\n };\n }\n Object.defineProperty(Session.prototype, \"id\", {\n get: function () {\n return this._id;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Session.prototype, \"started\", {\n get: function () {\n return this._started;\n },\n set: function (newDate) {\n this._started = newDate;\n if (this.options.stickySession) {\n saveSession(this);\n }\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Session.prototype, \"lastActivity\", {\n get: function () {\n return this._lastActivity;\n },\n set: function (newDate) {\n this._lastActivity = newDate;\n if (this.options.stickySession) {\n saveSession(this);\n }\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Session.prototype, \"segmentId\", {\n get: function () {\n return this._segmentId;\n },\n set: function (id) {\n this._segmentId = id;\n if (this.options.stickySession) {\n saveSession(this);\n }\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Session.prototype, \"previousSessionId\", {\n get: function () {\n return this._previousSessionId;\n },\n set: function (id) {\n this._previousSessionId = id;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Session.prototype, \"sampled\", {\n get: function () {\n return this._sampled;\n },\n set: function (_isSampled) {\n throw new Error('Unable to change sampled value');\n },\n enumerable: false,\n configurable: true\n });\n Session.prototype.toJSON = function () {\n return {\n id: this.id,\n started: this.started,\n lastActivity: this.lastActivity,\n segmentId: this._segmentId,\n sampled: this._sampled,\n };\n };\n return Session;\n}());\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nfunction createSession(_a) {\n var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate, _b = _a.stickySession, stickySession = _b === void 0 ? false : _b;\n var session = new Session(undefined, {\n stickySession: stickySession,\n errorSampleRate: errorSampleRate,\n sessionSampleRate: sessionSampleRate,\n });\n logger.log(\"Creating new session: \".concat(session.id));\n if (stickySession) {\n saveSession(session);\n }\n return session;\n}\n\n/**\n * Fetches a session from storage\n */\nfunction fetchSession(_a) {\n var sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;\n var hasSessionStorage = 'sessionStorage' in window;\n if (!hasSessionStorage) {\n return null;\n }\n try {\n // This can throw if cookies are disabled\n var sessionStringFromStorage = window.sessionStorage.getItem(REPLAY_SESSION_KEY);\n if (!sessionStringFromStorage) {\n return null;\n }\n var sessionObj = JSON.parse(sessionStringFromStorage);\n return new Session(sessionObj, \n // We are assuming that if there is a saved item, then the session is sticky,\n // however this could break down if we used a different storage mechanism (e.g. localstorage)\n { stickySession: true, sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate });\n }\n catch (_b) {\n return null;\n }\n}\n\n/**\n * Get or create a session\n */\nfunction getSession(_a) {\n var expiry = _a.expiry, currentSession = _a.currentSession, stickySession = _a.stickySession, sessionSampleRate = _a.sessionSampleRate, errorSampleRate = _a.errorSampleRate;\n // If session exists and is passed, use it instead of always hitting session storage\n var session = currentSession ||\n (stickySession && fetchSession({ sessionSampleRate: sessionSampleRate, errorSampleRate: errorSampleRate }));\n if (session) {\n // If there is a session, check if it is valid (e.g. \"last activity\" time\n // should be within the \"session idle time\", and \"session started\" time is\n // within \"max session time\").\n var isExpired = isSessionExpired(session, expiry);\n if (!isExpired) {\n return { type: 'saved', session: session };\n }\n else {\n logger.log(\"Session has expired\");\n }\n // Otherwise continue to create a new session\n }\n var newSession = createSession({\n stickySession: stickySession,\n sessionSampleRate: sessionSampleRate,\n errorSampleRate: errorSampleRate,\n });\n return { type: 'new', session: newSession };\n}\n\n/**\n * Wrapper for core SDK's `addBreadcrumb` only when used on `sentry.io`\n */\nfunction addInternalBreadcrumb(arg) {\n if (!isInternal()) {\n return;\n }\n var category = arg.category, level = arg.level, message = arg.message, rest = __rest(arg, [\"category\", \"level\", \"message\"]);\n addBreadcrumb(__assign({ category: category || 'console', level: level || 'debug', message: \"[debug]: \".concat(message) }, rest));\n}\n\n/**\n * Captures exceptions to Sentry only when it occurs on sentry.io\n */\nfunction captureInternalException(err) {\n if (!isInternal()) {\n return;\n }\n captureException(err);\n}\n\nfunction createPayload(_a) {\n var events = _a.events, headers = _a.headers;\n var payloadWithSequence;\n // XXX: newline is needed to separate sequence id from events\n var replayHeaders = \"\".concat(JSON.stringify(headers), \"\\n\");\n if (typeof events === 'string') {\n payloadWithSequence = \"\".concat(replayHeaders).concat(events);\n }\n else {\n var enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n var sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + events.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(events, sequence.length);\n }\n return payloadWithSequence;\n}\n\nvar NAVIGATION_ENTRY_KEYS = [\n 'name',\n 'type',\n 'startTime',\n 'transferSize',\n 'duration',\n];\nfunction isNavigationEntryEqual(a) {\n return function (b) {\n return NAVIGATION_ENTRY_KEYS.every(function (key) { return a[key] === b[key]; });\n };\n}\n/**\n * There are some difficulties diagnosing why there are duplicate navigation\n * entries. We've witnessed several intermittent results:\n * - duplicate entries have duration = 0\n * - duplicate entries are the same object reference\n * - none of the above\n *\n * Compare the values of several keys to determine if the entries are duplicates or not.\n */\nfunction dedupePerformanceEntries(currentList, newList) {\n // Partition `currentList` into 3 different lists based on entryType\n var _a = currentList.reduce(function (acc, entry) {\n if (entry.entryType === 'navigation') {\n acc[0].push(entry);\n }\n else if (entry.entryType === 'largest-contentful-paint') {\n acc[1].push(entry);\n }\n else {\n acc[2].push(entry);\n }\n return acc;\n }, [[], [], []]), existingNavigationEntries = _a[0], existingLcpEntries = _a[1], existingEntries = _a[2];\n var newEntries = [];\n var newNavigationEntries = [];\n var newLcpEntry = existingLcpEntries.length\n ? existingLcpEntries[existingLcpEntries.length - 1] // Take the last element as list is sorted\n : undefined;\n newList.forEach(function (entry) {\n if (entry.entryType === 'largest-contentful-paint') {\n // We want the latest LCP event only\n if (!newLcpEntry || newLcpEntry.startTime < entry.startTime) {\n newLcpEntry = entry;\n }\n return;\n }\n if (entry.entryType === 'navigation') {\n var navigationEntry = entry;\n // Check if the navigation entry is contained in currentList or newList\n if (\n // Ignore any navigation entries with duration 0, as they are likely duplicates\n entry.duration > 0 &&\n // Ensure new entry does not already exist in existing entries\n !existingNavigationEntries.find(isNavigationEntryEqual(navigationEntry)) &&\n // Ensure new entry does not already exist in new list of navigation entries\n !newNavigationEntries.find(isNavigationEntryEqual(navigationEntry))) {\n newNavigationEntries.push(navigationEntry);\n }\n // Otherwise this navigation entry is considered a duplicate and is thrown away\n return;\n }\n newEntries.push(entry);\n });\n // Re-combine and sort by startTime\n return __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], (newLcpEntry ? [newLcpEntry] : []), true), existingNavigationEntries, true), existingEntries, true), newEntries, true), newNavigationEntries, true).sort(function (a, b) { return a.startTime - b.startTime; });\n}\n\nvar _a;\n// Map entryType -> function to normalize data for event\nvar ENTRY_TYPES = (_a = {\n resource: createResourceEntry,\n paint: createPaintEntry,\n navigation: createNavigationEntry\n },\n _a['largest-contentful-paint'] = createLargestContentfulPaint,\n _a);\nfunction createPerformanceEntries(entries) {\n return entries\n .map(createPerformanceEntry)\n .filter(Boolean);\n}\nfunction createPerformanceEntry(entry) {\n if (ENTRY_TYPES[entry.entryType] === undefined) {\n return null;\n }\n return ENTRY_TYPES[entry.entryType](entry);\n}\nfunction getAbsoluteTime(time) {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return (((browserPerformanceTimeOrigin || window.performance.timeOrigin) + time) /\n 1000);\n}\nfunction createPaintEntry(entry) {\n var duration = entry.duration, entryType = entry.entryType, name = entry.name, startTime = entry.startTime;\n var start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name: name,\n start: start,\n end: start + duration,\n };\n}\nfunction createNavigationEntry(entry) {\n // TODO: There looks to be some more interesting bits in here (domComplete, domContentLoaded)\n var entryType = entry.entryType, name = entry.name, duration = entry.duration, domComplete = entry.domComplete, startTime = entry.startTime, transferSize = entry.transferSize, type = entry.type;\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n return {\n type: \"\".concat(entryType, \".\").concat(type),\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name: name,\n data: {\n size: transferSize,\n duration: duration,\n },\n };\n}\nfunction createResourceEntry(entry) {\n var entryType = entry.entryType, initiatorType = entry.initiatorType, name = entry.name, responseEnd = entry.responseEnd, startTime = entry.startTime, encodedBodySize = entry.encodedBodySize, transferSize = entry.transferSize;\n // Do not capture fetches to Sentry ingestion endpoint\n if (isIngestHost(name)) {\n return null;\n }\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n return {\n type: \"\".concat(entryType, \".\").concat(initiatorType),\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name: name,\n data: {\n size: transferSize,\n encodedBodySize: encodedBodySize,\n },\n };\n}\nfunction createLargestContentfulPaint(entry) {\n var duration = entry.duration, entryType = entry.entryType, startTime = entry.startTime, size = entry.size;\n var start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name: entryType,\n start: start,\n end: start + duration,\n data: {\n duration: duration,\n size: size,\n // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')\n nodeId: record.mirror.getId(entry.element),\n },\n };\n}\nfunction createMemoryEntry(memoryEntry) {\n var jsHeapSizeLimit = memoryEntry.jsHeapSizeLimit, totalJSHeapSize = memoryEntry.totalJSHeapSize, usedJSHeapSize = memoryEntry.usedJSHeapSize;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n var time = new Date().getTime() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit: jsHeapSizeLimit,\n totalJSHeapSize: totalJSHeapSize,\n usedJSHeapSize: usedJSHeapSize,\n },\n },\n };\n}\n\nvar workerString = `/*! pako 2.0.4 https://github.com/nodeca/pako @license (MIT AND Zlib) */\nfunction t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const b=t=>t<256?o[t]:o[256+(t>>>7)],g=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},p=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<<t.bi_valid&65535,g(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)},m=(t,e,a)=>{p(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)i[n]=r=r+a[n-1]<<1;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0},x=t=>{t.bi_valid>8?g(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]<t[s]||t[n]===t[s]&&i[e]<=i[a]},A=(t,e,a)=>{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n<t.heap_len&&z(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!z(e,i,t.heap[n],t.depth));)t.heap[a]=t.heap[n],a=n,n<<=1;t.heap[a]=i},E=(t,i,n)=>{let s,r,o,_,f=0;if(0!==t.last_lit)do{s=t.pending_buf[t.d_buf+2*f]<<8|t.pending_buf[t.d_buf+2*f+1],r=t.pending_buf[t.l_buf+f],f++,0===s?m(t,r,i):(o=l[r],m(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],p(t,r,_)),s--,o=b(s),m(t,o,n),_=a[o],0!==_&&(s-=d[o],p(t,s,_)))}while(f<t.last_lit);m(t,256,i)},R=(t,e)=>{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<s;r++)0!==a[2*r]?(t.heap[++t.heap_len]=h=r,t.depth[r]=0):a[2*r+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=h<2?++h:0,a[2*l]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=i[2*l+1]);for(e.max_code=h,r=t.heap_len>>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o<l&&n===r||(o<h?t.bl_tree[2*n]+=o:0!==n?(n!==s&&t.bl_tree[2*n]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4))},S=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o<l&&n===r)){if(o<h)do{m(t,n,t.bl_tree)}while(0!=--o);else 0!==n?(n!==s&&(m(t,n,t.bl_tree),o--),m(t,16,t.bl_tree),p(t,o-3,2)):o<=10?(m(t,17,t.bl_tree),p(t,o-3,3)):(m(t,18,t.bl_tree),p(t,o-11,7));o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4)}};let U=!1;const D=(t,e,a,i)=>{p(t,0+(i?1:0),3),((t,e,a,i)=>{x(t),i&&(g(t,a),g(t,~a)),t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a})(t,e,a,!0)};var O=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(p(t,2+(i?1:0),3),E(t,s,r)):(p(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(p(t,e-257,5),p(t,a-1,5),p(t,i-4,4),s=0;s<i;s++)p(t,t.bl_tree[2*n[s]+1],3);S(t,t.dyn_ltree,e-1),S(t,t.dyn_dtree,a-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,h+1),E(t,t.dyn_ltree,t.dyn_dtree)),y(t),i&&x(t)},T={_tr_init:t=>{U||((()=>{let t,n,w,b,g;const p=new Array(16);for(w=0,b=0;b<28;b++)for(h[b]=w,t=0;t<1<<e[b];t++)l[w++]=b;for(l[w-1]=b,g=0,b=0;b<16;b++)for(d[b]=g,t=0;t<1<<a[b];t++)o[g++]=b;for(g>>=7;b<30;b++)for(d[b]=g<<7,t=0;t<1<<a[b]-7;t++)o[256+g++]=b;for(n=0;n<=15;n++)p[n]=0;for(t=0;t<=143;)s[2*t+1]=8,t++,p[8]++;for(;t<=255;)s[2*t+1]=9,t++,p[9]++;for(;t<=279;)s[2*t+1]=7,t++,p[7]++;for(;t<=287;)s[2*t+1]=8,t++,p[8]++;for(v(s,287,p),t=0;t<30;t++)r[2*t+1]=5,r[2*t]=k(t,5);f=new _(s,e,257,286,15),c=new _(r,a,0,30,15),u=new _(new Array(0),i,0,19,7)})(),U=!0),t.l_desc=new w(t.dyn_ltree,f),t.d_desc=new w(t.dyn_dtree,c),t.bl_desc=new w(t.bl_tree,u),t.bi_buf=0,t.bi_valid=0,y(t)},_tr_stored_block:D,_tr_flush_block:O,_tr_tally:(t,e,a)=>(t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&a,t.last_lit++,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*b(e)]++),t.last_lit===t.lit_bufsize-1),_tr_align:t=>{p(t,2,3),m(t,256,s),(t=>{16===t.bi_valid?(g(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var N=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const F=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var L=(t,e,a,i)=>{const n=F,s=i+a;t^=-1;for(let a=i;a<s;a++)t=t>>>8^n[255&(t^e[a])];return-1^t},I={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=T,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:J,Z_OK:W,Z_STREAM_END:q,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>(t<<1)-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0};let _t=(t,e,a)=>(e<<t.hash_shift^a)&t.hash_mask;const ft=t=>{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ct=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ft(t.strm)},ut=(t,e)=>{t.pending_buf[t.pending++]=e},wt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=N(t.adler,e,n,a):2===t.state.wrap&&(t.adler=L(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&s<f);if(i=258-(f-s),s=f-258,i>r){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n,s,r;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)){t.window.set(t.window.subarray(e,e+e),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,i=t.hash_size,a=i;do{n=t.head[--a],t.head[a]=n>=e?n-e:0}while(--i);i=e,a=i;do{n=t.prev[--a],t.prev[a]=n>=e?n-e:0}while(--i);s+=e}if(0===t.strm.avail_in)break;if(i=bt(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=_t(t,t.ins_h,t.window[r+1]);t.insert&&(t.ins_h=_t(t,t.ins_h,t.window[r+3-1]),t.prev[r&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=r,r++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},mt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=_t(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=_t(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=_t(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ct(t,!1),0===t.strm.avail_out)?1:2},kt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=_t(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a),t.match_length<=5&&(t.strategy===et||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=_t(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ct(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ct(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ct(t,!1),0===t.strm.avail_out)?1:2};function vt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const yt=[new vt(0,0,0,0,((t,e)=>{let a=65535;for(a>t.pending_buf_size-5&&(a=t.pending_buf_size-5);;){if(t.lookahead<=1){if(pt(t),0===t.lookahead&&e===P)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;const i=t.block_start+a;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,ct(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-262&&(ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ct(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(ct(t,!1),t.strm.avail_out),1)})),new vt(4,4,8,4,mt),new vt(4,5,16,8,mt),new vt(4,6,32,32,mt),new vt(4,4,16,16,kt),new vt(8,16,32,32,kt),new vt(8,16,128,128,kt),new vt(8,32,128,256,kt),new vt(32,128,258,1024,kt),new vt(32,258,258,4096,kt)];function xt(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const zt=t=>{if(!t||!t.state)return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=P,C(e),W},At=t=>{const e=zt(t);var a;return e===W&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=yt[a.level].max_lazy,a.good_match=yt[a.level].good_length,a.nice_match=yt[a.level].nice_length,a.max_chain_length=yt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},Et=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt)return lt(t,Q);8===i&&(i=9);const o=new xt;return t.state=o,o.strm=t,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.d_buf=1*o.lit_bufsize,o.l_buf=3*o.lit_bufsize,o.level=e,o.strategy=s,o.method=a,At(t)};var Rt={deflateInit:(t,e)=>Et(t,e,ot,15,8,st),deflateInit2:Et,deflateReset:At,deflateResetKeep:zt,deflateSetHeader:(t,e)=>t&&t.state?2!==t.state.wrap?Q:(t.state.gzhead=e,W):Q,deflate:(t,e)=>{let a,i;if(!t||!t.state||e>J||e<0)return t?lt(t,Q):Q;const n=t.state;if(!t.output||!t.input&&0!==t.avail_in||666===n.status&&e!==X)return lt(t,0===t.avail_out?$:Q);n.strm=t;const s=n.last_flush;if(n.last_flush=e,42===n.status)if(2===n.wrap)t.adler=0,ut(n,31),ut(n,139),ut(n,8),n.gzhead?(ut(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),ut(n,255&n.gzhead.time),ut(n,n.gzhead.time>>8&255),ut(n,n.gzhead.time>>16&255),ut(n,n.gzhead.time>>24&255),ut(n,9===n.level?2:n.strategy>=at||n.level<2?4:0),ut(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(ut(n,255&n.gzhead.extra.length),ut(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=L(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(ut(n,0),ut(n,0),ut(n,0),ut(n,0),ut(n,0),ut(n,9===n.level?2:n.strategy>=at||n.level<2?4:0),ut(n,3),n.status=113);else{let e=ot+(n.w_bits-8<<4)<<8,a=-1;a=n.strategy>=at||n.level<2?0:n.level<6?1:6===n.level?2:3,e|=a<<6,0!==n.strstart&&(e|=32),e+=31-e%31,n.status=113,wt(n,e),0!==n.strstart&&(wt(n,t.adler>>>16),wt(n,65535&t.adler)),t.adler=1}if(69===n.status)if(n.gzhead.extra){for(a=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>a&&(t.adler=L(t.adler,n.pending_buf,n.pending-a,a)),ft(t),a=n.pending,n.pending!==n.pending_buf_size));)ut(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>a&&(t.adler=L(t.adler,n.pending_buf,n.pending-a,a)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){a=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>a&&(t.adler=L(t.adler,n.pending_buf,n.pending-a,a)),ft(t),a=n.pending,n.pending===n.pending_buf_size)){i=1;break}i=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,ut(n,i)}while(0!==i);n.gzhead.hcrc&&n.pending>a&&(t.adler=L(t.adler,n.pending_buf,n.pending-a,a)),0===i&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){a=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>a&&(t.adler=L(t.adler,n.pending_buf,n.pending-a,a)),ft(t),a=n.pending,n.pending===n.pending_buf_size)){i=1;break}i=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,ut(n,i)}while(0!==i);n.gzhead.hcrc&&n.pending>a&&(t.adler=L(t.adler,n.pending_buf,n.pending-a,a)),0===i&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&ft(t),n.pending+2<=n.pending_buf_size&&(ut(n,255&t.adler),ut(n,t.adler>>8&255),t.adler=0,n.status=113)):n.status=113),0!==n.pending){if(ft(t),0===t.avail_out)return n.last_flush=-1,W}else if(0===t.avail_in&&ht(e)<=ht(s)&&e!==X)return lt(t,$);if(666===n.status&&0!==t.avail_in)return lt(t,$);if(0!==t.avail_in||0!==n.lookahead||e!==P&&666!==n.status){let a=n.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ct(t,!1),0===t.strm.avail_out)?1:2})(n,e):n.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&n<s);t.match_length=258-(s-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ct(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ct(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(ct(t,!1),0===t.strm.avail_out)?1:2})(n,e):yt[n.level].func(n,e);if(3!==a&&4!==a||(n.status=666),1===a||3===a)return 0===t.avail_out&&(n.last_flush=-1),W;if(2===a&&(e===Y?K(n):e!==J&&(H(n,0,0,!1),e===G&&(dt(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),ft(t),0===t.avail_out))return n.last_flush=-1,W}return e!==X?W:n.wrap<=0?q:(2===n.wrap?(ut(n,255&t.adler),ut(n,t.adler>>8&255),ut(n,t.adler>>16&255),ut(n,t.adler>>24&255),ut(n,255&t.total_in),ut(n,t.total_in>>8&255),ut(n,t.total_in>>16&255),ut(n,t.total_in>>24&255)):(wt(n,t.adler>>>16),wt(n,65535&t.adler)),ft(t),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?W:q)},deflateEnd:t=>{if(!t||!t.state)return Q;const e=t.state.status;return 42!==e&&69!==e&&73!==e&&91!==e&&103!==e&&113!==e&&666!==e?lt(t,Q):(t.state=null,113===e?lt(t,V):W)},deflateSetDictionary:(t,e)=>{let a=e.length;if(!t||!t.state)return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=N(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=_t(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,W},deflateInfo:\"pako deflate (from Nodeca project)\"};const Zt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var St=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if(\"object\"!=typeof a)throw new TypeError(a+\"must be non-object\");for(const e in a)Zt(a,e)&&(t[e]=a[e])}}return t},Ut=t=>{let e=0;for(let a=0,i=t.length;a<i;a++)e+=t[a].length;const a=new Uint8Array(e);for(let e=0,i=0,n=t.length;e<n;e++){let n=t[e];a.set(n,i),i+=n.length}return a};let Dt=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Dt=!1}const Ot=new Uint8Array(256);for(let t=0;t<256;t++)Ot[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Ot[254]=Ot[254]=1;var Tt=t=>{if(\"function\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n<r;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),o+=a<128?1:a<2048?2:a<65536?3:4;for(e=new Uint8Array(o),s=0,n=0;s<o;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),a<128?e[s++]=a:a<2048?(e[s++]=192|a>>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},Nt=(t,e)=>{const a=e||t.length;if(\"function\"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i<a;){let e=t[i++];if(e<128){s[n++]=e;continue}let r=Ot[e];if(r>4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i<a;)e=e<<6|63&t[i++],r--;r>1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Dt)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a=\"\";for(let i=0;i<e;i++)a+=String.fromCharCode(t[i]);return a})(s,n)},Ft=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Ot[t[a]]>e?a:e};var Lt=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0};const It=Object.prototype.toString,{Z_NO_FLUSH:Bt,Z_SYNC_FLUSH:Ct,Z_FULL_FLUSH:Ht,Z_FINISH:Mt,Z_OK:jt,Z_STREAM_END:Kt,Z_DEFAULT_COMPRESSION:Pt,Z_DEFAULT_STRATEGY:Yt,Z_DEFLATED:Gt}=B;function Xt(t){this.options=St({level:Pt,method:Gt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Yt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Lt,this.strm.avail_out=0;let a=Rt.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==jt)throw new Error(I[a]);if(e.header&&Rt.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t=\"string\"==typeof e.dictionary?Tt(e.dictionary):\"[object ArrayBuffer]\"===It.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=Rt.deflateSetDictionary(this.strm,t),a!==jt)throw new Error(I[a]);this._dict_set=!0}}function Jt(t,e){const a=new Xt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}Xt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Mt:Bt,\"string\"==typeof t?a.input=Tt(t):\"[object ArrayBuffer]\"===It.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===Ct||s===Ht)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=Rt.deflate(a,s),n===Kt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=Rt.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===jt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},Xt.prototype.onData=function(t){this.chunks.push(t)},Xt.prototype.onEnd=function(t){t===jt&&(this.result=Ut(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Wt={Deflate:Xt,deflate:Jt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Jt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Jt(t,e)},constants:B};var qt=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,b,g,p,m,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,b=(1<<E.lenbits)-1,g=(1<<E.distbits)-1;t:do{c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),p=u[f&b];e:for(;;){if(m=p>>>24,f>>>=m,c-=m,m=p>>>16&255,0===m)A[n++]=65535&p;else{if(!(16&m)){if(0==(64&m)){p=u[(65535&p)+(f&(1<<m)-1)];continue e}if(32&m){E.mode=12;break t}t.msg=\"invalid literal/length code\",E.mode=30;break t}k=65535&p,m&=15,m&&(c<m&&(f+=z[a++]<<c,c+=8),k+=f&(1<<m)-1,f>>>=m,c-=m),c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),p=w[f&g];a:for(;;){if(m=p>>>24,f>>>=m,c-=m,m=p>>>16&255,!(16&m)){if(0==(64&m)){p=w[(65535&p)+(f&(1<<m)-1)];continue a}t.msg=\"invalid distance code\",E.mode=30;break t}if(v=65535&p,m&=15,c<m&&(f+=z[a++]<<c,c+=8,c<m&&(f+=z[a++]<<c,c+=8)),v+=f&(1<<m)-1,v>o){t.msg=\"invalid distance too far back\",E.mode=30;break t}if(f>>>=m,c-=m,m=n-s,v>m){if(m=v-m,m>h&&E.sane){t.msg=\"invalid distance too far back\",E.mode=30;break t}if(y=0,x=_,0===d){if(y+=l-m,m<k){k-=m;do{A[n++]=_[y++]}while(--m);y=n-v,x=A}}else if(d<m){if(y+=l+d-m,m-=d,m<k){k-=m;do{A[n++]=_[y++]}while(--m);if(y=0,d<k){m=d,k-=m;do{A[n++]=_[y++]}while(--m);y=n-v,x=A}}}else if(y+=d-m,m<k){k-=m;do{A[n++]=_[y++]}while(--m);y=n-v,x=A}for(;k>2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a<i&&n<r);k=c>>3,a-=k,c-=k<<3,f&=(1<<c)-1,t.next_in=a,t.next_out=n,t.avail_in=a<i?i-a+5:5-(a-i),t.avail_out=n<r?r-n+257:257-(n-r),E.hold=f,E.bits=c};const Qt=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),Vt=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),$t=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),te=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var ee=(t,e,a,i,n,s,r,o)=>{const l=o.bits;let h,d,_,f,c,u,w=0,b=0,g=0,p=0,m=0,k=0,v=0,y=0,x=0,z=0,A=null,E=0;const R=new Uint16Array(16),Z=new Uint16Array(16);let S,U,D,O=null,T=0;for(w=0;w<=15;w++)R[w]=0;for(b=0;b<i;b++)R[e[a+b]]++;for(m=l,p=15;p>=1&&0===R[p];p--);if(m>p&&(m=p),0===p)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(g=1;g<p&&0===R[g];g++);for(m<g&&(m=g),y=1,w=1;w<=15;w++)if(y<<=1,y-=R[w],y<0)return-1;if(y>0&&(0===t||1!==p))return-1;for(Z[1]=0,w=1;w<15;w++)Z[w+1]=Z[w]+R[w];for(b=0;b<i;b++)0!==e[a+b]&&(r[Z[e[a+b]]++]=b);if(0===t?(A=O=r,u=19):1===t?(A=Qt,E-=257,O=Vt,T-=257,u=256):(A=$t,O=te,u=-1),z=0,b=0,w=g,c=s,k=m,v=0,_=-1,x=1<<m,f=x-1,1===t&&x>852||2===t&&x>592)return 1;for(;;){S=w-v,r[b]<u?(U=0,D=r[b]):r[b]>u?(U=O[T+r[b]],D=A[E+r[b]]):(U=96,D=0),h=1<<w-v,d=1<<k,g=d;do{d-=h,n[c+(z>>v)+d]=S<<24|U<<16|D|0}while(0!==d);for(h=1<<w-1;z&h;)h>>=1;if(0!==h?(z&=h-1,z+=h):z=0,b++,0==--R[w]){if(w===p)break;w=e[a+r[b]]}if(w>m&&(z&f)!==_){for(0===v&&(v=m),c+=g,k=w-v,y=1<<k;k+v<p&&(y-=R[k+v],!(y<=0));)k++,y<<=1;if(x+=1<<k,1===t&&x>852||2===t&&x>592)return 1;_=z&f,n[_]=m<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=m,0};const{Z_FINISH:ae,Z_BLOCK:ie,Z_TREES:ne,Z_OK:se,Z_STREAM_END:re,Z_NEED_DICT:oe,Z_STREAM_ERROR:le,Z_DATA_ERROR:he,Z_MEM_ERROR:de,Z_BUF_ERROR:_e,Z_DEFLATED:fe}=B,ce=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ue(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const we=t=>{if(!t||!t.state)return le;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg=\"\",e.wrap&&(t.adler=1&e.wrap),e.mode=1,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,se},be=t=>{if(!t||!t.state)return le;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,we(t)},ge=(t,e)=>{let a;if(!t||!t.state)return le;const i=t.state;return e<0?(a=0,e=-e):(a=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?le:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,be(t))},pe=(t,e)=>{if(!t)return le;const a=new ue;t.state=a,a.window=null;const i=ge(t,e);return i!==se&&(t.state=null),i};let me,ke,ve=!0;const ye=t=>{if(ve){me=new Int32Array(512),ke=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ee(1,t.lens,0,288,me,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ee(2,t.lens,0,32,ke,0,t.work,{bits:5}),ve=!1}t.lencode=me,t.lenbits=9,t.distcode=ke,t.distbits=5},xe=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0};var ze={inflateReset:be,inflateReset2:ge,inflateResetKeep:we,inflateInit:t=>pe(t,15),inflateInit2:pe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,b,g,p,m,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return le;a=t.state,12===a.mode&&(a.mode=13),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=se;t:for(;;)switch(a.mode){case 1:if(0===a.wrap){a.mode=13;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(2&a.wrap&&35615===h){a.check=0,A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0),h=0,d=0,a.mode=2;break}if(a.flags=0,a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg=\"incorrect header check\",a.mode=30;break}if((15&h)!==fe){t.msg=\"unknown compression method\",a.mode=30;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits)a.wbits=y;else if(y>a.wbits){t.msg=\"invalid window size\",a.mode=30;break}a.dmax=1<<a.wbits,t.adler=a.check=1,a.mode=512&h?10:12,h=0,d=0;break;case 2:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.flags=h,(255&a.flags)!==fe){t.msg=\"unknown compression method\",a.mode=30;break}if(57344&a.flags){t.msg=\"unknown header flags set\",a.mode=30;break}a.head&&(a.head.text=h>>8&1),512&a.flags&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0,a.mode=3;case 3:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.time=h),512&a.flags&&(A[0]=255&h,A[1]=h>>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=L(a.check,A,4,0)),h=0,d=0,a.mode=4;case 4:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.xflags=255&h,a.head.os=h>>8),512&a.flags&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0,a.mode=5;case 5:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length=h,a.head&&(a.head.extra_len=h),512&a.flags&&(A[0]=255&h,A[1]=h>>>8&255,a.check=L(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=6;case 6:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=7;case 7:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.name=null);a.length=0,a.mode=8;case 8:if(4096&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.comment+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&(a.check=L(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.comment=null);a.mode=9;case 9:if(512&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h!==(65535&a.check)){t.msg=\"header crc mismatch\",a.mode=30;break}h=0,d=0}a.head&&(a.head.hcrc=a.flags>>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=12;break;case 10:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}t.adler=a.check=ce(h),h=0,d=0,a.mode=11;case 11:if(0===a.havedict)return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,oe;t.adler=a.check=1,a.mode=12;case 12:if(e===ie||e===ne)break t;case 13:if(a.last){h>>>=7&d,d-=7&d,a.mode=27;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}switch(a.last=1&h,h>>>=1,d-=1,3&h){case 0:a.mode=14;break;case 1:if(ye(a),a.mode=20,e===ne){h>>>=2,d-=2;break t}break;case 2:a.mode=17;break;case 3:t.msg=\"invalid block type\",a.mode=30}h>>>=2,d-=2;break;case 14:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if((65535&h)!=(h>>>16^65535)){t.msg=\"invalid stored block lengths\",a.mode=30;break}if(a.length=65535&h,h=0,d=0,a.mode=15,e===ne)break t;case 15:a.mode=16;case 16:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=12;break;case 17:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.nlen=257+(31&h),h>>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg=\"too many length or distance symbols\",a.mode=30;break}a.have=0,a.mode=18;case 18:for(;a.have<a.ncode;){for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.lens[Z[a.have++]]=7&h,h>>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ee(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid code lengths set\",a.mode=30;break}a.have=0,a.mode=19;case 19:for(;a.have<a.nlen+a.ndist;){for(;z=a.lencode[h&(1<<a.lenbits)-1],b=z>>>24,g=z>>>16&255,p=65535&z,!(b<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(p<16)h>>>=b,d-=b,a.lens[a.have++]=p;else{if(16===p){for(R=b+2;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h>>>=b,d-=b,0===a.have){t.msg=\"invalid bit length repeat\",a.mode=30;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===p){for(R=b+3;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=b,d-=b,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=b+7;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=b,d-=b,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg=\"invalid bit length repeat\",a.mode=30;break}for(;c--;)a.lens[a.have++]=y}}if(30===a.mode)break;if(0===a.lens[256]){t.msg=\"invalid code -- missing end-of-block\",a.mode=30;break}if(a.lenbits=9,E={bits:a.lenbits},x=ee(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid literal/lengths set\",a.mode=30;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ee(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg=\"invalid distances set\",a.mode=30;break}if(a.mode=20,e===ne)break t;case 20:a.mode=21;case 21:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,qt(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,12===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<<a.lenbits)-1],b=z>>>24,g=z>>>16&255,p=65535&z,!(b<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(g&&0==(240&g)){for(m=b,k=g,v=p;z=a.lencode[v+((h&(1<<m+k)-1)>>m)],b=z>>>24,g=z>>>16&255,p=65535&z,!(m+b<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,a.back+=m}if(h>>>=b,d-=b,a.back+=b,a.length=p,0===g){a.mode=26;break}if(32&g){a.back=-1,a.mode=12;break}if(64&g){t.msg=\"invalid literal/length code\",a.mode=30;break}a.extra=15&g,a.mode=22;case 22:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=23;case 23:for(;z=a.distcode[h&(1<<a.distbits)-1],b=z>>>24,g=z>>>16&255,p=65535&z,!(b<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(0==(240&g)){for(m=b,k=g,v=p;z=a.distcode[v+((h&(1<<m+k)-1)>>m)],b=z>>>24,g=z>>>16&255,p=65535&z,!(m+b<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,a.back+=m}if(h>>>=b,d-=b,a.back+=b,64&g){t.msg=\"invalid distance code\",a.mode=30;break}a.offset=p,a.extra=15&g,a.mode=24;case 24:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.offset+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg=\"invalid distance too far back\",a.mode=30;break}a.mode=25;case 25:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg=\"invalid distance too far back\",a.mode=30;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=21);break;case 26:if(0===l)break t;n[r++]=a.length,l--,a.mode=21;break;case 27:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<<d,d+=8}if(f-=l,t.total_out+=f,a.total+=f,f&&(t.adler=a.check=a.flags?L(a.check,n,f,r-f):N(a.check,n,f,r-f)),f=l,(a.flags?h:ce(h))!==a.check){t.msg=\"incorrect data check\",a.mode=30;break}h=0,d=0}a.mode=28;case 28:if(a.wrap&&a.flags){for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h!==(4294967295&a.total)){t.msg=\"incorrect length check\",a.mode=30;break}h=0,d=0}a.mode=29;case 29:x=re;break t;case 30:x=he;break t;case 31:return de;default:return le}return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,(a.wsize||f!==t.avail_out&&a.mode<30&&(a.mode<27||e!==ae))&&xe(t,t.output,t.next_out,f-t.avail_out),_-=t.avail_in,f-=t.avail_out,t.total_in+=_,t.total_out+=f,a.total+=f,a.wrap&&f&&(t.adler=a.check=a.flags?L(a.check,n,f,t.next_out-f):N(a.check,n,f,t.next_out-f)),t.data_type=a.bits+(a.last?64:0)+(12===a.mode?128:0)+(20===a.mode||15===a.mode?256:0),(0===_&&0===f||e===ae)&&x===se&&(x=_e),x},inflateEnd:t=>{if(!t||!t.state)return le;let e=t.state;return e.window&&(e.window=null),t.state=null,se},inflateGetHeader:(t,e)=>{if(!t||!t.state)return le;const a=t.state;return 0==(2&a.wrap)?le:(a.head=e,e.done=!1,se)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return t&&t.state?(i=t.state,0!==i.wrap&&11!==i.mode?le:11===i.mode&&(n=1,n=N(n,e,a,0),n!==i.check)?he:(s=xe(t,e,a,a),s?(i.mode=31,de):(i.havedict=1,se))):le},inflateInfo:\"pako inflate (from Nodeca project)\"};var Ae=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const Ee=Object.prototype.toString,{Z_NO_FLUSH:Re,Z_FINISH:Ze,Z_OK:Se,Z_STREAM_END:Ue,Z_NEED_DICT:De,Z_STREAM_ERROR:Oe,Z_DATA_ERROR:Te,Z_MEM_ERROR:Ne}=B;function Fe(t){this.options=St({chunkSize:65536,windowBits:15,to:\"\"},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Lt,this.strm.avail_out=0;let a=ze.inflateInit2(this.strm,e.windowBits);if(a!==Se)throw new Error(I[a]);if(this.header=new Ae,ze.inflateGetHeader(this.strm,this.header),e.dictionary&&(\"string\"==typeof e.dictionary?e.dictionary=Tt(e.dictionary):\"[object ArrayBuffer]\"===Ee.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=ze.inflateSetDictionary(this.strm,e.dictionary),a!==Se)))throw new Error(I[a])}Fe.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Ze:Re,\"[object ArrayBuffer]\"===Ee.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=ze.inflate(a,r),s===De&&n&&(s=ze.inflateSetDictionary(a,n),s===Se?s=ze.inflate(a,r):s===Te&&(s=De));a.avail_in>0&&s===Ue&&a.state.wrap>0&&0!==t[a.next_in];)ze.inflateReset(a),s=ze.inflate(a,r);switch(s){case Oe:case Te:case De:case Ne:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Ue))if(\"string\"===this.options.to){let t=Ft(a.output,a.next_out),e=a.next_out-t,n=Nt(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Se||0!==o){if(s===Ue)return s=ze.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},Fe.prototype.onData=function(t){this.chunks.push(t)},Fe.prototype.onEnd=function(t){t===Se&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=Ut(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Le,deflate:Ie,deflateRaw:Be,gzip:Ce}=Wt;var He=Le,Me=B,je=new(function(){function t(){this.init()}return t.prototype.init=function(){this.added=0,this.deflate=new He,this.deflate.push(\"[\",Me.Z_NO_FLUSH)},t.prototype.addEvent=function(t){if(t){var e=this.added>0?\",\":\"\";this.deflate.push(e+JSON.stringify(t),Me.Z_NO_FLUSH),this.added++}},t.prototype.finish=function(){if(this.deflate.push(\"]\",Me.Z_FINISH),this.deflate.err)throw this.deflate.err;var t=this.deflate.result;return this.init(),t},t}()),Ke={init:function(){return je.init(),\"\"},addEvent:function(t){return je.addEvent(t),\"\"},finish:function(){return je.finish()}};addEventListener(\"message\",(function(t){var e=t.data.method,a=t.data.id,i=(t.data.args?JSON.parse(t.data.args):[])[0];if(e in Ke&&\"function\"==typeof Ke[e])try{var n=Ke[e](i);postMessage({id:a,method:e,success:!0,response:n})}catch(t){postMessage({id:a,method:e,success:!1,response:t}),console.error(t)}}));`;\n\nfunction createEventBuffer(_a) {\n var useCompression = _a.useCompression;\n if (useCompression && window.Worker) {\n var workerBlob = new Blob([workerString]);\n var workerUrl = URL.createObjectURL(workerBlob);\n try {\n logger.log('Using compression worker');\n var worker = new Worker(workerUrl);\n if (worker) {\n return new EventBufferCompressionWorker(worker);\n }\n else {\n captureException(new Error('Unable to create compression worker'));\n }\n }\n catch (_b) {\n // catch and ignore, fallback to simple event buffer\n }\n logger.log('Falling back to simple event buffer');\n }\n logger.log('Using simple buffer');\n return new EventBufferArray();\n}\nvar EventBufferArray = /** @class */ (function () {\n function EventBufferArray() {\n this.events = [];\n }\n EventBufferArray.prototype.destroy = function () {\n this.events = [];\n };\n Object.defineProperty(EventBufferArray.prototype, \"length\", {\n get: function () {\n return this.events.length;\n },\n enumerable: false,\n configurable: true\n });\n EventBufferArray.prototype.addEvent = function (event, isCheckout) {\n if (isCheckout) {\n this.events = [event];\n return;\n }\n this.events.push(event);\n };\n EventBufferArray.prototype.finish = function () {\n var _this = this;\n return new Promise(function (resolve) {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n var eventsRet = _this.events;\n _this.events = [];\n resolve(JSON.stringify(eventsRet));\n });\n };\n return EventBufferArray;\n}());\n// exporting for testing\nvar EventBufferCompressionWorker = /** @class */ (function () {\n function EventBufferCompressionWorker(worker) {\n var _this = this;\n this.eventBufferItemLength = 0;\n this._id = 0;\n this.sendEventToWorker = function (event) {\n var promise = _this.postMessage({\n id: _this.id,\n method: 'addEvent',\n args: [event],\n });\n // XXX: See note in `get length()`\n _this.eventBufferItemLength++;\n return promise;\n };\n this.finishRequest = function (id) { return __awaiter(_this, void 0, void 0, function () {\n var promise;\n return __generator(this, function (_a) {\n promise = this.postMessage({ id: id, method: 'finish', args: [] });\n // XXX: See note in `get length()`\n this.eventBufferItemLength = 0;\n return [2 /*return*/, promise];\n });\n }); };\n this.worker = worker;\n }\n Object.defineProperty(EventBufferCompressionWorker.prototype, \"id\", {\n /**\n * Read-only incrementing counter\n */\n get: function () {\n return this._id++;\n },\n enumerable: false,\n configurable: true\n });\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n EventBufferCompressionWorker.prototype.postMessage = function (_a) {\n var _this = this;\n var id = _a.id, method = _a.method, args = _a.args;\n return new Promise(function (resolve, reject) {\n var _a, _b;\n var listener = function (_a) {\n var _b;\n var data = _a.data;\n if (data.method !== method) {\n return;\n }\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (data.id !== id) {\n return;\n }\n // At this point, we'll always want to remove listener regardless of result status\n (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.removeEventListener('message', listener);\n if (!data.success) {\n // TODO: Do some error handling, not sure what\n logger.error(data.response);\n reject(new Error('Error in compression worker'));\n return;\n }\n resolve(data.response);\n };\n var stringifiedArgs;\n try {\n stringifiedArgs = JSON.stringify(args);\n }\n catch (err) {\n console.error(err);\n stringifiedArgs = '[]';\n }\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n (_a = _this.worker) === null || _a === void 0 ? void 0 : _a.addEventListener('message', listener);\n (_b = _this.worker) === null || _b === void 0 ? void 0 : _b.postMessage({ id: id, method: method, args: stringifiedArgs });\n });\n };\n EventBufferCompressionWorker.prototype.init = function () {\n this.postMessage({ id: this.id, method: 'init', args: [] });\n logger.log('Initialized compression worker');\n };\n EventBufferCompressionWorker.prototype.destroy = function () {\n var _a;\n logger.log('Destroying compression worker');\n (_a = this.worker) === null || _a === void 0 ? void 0 : _a.terminate();\n this.worker = null;\n };\n Object.defineProperty(EventBufferCompressionWorker.prototype, \"length\", {\n /**\n * Note that this may not reflect what is actually in the event buffer. This\n * is only a local count of the buffer size since `addEvent` is async.\n */\n get: function () {\n return this.eventBufferItemLength;\n },\n enumerable: false,\n configurable: true\n });\n EventBufferCompressionWorker.prototype.addEvent = function (event, isCheckout) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!isCheckout) return [3 /*break*/, 2];\n // This event is a checkout, make sure worker buffer is cleared before\n // proceeding.\n return [4 /*yield*/, this.postMessage({\n id: this.id,\n method: 'init',\n args: [],\n })];\n case 1:\n // This event is a checkout, make sure worker buffer is cleared before\n // proceeding.\n _a.sent();\n _a.label = 2;\n case 2: return [2 /*return*/, this.sendEventToWorker(event)];\n }\n });\n });\n };\n EventBufferCompressionWorker.prototype.finish = function () {\n return this.finishRequest(this.id);\n };\n return EventBufferCompressionWorker;\n}());\n\nvar BASE_RETRY_INTERVAL = 5000;\nvar MAX_RETRY_COUNT = 3;\nvar UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\nvar MEDIA_SELECTORS = 'img,image,svg,path,rect,area,video,object,picture,embed,map,audio';\nvar _initialized = false;\nvar isBrowser = typeof window !== 'undefined';\nvar Replay = /** @class */ (function () {\n function Replay(_a) {\n if (_a === void 0) { _a = {}; }\n var _this = this;\n var _b = _a.flushMinDelay, flushMinDelay = _b === void 0 ? 5000 : _b, _c = _a.flushMaxDelay, flushMaxDelay = _c === void 0 ? 15000 : _c, _d = _a.initialFlushDelay, initialFlushDelay = _d === void 0 ? 5000 : _d, _e = _a.stickySession, stickySession = _e === void 0 ? true : _e, _f = _a.useCompression, useCompression = _f === void 0 ? true : _f, _g = _a.sessionSampleRate, sessionSampleRate = _g === void 0 ? DEFAULT_SESSION_SAMPLE_RATE : _g, _h = _a.errorSampleRate, errorSampleRate = _h === void 0 ? DEFAULT_ERROR_SAMPLE_RATE : _h, _j = _a.maskAllText, maskAllText = _j === void 0 ? true : _j, _k = _a.maskAllInputs, maskAllInputs = _k === void 0 ? true : _k, _l = _a.blockAllMedia, blockAllMedia = _l === void 0 ? true : _l, _m = _a.blockClass, blockClass = _m === void 0 ? 'sentry-block' : _m, _o = _a.ignoreClass, ignoreClass = _o === void 0 ? 'sentry-ignore' : _o, _p = _a.maskTextClass, maskTextClass = _p === void 0 ? 'sentry-mask' : _p, _q = _a.blockSelector, blockSelector = _q === void 0 ? '[data-sentry-block]' : _q, replaysSamplingRate = _a.replaysSamplingRate, captureOnlyOnError = _a.captureOnlyOnError, recordingOptions = __rest(_a, [\"flushMinDelay\", \"flushMaxDelay\", \"initialFlushDelay\", \"stickySession\", \"useCompression\", \"sessionSampleRate\", \"errorSampleRate\", \"maskAllText\", \"maskAllInputs\", \"blockAllMedia\", \"blockClass\", \"ignoreClass\", \"maskTextClass\", \"blockSelector\", \"replaysSamplingRate\", \"captureOnlyOnError\"]);\n /**\n * @inheritDoc\n */\n this.name = Replay.id;\n /**\n * List of PerformanceEntry from PerformanceObserver\n */\n this.performanceEvents = [];\n this.performanceObserver = null;\n this.retryCount = 0;\n this.retryInterval = BASE_RETRY_INTERVAL;\n this.flushLock = null;\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n this.lastActivity = new Date().getTime();\n /**\n * Is the integration currently active?\n */\n this.isEnabled = false;\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n this.isPaused = false;\n /**\n * Integration will wait until an error occurs before creating and sending a\n * replay.\n */\n this.waitForError = false;\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n this.hasInitializedCoreListeners = false;\n /**\n * Function to stop recording\n */\n this.stopRecording = null;\n this.context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n earliestEvent: null,\n initialTimestamp: new Date().getTime(),\n initialUrl: '',\n };\n /**\n * Core Sentry SDK global event handler. Attaches `replayId` to all [non-replay]\n * events as a tag. Also handles the case where we only want to capture a reply\n * when an error occurs.\n **/\n this.handleGlobalEvent = function (event) {\n var _a, _b, _c, _d, _e;\n // Do not apply replayId to the root event\n if (\n // @ts-expect-error new event type\n event.type === REPLAY_EVENT_NAME) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n // Only tag transactions with replayId if not waiting for an error\n if (event.type !== 'transaction' || !_this.waitForError) {\n event.tags = __assign(__assign({}, event.tags), { replayId: (_a = _this.session) === null || _a === void 0 ? void 0 : _a.id });\n }\n // Collect traceIds in context regardless of `waitForError` - if it's true,\n // context gets cleared on every checkout\n if (event.type === 'transaction') {\n _this.context.traceIds.add(String(((_c = (_b = event.contexts) === null || _b === void 0 ? void 0 : _b.trace) === null || _c === void 0 ? void 0 : _c.trace_id) || ''));\n return event;\n }\n // XXX: Is it safe to assume that all other events are error events?\n // @ts-expect-error: Type 'undefined' is not assignable to type 'string'.ts(2345)\n _this.context.errorIds.add(event.event_id);\n var exc = (_e = (_d = event.exception) === null || _d === void 0 ? void 0 : _d.values) === null || _e === void 0 ? void 0 : _e[0];\n addInternalBreadcrumb({\n message: \"Tagging event (\".concat(event.event_id, \") - \").concat(event.message, \" - \").concat((exc === null || exc === void 0 ? void 0 : exc.type) || 'Unknown', \": \").concat((exc === null || exc === void 0 ? void 0 : exc.value) || 'n/a'),\n });\n // Need to be very careful that this does not cause an infinite loop\n if (_this.waitForError &&\n event.exception &&\n event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing\n ) {\n setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: \n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n return [4 /*yield*/, this.flushImmediate()];\n case 1:\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n _a.sent();\n if (this.stopRecording) {\n this.stopRecording();\n // Reset all \"capture on error\" configuration before\n // starting a new recording\n delete this.recordingOptions.checkoutEveryNms;\n this.waitForError = false;\n this.startRecording();\n }\n return [2 /*return*/];\n }\n });\n }); });\n }\n return event;\n };\n /**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\n this.handleRecordingEmit = function (event, isCheckout) {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!_this.checkAndHandleExpiredSession()) {\n logger.error(new Error('Received replay event after session expired.'));\n return;\n }\n _this.addUpdate(function () {\n var _a, _b;\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (_this.waitForError && event.type === 2) {\n _this.setInitialState();\n }\n // We need to clear existing events on a checkout, otherwise they are\n // incremental event updates and should be appended\n _this.addEvent(event, isCheckout);\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (event.type !== 2) {\n return false;\n }\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if ((_a = _this.session) === null || _a === void 0 ? void 0 : _a.previousSessionId) {\n return true;\n }\n // See note above re: session start needs to reflect the most recent\n // checkout.\n if (_this.waitForError && _this.session && _this.context.earliestEvent) {\n _this.session.started = _this.context.earliestEvent;\n }\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n setTimeout(function () { return _this.conditionalFlush(); }, _this.options.initialFlushDelay);\n // Cancel any previously debounced flushes to ensure there are no [near]\n // simultaneous flushes happening. The latter request should be\n // insignificant in this case, so wait for additional user interaction to\n // trigger a new flush.\n //\n // This can happen because there's no guarantee that a recording event\n // happens first. e.g. a mouse click can happen and trigger a debounced\n // flush before the checkout.\n (_b = _this.debouncedFlush) === null || _b === void 0 ? void 0 : _b.cancel();\n return true;\n });\n };\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n this.handleVisibilityChange = function () {\n if (document.visibilityState === 'visible') {\n _this.doChangeToForegroundTasks();\n }\n else {\n _this.doChangeToBackgroundTasks();\n }\n };\n /**\n * Handle when page is blurred\n */\n this.handleWindowBlur = function () {\n var breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n _this.doChangeToBackgroundTasks(breadcrumb);\n };\n /**\n * Handle when page is focused\n */\n this.handleWindowFocus = function () {\n var breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n _this.doChangeToForegroundTasks(breadcrumb);\n };\n /**\n * Handler for Sentry Core SDK events.\n *\n * These specific events will create span-like objects in the recording.\n */\n this.handleCoreSpanListener = function (type) { return function (handlerData) {\n if (!_this.isEnabled) {\n return;\n }\n var handler = getSpanHandler(type);\n var result = handler(handlerData);\n if (result === null) {\n return;\n }\n if (type === 'history') {\n // Need to collect visited URLs\n _this.context.urls.push(result.name);\n _this.triggerUserActivity();\n }\n _this.addUpdate(function () {\n _this.createPerformanceSpans([result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return ['xhr', 'fetch'].includes(type);\n });\n }; };\n /**\n * Handler for Sentry Core SDK events.\n *\n * These events will create breadcrumb-like objects in the recording.\n */\n this.handleCoreBreadcrumbListener = function (type) { return function (handlerData) {\n if (!_this.isEnabled) {\n return;\n }\n var handler = getBreadcrumbHandler(type);\n var result = handler(handlerData);\n if (result === null) {\n return;\n }\n if (result.category === 'sentry.transaction') {\n return;\n }\n if (result.category === 'ui.click') {\n _this.triggerUserActivity();\n }\n else {\n _this.checkAndHandleExpiredSession();\n }\n _this.addUpdate(function () {\n _this.addEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (result.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n payload: result,\n },\n });\n // Do not flush after console log messages\n return result.category === 'console';\n });\n }; };\n /**\n * Keep a list of performance entries that will be sent with a replay\n */\n this.handlePerformanceObserver = function (list) {\n // For whatever reason the observer was returning duplicate navigation\n // entries (the other entry types were not duplicated).\n var newPerformanceEntries = dedupePerformanceEntries(_this.performanceEvents, list.getEntries());\n _this.performanceEvents = newPerformanceEntries;\n };\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n this.flush = function () { return __awaiter(_this, void 0, void 0, function () {\n var err_1;\n var _a, _b;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n if (!this.isEnabled) {\n // This is just a precaution, there should be no listeners that would\n // cause a flush.\n return [2 /*return*/];\n }\n if (!this.checkAndHandleExpiredSession()) {\n logger.error(new Error('Attempting to finish replay event after session expired.'));\n return [2 /*return*/];\n }\n if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.id)) {\n console.error(new Error('[Sentry]: No transaction, no replay'));\n return [2 /*return*/];\n }\n // A flush is about to happen, cancel any queued flushes\n (_b = this.debouncedFlush) === null || _b === void 0 ? void 0 : _b.cancel();\n if (!!this.flushLock) return [3 /*break*/, 2];\n this.flushLock = this.runFlush();\n return [4 /*yield*/, this.flushLock];\n case 1:\n _c.sent();\n this.flushLock = null;\n return [2 /*return*/];\n case 2:\n _c.trys.push([2, 4, 5, 6]);\n return [4 /*yield*/, this.flushLock];\n case 3:\n _c.sent();\n return [3 /*break*/, 6];\n case 4:\n err_1 = _c.sent();\n console.error(err_1);\n return [3 /*break*/, 6];\n case 5:\n this.debouncedFlush();\n return [7 /*endfinally*/];\n case 6: return [2 /*return*/];\n }\n });\n }); };\n this.recordingOptions = __assign({ maskAllInputs: maskAllInputs, blockClass: blockClass, ignoreClass: ignoreClass, maskTextClass: maskTextClass, blockSelector: blockSelector }, recordingOptions);\n var usingDeprecatedReplaysSamplingRate = replaysSamplingRate !== undefined;\n var usingDeprecatedCaptureOnlyOnError = captureOnlyOnError !== undefined;\n this.options = {\n flushMinDelay: flushMinDelay,\n flushMaxDelay: flushMaxDelay,\n stickySession: stickySession,\n initialFlushDelay: initialFlushDelay,\n sessionSampleRate: usingDeprecatedReplaysSamplingRate\n ? replaysSamplingRate\n : sessionSampleRate,\n errorSampleRate: usingDeprecatedCaptureOnlyOnError\n ? 1.0\n : errorSampleRate,\n useCompression: useCompression,\n maskAllText: maskAllText,\n blockAllMedia: blockAllMedia,\n };\n // TODO(deprecated): Maintain backwards compatibility for alpha users\n if (usingDeprecatedCaptureOnlyOnError) {\n console.warn('[@sentry/replay]: The `captureOnlyOnError` option is deprecated! Please configure `errorSampleRate` instead.');\n }\n if (usingDeprecatedReplaysSamplingRate) {\n console.warn('[@sentry/replay]: The `replaysSamplingRate` option is deprecated! Please configure `sessionSampleRate` instead.');\n }\n if (this.options.maskAllText) {\n // `maskAllText` is a more user friendly option to configure\n // `maskTextSelector`. This means that all nodes will have their text\n // content masked.\n this.recordingOptions.maskTextSelector = '*';\n }\n if (this.options.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this.recordingOptions.blockSelector = !this.recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : \"\".concat(this.recordingOptions.blockSelector, \",\").concat(MEDIA_SELECTORS);\n }\n this.debouncedFlush = debounce(function () { return _this.flush(); }, this.options.flushMinDelay, {\n maxWait: this.options.flushMaxDelay,\n });\n if (isBrowser && _initialized) {\n var error = new Error('Multiple Sentry Session Replay instances are not supported');\n captureInternalException(error);\n throw error;\n }\n _initialized = true;\n }\n /**\n * We previously used to create a transaction in `setupOnce` and it would\n * potentially create a transaction before some native SDK integrations have run\n * and applied their own global event processor. An example is:\n * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n *\n * So we call `this.setup` in next event loop as a workaround to wait for other\n * global event processors to finish. This is no longer needed, but keeping it\n * here to avoid any future issues.\n */\n Replay.prototype.setupOnce = function () {\n var _this = this;\n if (!isBrowser) {\n return;\n }\n // XXX: See method comments above\n window.setTimeout(function () { return _this.start(); });\n };\n /**\n * Initializes the plugin.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n Replay.prototype.start = function () {\n if (!isBrowser) {\n return;\n }\n this.setInitialState();\n this.loadSession({ expiry: SESSION_IDLE_DURATION });\n // If there is no session, then something bad has happened - can't continue\n if (!this.session) {\n captureInternalException(new Error('Invalid session'));\n return;\n }\n if (!this.session.sampled) {\n // If session was not sampled, then we do not initialize the integration at all.\n return;\n }\n // Modify recording options to checkoutEveryNthSecond if\n // sampling for error replay. This is because we don't know\n // when an error will occur, so we need to keep a buffer of\n // replay events.\n if (this.session.sampled === 'error') {\n // Checkout every minute, meaning we only get up-to one minute of events before the error happens\n this.recordingOptions.checkoutEveryNms = 60000;\n this.waitForError = true;\n }\n // setup() is generally called on page load or manually - in both cases we\n // should treat it as an activity\n this.updateSessionActivity();\n this.eventBuffer = createEventBuffer({\n useCompression: Boolean(this.options.useCompression),\n });\n this.addListeners();\n this.startRecording();\n this.isEnabled = true;\n };\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n Replay.prototype.startRecording = function () {\n try {\n this.stopRecording = record(__assign(__assign({}, this.recordingOptions), { emit: this.handleRecordingEmit }));\n }\n catch (err) {\n logger.error(err);\n captureInternalException(err);\n }\n };\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n Replay.prototype.stop = function () {\n var _a, _b;\n if (!isBrowser) {\n return;\n }\n try {\n logger.log('Stopping Replays');\n this.isEnabled = false;\n this.removeListeners();\n (_a = this.stopRecording) === null || _a === void 0 ? void 0 : _a.call(this);\n (_b = this.eventBuffer) === null || _b === void 0 ? void 0 : _b.destroy();\n this.eventBuffer = null;\n }\n catch (err) {\n logger.error(err);\n captureInternalException(err);\n }\n };\n /**\n * Pause some replay functionality. See comments for `isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n Replay.prototype.pause = function () {\n this.isPaused = true;\n try {\n if (this.stopRecording) {\n this.stopRecording();\n this.stopRecording = undefined;\n }\n }\n catch (err) {\n logger.error(err);\n captureInternalException(err);\n }\n };\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n Replay.prototype.resume = function () {\n this.isPaused = false;\n this.startRecording();\n };\n Replay.prototype.clearSession = function () {\n try {\n deleteSession();\n this.session = undefined;\n }\n catch (err) {\n logger.error(err);\n captureInternalException(err);\n }\n };\n /**\n * Loads a session from storage, or creates a new one if it does not exist or\n * is expired.\n */\n Replay.prototype.loadSession = function (_a) {\n var _b, _c;\n var expiry = _a.expiry;\n var _d = getSession({\n expiry: expiry,\n stickySession: Boolean(this.options.stickySession),\n currentSession: this.session,\n sessionSampleRate: this.options.sessionSampleRate,\n errorSampleRate: this.options.errorSampleRate,\n }), type = _d.type, session = _d.session;\n // If session was newly created (i.e. was not loaded from storage), then\n // enable flag to create the root replay\n if (type === 'new') {\n this.setInitialState();\n }\n if (session.id !== ((_b = this.session) === null || _b === void 0 ? void 0 : _b.id)) {\n session.previousSessionId = (_c = this.session) === null || _c === void 0 ? void 0 : _c.id;\n }\n this.session = session;\n };\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n Replay.prototype.setInitialState = function () {\n var urlPath = \"\".concat(window.location.pathname).concat(window.location.hash).concat(window.location.search);\n var url = \"\".concat(window.location.origin).concat(urlPath);\n this.performanceEvents = [];\n // Reset context as well\n this.clearContext();\n this.context.initialUrl = url;\n this.context.initialTimestamp = new Date().getTime();\n this.context.urls.push(url);\n };\n /**\n * Adds listeners to record events for the replay\n */\n Replay.prototype.addListeners = function () {\n var _this = this;\n try {\n document.addEventListener('visibilitychange', this.handleVisibilityChange);\n window.addEventListener('blur', this.handleWindowBlur);\n window.addEventListener('focus', this.handleWindowFocus);\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this.hasInitializedCoreListeners) {\n // Listeners from core SDK //\n var scope = getCurrentHub().getScope();\n scope === null || scope === void 0 ? void 0 : scope.addScopeListener(this.handleCoreBreadcrumbListener('scope'));\n addInstrumentationHandler('dom', this.handleCoreBreadcrumbListener('dom'));\n addInstrumentationHandler('fetch', this.handleCoreSpanListener('fetch'));\n addInstrumentationHandler('xhr', this.handleCoreSpanListener('xhr'));\n addInstrumentationHandler('history', this.handleCoreSpanListener('history'));\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n addGlobalEventProcessor(this.handleGlobalEvent);\n this.hasInitializedCoreListeners = true;\n }\n }\n catch (err) {\n logger.error(err);\n captureInternalException(err);\n }\n // PerformanceObserver //\n if (!('PerformanceObserver' in window)) {\n return;\n }\n this.performanceObserver = new PerformanceObserver(this.handlePerformanceObserver);\n // Observe almost everything for now (no mark/measure)\n [\n 'element',\n 'event',\n 'first-input',\n 'largest-contentful-paint',\n 'layout-shift',\n 'longtask',\n 'navigation',\n 'paint',\n 'resource',\n ].forEach(function (type) {\n var _a;\n try {\n (_a = _this.performanceObserver) === null || _a === void 0 ? void 0 : _a.observe({\n type: type,\n buffered: true,\n });\n }\n catch (_b) {\n // This can throw if an entry type is not supported in the browser.\n // Ignore these errors.\n }\n });\n };\n /**\n * Cleans up listeners that were created in `addListeners`\n */\n Replay.prototype.removeListeners = function () {\n try {\n document.removeEventListener('visibilitychange', this.handleVisibilityChange);\n window.removeEventListener('blur', this.handleWindowBlur);\n window.removeEventListener('focus', this.handleWindowFocus);\n if (this.performanceObserver) {\n this.performanceObserver.disconnect();\n this.performanceObserver = null;\n }\n }\n catch (err) {\n logger.error(err);\n captureInternalException(err);\n }\n };\n /**\n * We want to batch uploads of replay events. Save events only if\n * `<flushMinDelay>` milliseconds have elapsed since the last event\n * *OR* if `<flushMaxDelay>` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n Replay.prototype.addUpdate = function (cb) {\n // We need to always run `cb` (e.g. in the case of `this.waitForError == true`)\n var cbResult = cb === null || cb === void 0 ? void 0 : cb();\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.waitForError) {\n return;\n }\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n // addUpdate is called quite frequently - use debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this.debouncedFlush();\n };\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n Replay.prototype.doChangeToBackgroundTasks = function (breadcrumb) {\n if (!this.session) {\n return;\n }\n var expired = isSessionExpired(this.session, VISIBILITY_CHANGE_TIMEOUT);\n if (breadcrumb && !expired) {\n this.createCustomBreadcrumb(breadcrumb);\n }\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n this.conditionalFlush();\n };\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n Replay.prototype.doChangeToForegroundTasks = function (breadcrumb) {\n if (!this.session) {\n return;\n }\n var isSessionActive = this.checkAndHandleExpiredSession({\n expiry: VISIBILITY_CHANGE_TIMEOUT,\n });\n if (!isSessionActive) {\n // If the user has come back to the page within VISIBILITY_CHANGE_TIMEOUT\n // ms, we will re-use the existing session, otherwise create a new\n // session\n logger.log('Document has become active, but session has expired');\n return;\n }\n if (breadcrumb) {\n this.createCustomBreadcrumb(breadcrumb);\n }\n };\n /**\n * Trigger rrweb to take a full snapshot which will cause this plugin to\n * create a new Replay event.\n */\n Replay.prototype.triggerFullSnapshot = function () {\n logger.log('Taking full rrweb snapshot');\n record.takeFullSnapshot(true);\n };\n /**\n * Add an event to the event buffer\n */\n Replay.prototype.addEvent = function (event, isCheckout) {\n var _a;\n if (!this.eventBuffer) {\n // This implies that `isEnabled` is false\n return;\n }\n if (this.isPaused) {\n // Do not add to event buffer when recording is paused\n return;\n }\n // TODO: sadness -- we will want to normalize timestamps to be in ms -\n // requires coordination with frontend\n var isMs = event.timestamp > 9999999999;\n var timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + SESSION_IDLE_DURATION < new Date().getTime()) {\n return;\n }\n // Only record earliest event if a new session was created, otherwise it\n // shouldn't be relevant\n if (((_a = this.session) === null || _a === void 0 ? void 0 : _a.segmentId) === 0 &&\n (!this.context.earliestEvent ||\n timestampInMs < this.context.earliestEvent)) {\n this.context.earliestEvent = timestampInMs;\n }\n this.eventBuffer.addEvent(event, isCheckout);\n };\n /**\n * Update user activity (across session lifespans)\n */\n Replay.prototype.updateUserActivity = function (lastActivity) {\n if (lastActivity === void 0) { lastActivity = new Date().getTime(); }\n this.lastActivity = lastActivity;\n };\n /**\n * Updates the session's last activity timestamp\n */\n Replay.prototype.updateSessionActivity = function (lastActivity) {\n if (lastActivity === void 0) { lastActivity = new Date().getTime(); }\n if (this.session) {\n this.session.lastActivity = lastActivity;\n }\n };\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n Replay.prototype.triggerUserActivity = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n this.updateUserActivity();\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this.stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n this.loadSession({ expiry: SESSION_IDLE_DURATION });\n // Note: This will cause a new DOM checkout\n this.resume();\n return [2 /*return*/];\n }\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n this.updateSessionActivity();\n return [2 /*return*/];\n });\n });\n };\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n Replay.prototype.createCustomBreadcrumb = function (breadcrumb) {\n var _this = this;\n this.addUpdate(function () {\n _this.addEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n };\n /**\n * Create a \"span\" for each performance entry. The parent transaction is `this.replayEvent`.\n */\n Replay.prototype.createPerformanceSpans = function (entries) {\n var _this = this;\n return Promise.all(entries.map(function (_a) {\n var type = _a.type, start = _a.start, end = _a.end, name = _a.name, data = _a.data;\n return _this.addEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data: data,\n },\n },\n });\n }));\n };\n /**\n * Observed performance events are added to `this.performanceEvents`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n Replay.prototype.addPerformanceEntries = function () {\n // Copy and reset entries before processing\n var entries = __spreadArray([], this.performanceEvents, true);\n this.performanceEvents = [];\n return this.createPerformanceSpans(createPerformanceEntries(entries));\n };\n /**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\n Replay.prototype.addMemoryEntry = function () {\n // window.performance.memory is a non-standard API and doesn't work on all browsers\n // so we check before creating the event.\n if (!('memory' in window.performance)) {\n return;\n }\n return this.createPerformanceSpans([\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(window.performance.memory),\n ]);\n };\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n */\n Replay.prototype.checkAndHandleExpiredSession = function (_a) {\n var _b, _c;\n var _d = _a === void 0 ? {} : _a, _e = _d.expiry, expiry = _e === void 0 ? SESSION_IDLE_DURATION : _e;\n var oldSessionId = (_b = this.session) === null || _b === void 0 ? void 0 : _b.id;\n // Prevent starting a new session if the last user activity is older than\n // MAX_SESSION_LIFE. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (this.lastActivity && isExpired(this.lastActivity, MAX_SESSION_LIFE)) {\n // Pause recording\n this.pause();\n return;\n }\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n this.loadSession({ expiry: expiry });\n // Session was expired if session ids do not match\n var expired = oldSessionId !== ((_c = this.session) === null || _c === void 0 ? void 0 : _c.id);\n if (!expired) {\n return true;\n }\n // Session is expired, trigger a full snapshot (which will create a new session)\n this.triggerFullSnapshot();\n return false;\n };\n /**\n * Only flush if `this.waitForError` is false.\n */\n Replay.prototype.conditionalFlush = function () {\n if (this.waitForError) {\n return;\n }\n this.flushImmediate();\n };\n /**\n * Clear context\n */\n Replay.prototype.clearContext = function () {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this.context.errorIds.clear();\n this.context.traceIds.clear();\n this.context.urls = [];\n this.context.earliestEvent = null;\n };\n /**\n * Return and clear context\n */\n Replay.prototype.popEventContext = function () {\n if (this.context.earliestEvent &&\n this.context.earliestEvent < this.context.initialTimestamp) {\n this.context.initialTimestamp = this.context.earliestEvent;\n }\n var context = {\n initialTimestamp: this.context.initialTimestamp,\n initialUrl: this.context.initialUrl,\n errorIds: Array.from(this.context.errorIds).filter(Boolean),\n traceIds: Array.from(this.context.traceIds).filter(Boolean),\n urls: this.context.urls,\n };\n this.clearContext();\n return context;\n };\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n Replay.prototype.runFlush = function () {\n var _a;\n return __awaiter(this, void 0, void 0, function () {\n var recordingData, replayId, eventContext, segmentId, err_2;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n if (!this.session) {\n console.error(new Error('[Sentry]: No transaction, no replay'));\n return [2 /*return*/];\n }\n return [4 /*yield*/, this.addPerformanceEntries()];\n case 1:\n _b.sent();\n if (!((_a = this.eventBuffer) === null || _a === void 0 ? void 0 : _a.length)) {\n return [2 /*return*/];\n }\n // Only attach memory event if eventBuffer is not empty\n return [4 /*yield*/, this.addMemoryEntry()];\n case 2:\n // Only attach memory event if eventBuffer is not empty\n _b.sent();\n _b.label = 3;\n case 3:\n _b.trys.push([3, 6, , 7]);\n return [4 /*yield*/, this.eventBuffer.finish()];\n case 4:\n recordingData = _b.sent();\n replayId = this.session.id;\n eventContext = this.popEventContext();\n segmentId = this.session.segmentId++;\n return [4 /*yield*/, this.sendReplay({\n replayId: replayId,\n events: recordingData,\n segmentId: segmentId,\n includeReplayStartTimestamp: segmentId === 0,\n eventContext: eventContext,\n })];\n case 5:\n _b.sent();\n return [3 /*break*/, 7];\n case 6:\n err_2 = _b.sent();\n captureInternalException(err_2);\n console.error(err_2);\n return [3 /*break*/, 7];\n case 7: return [2 /*return*/];\n }\n });\n });\n };\n /**\n *\n * Always flush via `debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n Replay.prototype.flushImmediate = function () {\n this.debouncedFlush();\n // `.flush` is provided by lodash.debounce\n return this.debouncedFlush.flush();\n };\n /**\n * Send replay attachment using `fetch()`\n */\n Replay.prototype.sendReplayRequest = function (_a) {\n var _b;\n var events = _a.events, event_id = _a.replayId, segment_id = _a.segmentId, includeReplayStartTimestamp = _a.includeReplayStartTimestamp, eventContext = _a.eventContext;\n return __awaiter(this, void 0, void 0, function () {\n var payloadWithSequence, urls, errorIds, traceIds, initialTimestamp, currentTimestamp, sdkInfo, replayEvent, envelope, client;\n var _this = this;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n payloadWithSequence = createPayload({\n events: events,\n headers: {\n segment_id: segment_id,\n },\n });\n urls = eventContext.urls, errorIds = eventContext.errorIds, traceIds = eventContext.traceIds, initialTimestamp = eventContext.initialTimestamp;\n currentTimestamp = new Date().getTime();\n sdkInfo = {\n name: 'sentry.javascript.integration.replay',\n version: \"0.6.14\",\n };\n return [4 /*yield*/, new Promise(function (resolve) {\n var _a;\n (_a = getCurrentHub()) === null || _a === void 0 ? void 0 : _a._withClient(function (client, scope) { return __awaiter(_this, void 0, void 0, function () {\n var preparedEvent, session;\n var _a;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, client._prepareEvent(__assign(__assign({ type: REPLAY_EVENT_NAME }, (includeReplayStartTimestamp\n ? { replay_start_timestamp: initialTimestamp / 1000 }\n : {})), { timestamp: currentTimestamp / 1000, error_ids: errorIds, trace_ids: traceIds, urls: urls, replay_id: event_id, segment_id: segment_id }), { event_id: event_id }, scope)];\n case 1:\n preparedEvent = _b.sent();\n session = scope && scope.getSession();\n if (session) {\n client._updateSessionFromEvent(session, preparedEvent);\n }\n preparedEvent.sdk = __assign(__assign({}, preparedEvent.sdk), sdkInfo);\n preparedEvent.tags = __assign(__assign({}, preparedEvent.tags), { sessionSampleRate: this.options.sessionSampleRate, errorSampleRate: this.options.errorSampleRate, replayType: (_a = this.session) === null || _a === void 0 ? void 0 : _a.sampled });\n resolve(preparedEvent);\n return [2 /*return*/];\n }\n });\n }); });\n })];\n case 1:\n replayEvent = _c.sent();\n envelope = createEnvelope({\n event_id: event_id,\n sent_at: new Date().toISOString(),\n sdk: sdkInfo,\n }, [\n // @ts-expect-error New types\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n // @ts-expect-error setting envelope\n type: 'replay_recording',\n length: payloadWithSequence.length,\n },\n // @ts-expect-error: Type 'string' is not assignable to type 'ClientReport'.ts(2322)\n payloadWithSequence,\n ],\n ]);\n client = getCurrentHub().getClient();\n try {\n return [2 /*return*/, (_b = client === null || client === void 0 ? void 0 : client.getTransport()) === null || _b === void 0 ? void 0 : _b.send(envelope)];\n }\n catch (_d) {\n throw new Error(UNABLE_TO_SEND_REPLAY);\n }\n return [2 /*return*/];\n }\n });\n });\n };\n Replay.prototype.resetRetries = function () {\n this.retryCount = 0;\n this.retryInterval = BASE_RETRY_INTERVAL;\n };\n /**\n * Finalize and send the current replay event to Sentry\n */\n Replay.prototype.sendReplay = function (_a) {\n var replayId = _a.replayId, events = _a.events, segmentId = _a.segmentId, includeReplayStartTimestamp = _a.includeReplayStartTimestamp, eventContext = _a.eventContext;\n return __awaiter(this, void 0, void 0, function () {\n var ex_1;\n var _this = this;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n // short circuit if there's no events to upload (this shouldn't happen as runFlush makes this check)\n if (!events.length) {\n return [2 /*return*/];\n }\n _b.label = 1;\n case 1:\n _b.trys.push([1, 3, , 5]);\n return [4 /*yield*/, this.sendReplayRequest({\n events: events,\n replayId: replayId,\n segmentId: segmentId,\n includeReplayStartTimestamp: includeReplayStartTimestamp,\n eventContext: eventContext,\n })];\n case 2:\n _b.sent();\n this.resetRetries();\n return [2 /*return*/, true];\n case 3:\n ex_1 = _b.sent();\n console.error(ex_1);\n // Capture error for every failed replay\n setContext('Replays', {\n retryCount: this.retryCount,\n });\n captureInternalException(ex_1);\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (this.retryCount >= MAX_RETRY_COUNT) {\n throw new Error(\"\".concat(UNABLE_TO_SEND_REPLAY, \" - max retries exceeded\"));\n }\n this.retryCount = this.retryCount + 1;\n // will retry in intervals of 5, 10, 30\n this.retryInterval = this.retryCount * this.retryInterval;\n return [4 /*yield*/, new Promise(function (resolve, reject) {\n setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {\n var err_3;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, this.sendReplay({\n replayId: replayId,\n events: events,\n segmentId: segmentId,\n includeReplayStartTimestamp: includeReplayStartTimestamp,\n eventContext: eventContext,\n })];\n case 1:\n _a.sent();\n resolve(true);\n return [3 /*break*/, 3];\n case 2:\n err_3 = _a.sent();\n reject(err_3);\n return [3 /*break*/, 3];\n case 3: return [2 /*return*/];\n }\n });\n }); }, _this.retryInterval);\n })];\n case 4: return [2 /*return*/, _b.sent()];\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n /**\n * @inheritDoc\n */\n Replay.id = 'Replay';\n return Replay;\n}());\n\nexport { Replay };\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Metric, ReportCallback } from '../types';\n\nexport const bindReporter = (\n callback: ReportCallback,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n let delta: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { NavigationTimingPolyfillEntry } from '../types';\n\nconst getNavigationEntryFromPerformanceTiming = (): NavigationTimingPolyfillEntry => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry: { [key: string]: number | string } = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key as keyof PerformanceTiming] as number) - timing.navigationStart, 0);\n }\n }\n return navigationEntry as unknown as NavigationTimingPolyfillEntry;\n};\n\nexport const getNavigationEntry = (): PerformanceNavigationTiming | NavigationTimingPolyfillEntry | undefined => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const getActivationStart = (): number => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport type { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\nimport { getActivationStart } from './getActivationStart';\nimport { getNavigationEntry } from './getNavigationEntry';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n const navEntry = getNavigationEntry();\n let navigationType: Metric['navigationType'] = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') as Metric['navigationType'];\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FirstInputPolyfillEntry, NavigationTimingPolyfillEntry, PerformancePaintTiming } from '../types';\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\ninterface PerformanceEntryMap {\n event: PerformanceEventTiming[];\n paint: PerformancePaintTiming[];\n 'layout-shift': LayoutShift[];\n 'largest-contentful-paint': LargestContentfulPaint[];\n 'first-input': PerformanceEventTiming[] | FirstInputPolyfillEntry[];\n navigation: PerformanceNavigationTiming[] | NavigationTimingPolyfillEntry[];\n resource: PerformanceResourceTiming[];\n longtask: PerformanceEntry[];\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = <K extends keyof PerformanceEntryMap>(\n type: K,\n callback: (entries: PerformanceEntryMap[K]) => void,\n opts?: PerformanceObserverInit,\n): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() as PerformanceEntryMap[K]);\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) as PerformanceObserverInit,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WINDOW } from '../../types';\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): number => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getActivationStart } from './lib/getActivationStart';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { LCPMetric, ReportCallback, StopListening } from './types';\n\nconst reportedMetricIDs: Record<string, boolean> = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nexport const onLCP = (onReport: ReportCallback): StopListening | undefined => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType<typeof bindReporter>;\n\n const handleEntries = (entries: LCPMetric['entries']): void => {\n const lastEntry = entries[entries.length - 1] as LargestContentfulPaint;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() as LCPMetric['entries']);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n","import type { Transaction } from '@sentry/core';\nimport type { Span, SpanContext } from '@sentry/types';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nexport function isMeasurementValue(value: unknown): value is number {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n","/* eslint-disable max-lines */\nimport type { IdleTransaction, Transaction } from '@sentry/core';\nimport { getActiveTransaction } from '@sentry/core';\nimport type { Measurements } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, htmlTreeAsString, logger } from '@sentry/utils';\n\nimport { WINDOW } from '../types';\nimport { onCLS } from '../web-vitals/getCLS';\nimport { onFID } from '../web-vitals/getFID';\nimport { onLCP } from '../web-vitals/getLCP';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher';\nimport { observe } from '../web-vitals/lib/observe';\nimport type { NavigatorDeviceMemory, NavigatorNetworkInformation } from '../web-vitals/types';\nimport { _startChild, isMeasurementValue } from './utils';\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time: number): number {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI(): Performance | undefined {\n // @ts-ignore we want to make sure all of these are available, even if TS is sure they are\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor: number = 0;\n\nlet _measurements: Measurements = {};\nlet _lcpEntry: LargestContentfulPaint | undefined;\nlet _clsEntry: LayoutShift | undefined;\n\n/**\n * Start tracking web vitals\n *\n * @returns A function that forces web vitals collection\n */\nexport function startTrackingWebVitals(): () => void {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n // @ts-ignore we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n\n return (): void => {\n if (clsCallback) {\n clsCallback();\n }\n if (lcpCallback) {\n lcpCallback();\n }\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nexport function startTrackingLongTasks(): void {\n const entryHandler = (entries: PerformanceEntry[]): void => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n };\n\n observe('longtask', entryHandler);\n}\n\n/**\n * Start tracking interaction events.\n */\nexport function startTrackingInteractions(): void {\n const entryHandler = (entries: PerformanceEventTiming[]): void => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() as IdleTransaction | undefined;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin as number) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n }\n };\n\n observe('event', entryHandler, { durationThreshold: 0 });\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS(): ReturnType<typeof onCLS> {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n return onCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry as LayoutShift;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP(): ReturnType<typeof onLCP> {\n return onLCP(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry as LargestContentfulPaint;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID(): void {\n onFID(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime);\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nexport function addPerformanceEntries(transaction: Transaction): void {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n __DEBUG_BUILD__ && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp: number | undefined;\n let requestStartTimestamp: number | undefined;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry: Record<string, any>) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name as string).replace(WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n __DEBUG_BUILD__ &&\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nexport function _addMeasureSpans(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record<string, any>,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n origin: 'auto.resource.browser.metrics',\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction: Transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry: Record<string, any>,\n event: string,\n timeOrigin: number,\n description?: string,\n eventEnd?: string,\n): void {\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n}\n\nexport interface ResourceEntry extends Record<string, unknown> {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n renderBlockingStatus?: string;\n}\n\n/** Create resource-related spans */\nexport function _addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceName: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): void {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data: Record<string, any> = {};\n if ('transferSize' in entry) {\n data['http.response_transfer_size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['http.response_content_length'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['http.decoded_response_content_length'] = entry.decodedBodySize;\n }\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n origin: 'auto.resource.browser.metrics',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction: Transaction): void {\n const navigator = WINDOW.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction: Transaction): void {\n if (_lcpEntry) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n __DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { FIDMetric, PerformanceEventTiming, ReportCallback } from './types';\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nexport const onFID = (onReport: ReportCallback): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report: ReturnType<typeof bindReporter>;\n\n const handleEntry = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries: FIDMetric['entries']): void => {\n (entries as PerformanceEventTiming[]).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() as FIDMetric['entries']);\n po.disconnect();\n }, true);\n }\n};\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport type { CLSMetric, ReportCallback, StopListening } from './types';\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nexport const onCLS = (onReport: ReportCallback): StopListening | undefined => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType<typeof bindReporter>;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries: LayoutShift[]): void => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = (): void => {\n handleEntries(po.takeRecords() as CLSMetric['entries']);\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n","/* eslint-disable max-lines */\nimport { getCurrentHub, getDynamicSamplingContextFromClient, hasTracingEnabled } from '@sentry/core';\nimport type { Client, Scope, Span } from '@sentry/types';\nimport {\n addInstrumentationHandler,\n BAGGAGE_HEADER_NAME,\n browserPerformanceTimeOrigin,\n dynamicSamplingContextToSentryBaggageHeader,\n generateSentryTraceHeader,\n isInstanceOf,\n SENTRY_XHR_DATA_KEY,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nexport const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * @deprecated Will be removed in v8.\n * Use `shouldCreateSpanForRequest` to control span creation and `tracePropagationTargets` to control\n * trace header attachment.\n */\n tracingOrigins: Array<string | RegExp>;\n\n /**\n * List of strings and/or regexes used to determine which outgoing requests will have `sentry-trace` and `baggage`\n * headers attached.\n *\n * @deprecated Use the top-level `tracePropagationTargets` option in `Sentry.init` instead.\n * This option will be removed in v8.\n *\n * Default: ['localhost', /^\\//] @see {DEFAULT_TRACE_PROPAGATION_TARGETS}\n */\n tracePropagationTargets: Array<string | RegExp>;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * If true, Sentry will capture http timings and add them to the corresponding http spans.\n *\n * Default: true\n */\n enableHTTPTimings: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * Default: (url: string) => true\n */\n shouldCreateSpanForRequest?(this: void, url: string): boolean;\n}\n\n/** Data returned from fetch callback */\nexport interface FetchData {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[]; // the arguments passed to the fetch call itself\n fetchData?: {\n method: string;\n url: string;\n // span_id\n __span?: string;\n };\n\n // TODO Should this be unknown instead? If we vendor types, make it a Response\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response?: any;\n error?: unknown;\n\n startTimestamp: number;\n endTimestamp?: number;\n}\n\n/** Data returned from XHR request */\nexport interface XHRData {\n xhr?: {\n [SENTRY_XHR_DATA_KEY]?: {\n method: string;\n url: string;\n status_code: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: Record<string, any>;\n };\n __sentry_xhr_span_id__?: string;\n setRequestHeader?: (key: string, val: string) => void;\n getRequestHeader?: (key: string) => string;\n __sentry_own_request__?: boolean;\n };\n startTimestamp: number;\n endTimestamp?: number;\n}\n\ntype PolymorphicRequestHeaders =\n | Record<string, string | undefined>\n | Array<[string, string]>\n // the below is not preicsely the Header type used in Request, but it'll pass duck-typing\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n append: (key: string, value: string) => void;\n get: (key: string) => string | null | undefined;\n };\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial<RequestInstrumentationOptions>): void {\n const {\n traceFetch,\n traceXHR,\n // eslint-disable-next-line deprecation/deprecation\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_: string) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url: string): boolean =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans: Record<string, Span> = {};\n\n if (traceFetch) {\n addInstrumentationHandler('fetch', (handlerData: FetchData) => {\n const createdSpan = fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler('xhr', (handlerData: XHRData) => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry as PerformanceResourceTiming).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span: Span): void {\n const url = span.data.url;\n const observer = new PerformanceObserver(list => {\n const entries = list.getEntries();\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setData(...data));\n observer.disconnect();\n }\n });\n });\n observer.observe({\n entryTypes: ['resource'],\n });\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nexport function extractNetworkProtocol(nextHopProtocol: string): { name: string; version: string } {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/');\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1];\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nfunction getAbsoluteTime(time: number = 0): number {\n return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming: PerformanceResourceTiming): [string, string | number][] {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData: [string, string | number][] = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nexport function shouldAttachHeaders(url: string, tracePropagationTargets: (string | RegExp)[] | undefined): boolean {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track fetch request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\nexport function fetchCallback(\n handlerData: FetchData,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record<string, Span>,\n): Span | undefined {\n if (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n\n const contentLength: string =\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setData('http.response_content_length', contentLengthNum);\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n const client = hub.getClient();\n const parentSpan = scope.getSpan();\n\n const { method, url } = handlerData.fetchData;\n\n const span =\n shouldCreateSpanResult && parentSpan\n ? parentSpan.startChild({\n data: {\n url,\n type: 'fetch',\n 'http.method': method,\n },\n description: `${method} ${url}`,\n op: 'http.client',\n origin: 'auto.http.browser',\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request: string | Request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options: { [key: string]: any } = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nexport function addTracingHeadersToFetchRequest(\n request: string | unknown, // unknown is actually type Request but we can't export DOM types from this package,\n client: Client,\n scope: Scope,\n options: {\n headers?:\n | {\n [key: string]: string[] | string | undefined;\n }\n | PolymorphicRequestHeaders;\n },\n requestSpan?: Span,\n): PolymorphicRequestHeaders | undefined {\n const span = requestSpan || scope.getSpan();\n\n const transaction = span && span.transaction;\n\n const { traceId, sampled, dsc } = scope.getPropagationContext();\n\n const sentryTraceHeader = span ? span.toTraceparent() : generateSentryTraceHeader(traceId, undefined, sampled);\n const dynamicSamplingContext = transaction\n ? transaction.getDynamicSamplingContext()\n : dsc\n ? dsc\n : getDynamicSamplingContextFromClient(traceId, client, scope);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n const headers =\n typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request as Request).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers as Headers);\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders as PolymorphicRequestHeaders;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders: string[] = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers as Exclude<typeof headers, Headers>),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nexport function xhrCallback(\n handlerData: XHRData,\n shouldCreateSpan: (url: string) => boolean,\n shouldAttachHeaders: (url: string) => boolean,\n spans: Record<string, Span>,\n): Span | undefined {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || (xhr && xhr.__sentry_own_request__) || !xhr || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n span.setHttpStatus(sentryXhrData.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n const parentSpan = scope.getSpan();\n\n const span =\n shouldCreateSpanResult && parentSpan\n ? parentSpan.startChild({\n data: {\n ...sentryXhrData.data,\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n url: sentryXhrData.url,\n },\n description: `${sentryXhrData.method} ${sentryXhrData.url}`,\n op: 'http.client',\n origin: 'auto.http.browser',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url)) {\n if (span) {\n const transaction = span && span.transaction;\n const dynamicSamplingContext = transaction && transaction.getDynamicSamplingContext();\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n setHeaderOnXhr(xhr, span.toTraceparent(), sentryBaggageHeader);\n } else {\n const client = hub.getClient();\n const { traceId, sampled, dsc } = scope.getPropagationContext();\n const sentryTraceHeader = generateSentryTraceHeader(traceId, undefined, sampled);\n const dynamicSamplingContext =\n dsc || (client ? getDynamicSamplingContextFromClient(traceId, client, scope) : undefined);\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n }\n\n return span;\n}\n\nfunction setHeaderOnXhr(\n xhr: NonNullable<XHRData['xhr']>,\n sentryTraceHeader: string,\n sentryBaggageHeader: string | undefined,\n): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader!(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n","/* eslint-disable max-lines */\nimport type { Hub, IdleTransaction } from '@sentry/core';\nimport { addTracingExtensions, getActiveTransaction, startIdleTransaction, TRACING_DEFAULTS } from '@sentry/core';\nimport type { EventProcessor, Integration, Transaction, TransactionContext, TransactionSource } from '@sentry/types';\nimport { getDomElement, logger, tracingContextFromHeaders } from '@sentry/utils';\n\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport {\n addPerformanceEntries,\n startTrackingInteractions,\n startTrackingLongTasks,\n startTrackingWebVitals,\n} from './metrics';\nimport type { RequestInstrumentationOptions } from './request';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request';\nimport { instrumentRoutingWithDefaults } from './router';\nimport { WINDOW } from './types';\n\nexport const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished during an idle state. An idle state is defined\n * by a moment where there are no in-progress spans.\n *\n * The transaction will use the end timestamp of the last finished span as the endtime for the transaction.\n * If there are still active spans when this the `idleTimeout` is set, the `idleTimeout` will get reset.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * The max duration for a transaction. If a transaction duration hits the `finalTimeout` value, it\n * will be finished.\n * Time is in ms.\n *\n * Default: 30000\n */\n finalTimeout: number;\n\n /**\n * The heartbeat interval. If no new spans are started or open spans are finished within 3 heartbeats,\n * the transaction will be finished.\n * Time is in ms.\n *\n * Default: 5000\n */\n heartbeatInterval: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * If true, Sentry will capture long tasks and add them to the corresponding transaction.\n *\n * Default: true\n */\n enableLongTask: boolean;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{\n /**\n * @deprecated This property no longer has any effect and will be removed in v8.\n */\n _reportAllChanges: boolean;\n }>;\n\n /**\n * _experiments allows the user to send options to define how this integration works.\n * Note that the `enableLongTask` options is deprecated in favor of the option at the top level, and will be removed in v8.\n *\n * TODO (v8): Remove enableLongTask\n *\n * Default: undefined\n */\n _experiments: Partial<{\n enableLongTask: boolean;\n enableInteractions: boolean;\n onStartRouteTransaction: (t: Transaction | undefined, ctx: TransactionContext, getCurrentHub: () => Hub) => void;\n }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(this: void, context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation<T extends Transaction>(\n this: void,\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS: BrowserTracingOptions = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nexport class BrowserTracing implements Integration {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string;\n\n private _getCurrentHub?: () => Hub;\n\n private _latestRouteName?: string;\n private _latestRouteSource?: TransactionSource;\n\n private _collectWebVitals: () => void;\n\n private _hasSetTracePropagationTargets: boolean;\n\n public constructor(_options?: Partial<BrowserTracingOptions>) {\n this.name = BROWSER_TRACING_INTEGRATION_ID;\n this._hasSetTracePropagationTargets = false;\n\n addTracingExtensions();\n\n if (__DEBUG_BUILD__) {\n this._hasSetTracePropagationTargets = !!(\n _options &&\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n );\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n const hub = getCurrentHub();\n const client = hub.getClient();\n const clientOptions = client && client.getOptions();\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n _experiments,\n } = this.options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;\n if (__DEBUG_BUILD__ && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n instrumentRouting(\n (context: TransactionContext) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : '';\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n const expandedContext: TransactionContext = {\n ...context,\n ...traceparentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n __DEBUG_BUILD__ &&\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n __DEBUG_BUILD__ && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n\n const scope = hub.getScope();\n\n // If it's a pageload and there is a meta tag set\n // use the traceparentData as the propagation context\n if (isPageloadTransaction && traceparentData) {\n scope.setPropagationContext(propagationContext);\n } else {\n // Navigation transactions should set a new propagation context based on the\n // created idle transaction.\n scope.setPropagationContext({\n traceId: idleTransaction.traceId,\n spanId: idleTransaction.spanId,\n parentSpanId: idleTransaction.parentSpanId,\n sampled: idleTransaction.sampled,\n });\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction as Transaction;\n }\n\n /** Start listener for interaction transactions */\n private _registerInteractionListener(): void {\n let inflightInteractionTransaction: IdleTransaction | undefined;\n const registerInteractionTransaction = (): void => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n __DEBUG_BUILD__ && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context: TransactionContext = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | undefined {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n","import type { Transaction, TransactionContext } from '@sentry/types';\nimport { addInstrumentationHandler, browserPerformanceTimeOrigin, logger } from '@sentry/utils';\n\nimport { WINDOW } from './types';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults<T extends Transaction>(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!WINDOW || !WINDOW.location) {\n __DEBUG_BUILD__ && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = WINDOW.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n origin: 'auto.pageload.browser',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler('history', ({ to, from }: { to: string; from?: string }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n __DEBUG_BUILD__ && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n origin: 'auto.navigation.browser',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n","import type { IdleTransaction, SpanStatusType } from '@sentry/core';\nimport { getActiveTransaction } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { WINDOW } from './types';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (WINDOW && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (WINDOW.document.hidden && activeTransaction) {\n const statusType: SpanStatusType = 'cancelled';\n\n __DEBUG_BUILD__ &&\n logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n __DEBUG_BUILD__ &&\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n","import type { Envelope, InternalBaseTransportOptions, Transport, TransportMakeRequestResponse } from '@sentry/types';\nimport { envelopeContainsItemType, logger, parseRetryAfterHeader } from '@sentry/utils';\n\nexport const MIN_DELAY = 100; // 100 ms\nexport const START_DELAY = 5_000; // 5 seconds\nconst MAX_DELAY = 3.6e6; // 1 hour\n\nfunction log(msg: string, error?: Error): void {\n __DEBUG_BUILD__ && logger.info(`[Offline]: ${msg}`, error);\n}\n\nexport interface OfflineStore {\n insert(env: Envelope): Promise<void>;\n pop(): Promise<Envelope | undefined>;\n}\n\nexport type CreateOfflineStore = (options: OfflineTransportOptions) => OfflineStore;\n\nexport interface OfflineTransportOptions extends InternalBaseTransportOptions {\n /**\n * A function that creates the offline store instance.\n */\n createStore?: CreateOfflineStore;\n\n /**\n * Flush the offline store shortly after startup.\n *\n * Defaults: false\n */\n flushAtStartup?: boolean;\n\n /**\n * Called before an event is stored.\n *\n * Return false to drop the envelope rather than store it.\n *\n * @param envelope The envelope that failed to send.\n * @param error The error that occurred.\n * @param retryDelay The current retry delay in milliseconds.\n */\n shouldStore?: (envelope: Envelope, error: Error, retryDelay: number) => boolean | Promise<boolean>;\n}\n\ntype Timer = number | { unref?: () => void };\n\n/**\n * Wraps a transport and stores and retries events when they fail to send.\n *\n * @param createTransport The transport to wrap.\n */\nexport function makeOfflineTransport<TO>(\n createTransport: (options: TO) => Transport,\n): (options: TO & OfflineTransportOptions) => Transport {\n return options => {\n const transport = createTransport(options);\n const store = options.createStore ? options.createStore(options) : undefined;\n\n let retryDelay = START_DELAY;\n let flushTimer: Timer | undefined;\n\n function shouldQueue(env: Envelope, error: Error, retryDelay: number): boolean | Promise<boolean> {\n // We don't queue Session Replay envelopes because they are:\n // - Ordered and Replay relies on the response status to know when they're successfully sent.\n // - Likely to fill the queue quickly and block other events from being sent.\n // We also want to drop client reports because they can be generated when we retry sending events while offline.\n if (envelopeContainsItemType(env, ['replay_event', 'replay_recording', 'client_report'])) {\n return false;\n }\n\n if (options.shouldStore) {\n return options.shouldStore(env, error, retryDelay);\n }\n\n return true;\n }\n\n function flushIn(delay: number): void {\n if (!store) {\n return;\n }\n\n if (flushTimer) {\n clearTimeout(flushTimer as ReturnType<typeof setTimeout>);\n }\n\n flushTimer = setTimeout(async () => {\n flushTimer = undefined;\n\n const found = await store.pop();\n if (found) {\n log('Attempting to send previously queued event');\n void send(found).catch(e => {\n log('Failed to retry sending', e);\n });\n }\n }, delay) as Timer;\n\n // We need to unref the timer in node.js, otherwise the node process never exit.\n if (typeof flushTimer !== 'number' && flushTimer.unref) {\n flushTimer.unref();\n }\n }\n\n function flushWithBackOff(): void {\n if (flushTimer) {\n return;\n }\n\n flushIn(retryDelay);\n\n retryDelay = Math.min(retryDelay * 2, MAX_DELAY);\n }\n\n async function send(envelope: Envelope): Promise<void | TransportMakeRequestResponse> {\n try {\n const result = await transport.send(envelope);\n\n let delay = MIN_DELAY;\n\n if (result) {\n // If there's a retry-after header, use that as the next delay.\n if (result.headers && result.headers['retry-after']) {\n delay = parseRetryAfterHeader(result.headers['retry-after']);\n } // If we have a server error, return now so we don't flush the queue.\n else if ((result.statusCode || 0) >= 400) {\n return result;\n }\n }\n\n flushIn(delay);\n retryDelay = START_DELAY;\n return result;\n } catch (e) {\n if (store && (await shouldQueue(envelope, e as Error, retryDelay))) {\n await store.insert(envelope);\n flushWithBackOff();\n log('Error sending. Event queued', e as Error);\n return {};\n } else {\n throw e;\n }\n }\n }\n\n if (options.flushAtStartup) {\n flushWithBackOff();\n }\n\n return {\n send,\n flush: t => transport.flush(t),\n };\n };\n}\n","import type { OfflineStore, OfflineTransportOptions } from '@sentry/core';\nimport { makeOfflineTransport } from '@sentry/core';\nimport type { Envelope, InternalBaseTransportOptions, Transport } from '@sentry/types';\nimport type { TextDecoderInternal } from '@sentry/utils';\nimport { parseEnvelope, serializeEnvelope } from '@sentry/utils';\n\n// 'Store', 'promisifyRequest' and 'createStore' were originally copied from the 'idb-keyval' package before being\n// modified and simplified: https://github.com/jakearchibald/idb-keyval\n//\n// At commit: 0420a704fd6cbb4225429c536b1f61112d012fca\n// Original licence:\n\n// Copyright 2016, Jake Archibald\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\ntype Store = <T>(callback: (store: IDBObjectStore) => T | PromiseLike<T>) => Promise<T>;\n\nfunction promisifyRequest<T = undefined>(request: IDBRequest<T> | IDBTransaction): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\n\n/** Create or open an IndexedDb store */\nexport function createStore(dbName: string, storeName: string): Store {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n\n return callback => dbp.then(db => callback(db.transaction(storeName, 'readwrite').objectStore(storeName)));\n}\n\nfunction keys(store: IDBObjectStore): Promise<number[]> {\n return promisifyRequest(store.getAllKeys() as IDBRequest<number[]>);\n}\n\n/** Insert into the store */\nexport function insert(store: Store, value: Uint8Array | string, maxQueueSize: number): Promise<void> {\n return store(store => {\n return keys(store).then(keys => {\n if (keys.length >= maxQueueSize) {\n return;\n }\n\n // We insert with an incremented key so that the entries are popped in order\n store.put(value, Math.max(...keys, 0) + 1);\n return promisifyRequest(store.transaction);\n });\n });\n}\n\n/** Pop the oldest value from the store */\nexport function pop(store: Store): Promise<Uint8Array | string | undefined> {\n return store(store => {\n return keys(store).then(keys => {\n if (keys.length === 0) {\n return undefined;\n }\n\n return promisifyRequest(store.get(keys[0])).then(value => {\n store.delete(keys[0]);\n return promisifyRequest(store.transaction).then(() => value);\n });\n });\n });\n}\n\nexport interface BrowserOfflineTransportOptions extends OfflineTransportOptions {\n /**\n * Name of indexedDb database to store envelopes in\n * Default: 'sentry-offline'\n */\n dbName?: string;\n /**\n * Name of indexedDb object store to store envelopes in\n * Default: 'queue'\n */\n storeName?: string;\n /**\n * Maximum number of envelopes to store\n * Default: 30\n */\n maxQueueSize?: number;\n /**\n * Only required for testing on node.js\n * @ignore\n */\n textDecoder?: TextDecoderInternal;\n}\n\nfunction createIndexedDbStore(options: BrowserOfflineTransportOptions): OfflineStore {\n let store: Store | undefined;\n\n // Lazily create the store only when it's needed\n function getStore(): Store {\n if (store == undefined) {\n store = createStore(options.dbName || 'sentry-offline', options.storeName || 'queue');\n }\n\n return store;\n }\n\n return {\n insert: async (env: Envelope) => {\n try {\n const serialized = await serializeEnvelope(env, options.textEncoder);\n await insert(getStore(), serialized, options.maxQueueSize || 30);\n } catch (_) {\n //\n }\n },\n pop: async () => {\n try {\n const deserialized = await pop(getStore());\n if (deserialized) {\n return parseEnvelope(\n deserialized,\n options.textEncoder || new TextEncoder(),\n options.textDecoder || new TextDecoder(),\n );\n }\n } catch (_) {\n //\n }\n\n return undefined;\n },\n };\n}\n\nfunction makeIndexedDbOfflineTransport<T>(\n createTransport: (options: T) => Transport,\n): (options: T & BrowserOfflineTransportOptions) => Transport {\n return options => createTransport({ ...options, createStore: createIndexedDbStore });\n}\n\n/**\n * Creates a transport that uses IndexedDb to store events when offline.\n */\nexport function makeBrowserOfflineTransport<T extends InternalBaseTransportOptions>(\n createTransport: (options: T) => Transport,\n): (options: T & BrowserOfflineTransportOptions) => Transport {\n return makeIndexedDbOfflineTransport<T>(makeOfflineTransport(createTransport));\n}\n","/* eslint-disable max-lines */\n\nimport { DEFAULT_ENVIRONMENT, getCurrentHub } from '@sentry/core';\nimport type { DebugImage, Envelope, Event, StackFrame, StackParser } from '@sentry/types';\nimport type { Profile, ThreadCpuProfile } from '@sentry/types/src/profiling';\nimport { browserPerformanceTimeOrigin, forEachEnvelopeItem, GLOBAL_OBJ, logger, uuid4 } from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\nimport type { JSSelfProfile, JSSelfProfileStack } from './jsSelfProfiling';\n\nconst MS_TO_NS = 1e6;\n// Use 0 as main thread id which is identical to threadId in node:worker_threads\n// where main logs 0 and workers seem to log in increments of 1\nconst THREAD_ID_STRING = String(0);\nconst THREAD_NAME = 'main';\n\n// Machine properties (eval only once)\nlet OS_PLATFORM = '';\nlet OS_PLATFORM_VERSION = '';\nlet OS_ARCH = '';\nlet OS_BROWSER = (WINDOW.navigator && WINDOW.navigator.userAgent) || '';\nlet OS_MODEL = '';\nconst OS_LOCALE =\n (WINDOW.navigator && WINDOW.navigator.language) ||\n (WINDOW.navigator && WINDOW.navigator.languages && WINDOW.navigator.languages[0]) ||\n '';\n\ntype UAData = {\n platform?: string;\n architecture?: string;\n model?: string;\n platformVersion?: string;\n fullVersionList?: {\n brand: string;\n version: string;\n }[];\n};\n\ninterface UserAgentData {\n getHighEntropyValues: (keys: string[]) => Promise<UAData>;\n}\n\nfunction isUserAgentData(data: unknown): data is UserAgentData {\n return typeof data === 'object' && data !== null && 'getHighEntropyValues' in data;\n}\n\n// @ts-ignore userAgentData is not part of the navigator interface yet\nconst userAgentData = WINDOW.navigator && WINDOW.navigator.userAgentData;\n\nif (isUserAgentData(userAgentData)) {\n userAgentData\n .getHighEntropyValues(['architecture', 'model', 'platform', 'platformVersion', 'fullVersionList'])\n .then((ua: UAData) => {\n OS_PLATFORM = ua.platform || '';\n OS_ARCH = ua.architecture || '';\n OS_MODEL = ua.model || '';\n OS_PLATFORM_VERSION = ua.platformVersion || '';\n\n if (ua.fullVersionList && ua.fullVersionList.length > 0) {\n const firstUa = ua.fullVersionList[ua.fullVersionList.length - 1];\n OS_BROWSER = `${firstUa.brand} ${firstUa.version}`;\n }\n })\n .catch(e => void e);\n}\n\nfunction isProcessedJSSelfProfile(profile: ThreadCpuProfile | JSSelfProfile): profile is JSSelfProfile {\n return !('thread_metadata' in profile);\n}\n\n// Enriches the profile with threadId of the current thread.\n// This is done in node as we seem to not be able to get the info from C native code.\n/**\n *\n */\nexport function enrichWithThreadInformation(profile: ThreadCpuProfile | JSSelfProfile): ThreadCpuProfile {\n if (!isProcessedJSSelfProfile(profile)) {\n return profile;\n }\n\n return convertJSSelfProfileToSampledFormat(profile);\n}\n\n// Profile is marked as optional because it is deleted from the metadata\n// by the integration before the event is processed by other integrations.\nexport interface ProfiledEvent extends Event {\n sdkProcessingMetadata: {\n profile?: JSSelfProfile;\n };\n}\n\nfunction getTraceId(event: Event): string {\n const traceId: unknown = event && event.contexts && event.contexts['trace'] && event.contexts['trace']['trace_id'];\n // Log a warning if the profile has an invalid traceId (should be uuidv4).\n // All profiles and transactions are rejected if this is the case and we want to\n // warn users that this is happening if they enable debug flag\n if (typeof traceId === 'string' && traceId.length !== 32) {\n if (__DEBUG_BUILD__) {\n logger.log(`[Profiling] Invalid traceId: ${traceId} on profiled event`);\n }\n }\n if (typeof traceId !== 'string') {\n return '';\n }\n\n return traceId;\n}\n/**\n * Creates a profiling event envelope from a Sentry event. If profile does not pass\n * validation, returns null.\n * @param event\n * @param dsn\n * @param metadata\n * @param tunnel\n * @returns {EventEnvelope | null}\n */\n\n/**\n * Creates a profiling event envelope from a Sentry event.\n */\nexport function createProfilePayload(\n event: ProfiledEvent,\n processedProfile: JSSelfProfile,\n profile_id: string,\n): Profile {\n if (event.type !== 'transaction') {\n // createProfilingEventEnvelope should only be called for transactions,\n // we type guard this behavior with isProfiledTransactionEvent.\n throw new TypeError('Profiling events may only be attached to transactions, this should never occur.');\n }\n\n if (processedProfile === undefined || processedProfile === null) {\n throw new TypeError(\n `Cannot construct profiling event envelope without a valid profile. Got ${processedProfile} instead.`,\n );\n }\n\n const traceId = getTraceId(event);\n const enrichedThreadProfile = enrichWithThreadInformation(processedProfile);\n const transactionStartMs = typeof event.start_timestamp === 'number' ? event.start_timestamp * 1000 : Date.now();\n const transactionEndMs = typeof event.timestamp === 'number' ? event.timestamp * 1000 : Date.now();\n\n const profile: Profile = {\n event_id: profile_id,\n timestamp: new Date(transactionStartMs).toISOString(),\n platform: 'javascript',\n version: '1',\n release: event.release || '',\n environment: event.environment || DEFAULT_ENVIRONMENT,\n runtime: {\n name: 'javascript',\n version: WINDOW.navigator.userAgent,\n },\n os: {\n name: OS_PLATFORM,\n version: OS_PLATFORM_VERSION,\n build_number: OS_BROWSER,\n },\n device: {\n locale: OS_LOCALE,\n model: OS_MODEL,\n manufacturer: OS_BROWSER,\n architecture: OS_ARCH,\n is_emulator: false,\n },\n debug_meta: {\n images: applyDebugMetadata(processedProfile.resources),\n },\n profile: enrichedThreadProfile,\n transactions: [\n {\n name: event.transaction || '',\n id: event.event_id || uuid4(),\n trace_id: traceId,\n active_thread_id: THREAD_ID_STRING,\n relative_start_ns: '0',\n relative_end_ns: ((transactionEndMs - transactionStartMs) * 1e6).toFixed(0),\n },\n ],\n };\n\n return profile;\n}\n\n/**\n *\n */\nexport function isProfiledTransactionEvent(event: Event): event is ProfiledEvent {\n return !!(event.sdkProcessingMetadata && event.sdkProcessingMetadata['profile']);\n}\n\n/**\n * Converts a JSSelfProfile to a our sampled format.\n * Does not currently perform stack indexing.\n */\nexport function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profile['profile'] {\n let EMPTY_STACK_ID: undefined | number = undefined;\n let STACK_ID = 0;\n\n // Initialize the profile that we will fill with data\n const profile: Profile['profile'] = {\n samples: [],\n stacks: [],\n frames: [],\n thread_metadata: {\n [THREAD_ID_STRING]: { name: THREAD_NAME },\n },\n };\n\n if (!input.samples.length) {\n return profile;\n }\n\n // We assert samples.length > 0 above and timestamp should always be present\n const start = input.samples[0].timestamp;\n // The JS SDK might change it's time origin based on some heuristic (see See packages/utils/src/time.ts)\n // when that happens, we need to ensure we are correcting the profile timings so the two timelines stay in sync.\n // Since JS self profiling time origin is always initialized to performance.timeOrigin, we need to adjust for\n // the drift between the SDK selected value and our profile time origin.\n const origin =\n typeof performance.timeOrigin === 'number' ? performance.timeOrigin : browserPerformanceTimeOrigin || 0;\n const adjustForOriginChange = origin - (browserPerformanceTimeOrigin || origin);\n\n for (let i = 0; i < input.samples.length; i++) {\n const jsSample = input.samples[i];\n\n // If sample has no stack, add an empty sample\n if (jsSample.stackId === undefined) {\n if (EMPTY_STACK_ID === undefined) {\n EMPTY_STACK_ID = STACK_ID;\n profile.stacks[EMPTY_STACK_ID] = [];\n STACK_ID++;\n }\n\n profile['samples'][i] = {\n // convert ms timestamp to ns\n elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),\n stack_id: EMPTY_STACK_ID,\n thread_id: THREAD_ID_STRING,\n };\n continue;\n }\n\n let stackTop: JSSelfProfileStack | undefined = input.stacks[jsSample.stackId];\n\n // Functions in top->down order (root is last)\n // We follow the stackTop.parentId trail and collect each visited frameId\n const stack: number[] = [];\n\n while (stackTop) {\n stack.push(stackTop.frameId);\n\n const frame = input.frames[stackTop.frameId];\n\n // If our frame has not been indexed yet, index it\n if (profile.frames[stackTop.frameId] === undefined) {\n profile.frames[stackTop.frameId] = {\n function: frame.name,\n abs_path: typeof frame.resourceId === 'number' ? input.resources[frame.resourceId] : undefined,\n lineno: frame.line,\n colno: frame.column,\n };\n }\n\n stackTop = stackTop.parentId === undefined ? undefined : input.stacks[stackTop.parentId];\n }\n\n const sample: Profile['profile']['samples'][0] = {\n // convert ms timestamp to ns\n elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start) * MS_TO_NS).toFixed(0),\n stack_id: STACK_ID,\n thread_id: THREAD_ID_STRING,\n };\n\n profile['stacks'][STACK_ID] = stack;\n profile['samples'][i] = sample;\n STACK_ID++;\n }\n\n return profile;\n}\n\n/**\n * Adds items to envelope if they are not already present - mutates the envelope.\n * @param envelope\n */\nexport function addProfilesToEnvelope(envelope: Envelope, profiles: Profile[]): Envelope {\n if (!profiles.length) {\n return envelope;\n }\n\n for (const profile of profiles) {\n // @ts-ignore untyped envelope\n envelope[1].push([{ type: 'profile' }, profile]);\n }\n return envelope;\n}\n\n/**\n * Finds transactions with profile_id context in the envelope\n * @param envelope\n * @returns\n */\nexport function findProfiledTransactionsFromEnvelope(envelope: Envelope): Event[] {\n const events: Event[] = [];\n\n forEachEnvelopeItem(envelope, (item, type) => {\n if (type !== 'transaction') {\n return;\n }\n\n for (let j = 1; j < item.length; j++) {\n const event = item[j] as Event;\n\n if (event && event.contexts && event.contexts['profile'] && event.contexts['profile']['profile_id']) {\n events.push(item[j] as Event);\n }\n }\n });\n\n return events;\n}\n\nconst debugIdStackParserCache = new WeakMap<StackParser, Map<string, StackFrame[]>>();\n/**\n * Applies debug meta data to an event from a list of paths to resources (sourcemaps)\n */\nexport function applyDebugMetadata(resource_paths: ReadonlyArray<string>): DebugImage[] {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return [];\n }\n\n const hub = getCurrentHub();\n if (!hub) {\n return [];\n }\n const client = hub.getClient();\n if (!client) {\n return [];\n }\n const options = client.getOptions();\n if (!options) {\n return [];\n }\n const stackParser = options.stackParser;\n if (!stackParser) {\n return [];\n }\n\n let debugIdStackFramesCache: Map<string, StackFrame[]>;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map<string, StackFrame[]>();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce<Record<string, string>>((acc, debugIdStackTrace) => {\n let parsedStack: StackFrame[];\n\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n const file = stackFrame && stackFrame.filename;\n\n if (stackFrame && file) {\n acc[file] = debugIdMap[debugIdStackTrace] as string;\n break;\n }\n }\n return acc;\n }, {});\n\n const images: DebugImage[] = [];\n for (const path of resource_paths) {\n if (path && filenameDebugIdMap[path]) {\n images.push({\n type: 'sourcemap',\n code_file: path,\n debug_id: filenameDebugIdMap[path] as string,\n });\n }\n }\n\n return images;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nexport function isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n if ((typeof rate !== 'number' && typeof rate !== 'boolean') || (typeof rate === 'number' && isNaN(rate))) {\n __DEBUG_BUILD__ &&\n logger.warn(\n `[Profiling] Invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // Boolean sample rates are always valid\n if (rate === true || rate === false) {\n return true;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n __DEBUG_BUILD__ &&\n logger.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\nfunction isValidProfile(profile: JSSelfProfile): profile is JSSelfProfile & { profile_id: string } {\n if (profile.samples.length < 2) {\n if (__DEBUG_BUILD__) {\n // Log a warning if the profile has less than 2 samples so users can know why\n // they are not seeing any profiling data and we cant avoid the back and forth\n // of asking them to provide us with a dump of the profile data.\n logger.log('[Profiling] Discarding profile because it contains less than 2 samples');\n }\n return false;\n }\n\n if (!profile.frames.length) {\n if (__DEBUG_BUILD__) {\n logger.log('[Profiling] Discarding profile because it contains no frames');\n }\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a profiling envelope item, if the profile does not pass validation, returns null.\n * @param event\n * @returns {Profile | null}\n */\nexport function createProfilingEvent(profile_id: string, profile: JSSelfProfile, event: ProfiledEvent): Profile | null {\n if (!isValidProfile(profile)) {\n return null;\n }\n\n return createProfilePayload(event, profile, profile_id);\n}\n\nexport const PROFILE_MAP: Map<string, JSSelfProfile> = new Map();\n/**\n *\n */\nexport function addProfileToMap(profile_id: string, profile: JSSelfProfile): void {\n PROFILE_MAP.set(profile_id, profile);\n\n if (PROFILE_MAP.size > 30) {\n const last: string = PROFILE_MAP.keys().next().value;\n PROFILE_MAP.delete(last);\n }\n}\n","/* eslint-disable complexity */\nimport { getCurrentHub } from '@sentry/core';\nimport type { Transaction } from '@sentry/types';\nimport { logger, uuid4 } from '@sentry/utils';\n\nimport { WINDOW } from '../helpers';\nimport type { JSSelfProfile, JSSelfProfiler, JSSelfProfilerConstructor } from './jsSelfProfiling';\nimport { addProfileToMap, isValidSampleRate } from './utils';\n\nexport const MAX_PROFILE_DURATION_MS = 30_000;\n// Keep a flag value to avoid re-initializing the profiler constructor. If it fails\n// once, it will always fail and this allows us to early return.\nlet PROFILING_CONSTRUCTOR_FAILED = false;\n\n/**\n * Check if profiler constructor is available.\n * @param maybeProfiler\n */\nfunction isJSProfilerSupported(maybeProfiler: unknown): maybeProfiler is typeof JSSelfProfilerConstructor {\n return typeof maybeProfiler === 'function';\n}\n\n/**\n * Safety wrapper for startTransaction for the unlikely case that transaction starts before tracing is imported -\n * if that happens we want to avoid throwing an error from profiling code.\n * see https://github.com/getsentry/sentry-javascript/issues/4731.\n *\n * @experimental\n */\nexport function onProfilingStartRouteTransaction(transaction: Transaction | undefined): Transaction | undefined {\n if (!transaction) {\n if (__DEBUG_BUILD__) {\n logger.log('[Profiling] Transaction is undefined, skipping profiling');\n }\n return transaction;\n }\n\n return wrapTransactionWithProfiling(transaction);\n}\n\n/**\n * Wraps startTransaction and stopTransaction with profiling related logic.\n * startProfiling is called after the call to startTransaction in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to stopTransaction.\n */\nexport function wrapTransactionWithProfiling(transaction: Transaction): Transaction {\n // Feature support check first\n const JSProfilerConstructor = WINDOW.Profiler;\n\n if (!isJSProfilerSupported(JSProfilerConstructor)) {\n if (__DEBUG_BUILD__) {\n logger.log(\n '[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object.',\n );\n }\n return transaction;\n }\n\n // If constructor failed once, it will always fail, so we can early return.\n if (PROFILING_CONSTRUCTOR_FAILED) {\n if (__DEBUG_BUILD__) {\n logger.log('[Profiling] Profiling has been disabled for the duration of the current user session.');\n }\n return transaction;\n }\n\n const client = getCurrentHub().getClient();\n const options = client && client.getOptions();\n if (!options) {\n __DEBUG_BUILD__ && logger.log('[Profiling] Profiling disabled, no options found.');\n return transaction;\n }\n\n // @ts-ignore profilesSampleRate is not part of the browser options yet\n const profilesSampleRate: number | boolean | undefined = options.profilesSampleRate;\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(profilesSampleRate)) {\n __DEBUG_BUILD__ && logger.warn('[Profiling] Discarding profile because of invalid sample rate.');\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `profileSampleRate` is 0, it's a sign the profile should be dropped\n if (!profilesSampleRate) {\n __DEBUG_BUILD__ &&\n logger.log(\n '[Profiling] Discarding profile because a negative sampling decision was inherited or profileSampleRate is set to 0',\n );\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n const sampled = profilesSampleRate === true ? true : Math.random() < profilesSampleRate;\n // Check if we should sample this profile\n if (!sampled) {\n __DEBUG_BUILD__ &&\n logger.log(\n `[Profiling] Discarding profile because it's not included in the random sample (sampling rate = ${Number(\n profilesSampleRate,\n )})`,\n );\n return transaction;\n }\n\n // From initial testing, it seems that the minimum value for sampleInterval is 10ms.\n const samplingIntervalMS = 10;\n // Start the profiler\n const maxSamples = Math.floor(MAX_PROFILE_DURATION_MS / samplingIntervalMS);\n let profiler: JSSelfProfiler | undefined;\n\n // Attempt to initialize the profiler constructor, if it fails, we disable profiling for the current user session.\n // This is likely due to a missing 'Document-Policy': 'js-profiling' header. We do not want to throw an error if this happens\n // as we risk breaking the user's application, so just disable profiling and log an error.\n try {\n profiler = new JSProfilerConstructor({ sampleInterval: samplingIntervalMS, maxBufferSize: maxSamples });\n } catch (e) {\n if (__DEBUG_BUILD__) {\n logger.log(\n \"[Profiling] Failed to initialize the Profiling constructor, this is likely due to a missing 'Document-Policy': 'js-profiling' header.\",\n );\n logger.log('[Profiling] Disabling profiling for current user session.');\n }\n PROFILING_CONSTRUCTOR_FAILED = true;\n }\n\n // We failed to construct the profiler, fallback to original transaction - there is no need to log\n // anything as we already did that in the try/catch block.\n if (!profiler) {\n return transaction;\n }\n\n if (__DEBUG_BUILD__) {\n logger.log(`[Profiling] started profiling transaction: ${transaction.name || transaction.description}`);\n }\n\n // We create \"unique\" transaction names to avoid concurrent transactions with same names\n // from being ignored by the profiler. From here on, only this transaction name should be used when\n // calling the profiler methods. Note: we log the original name to the user to avoid confusion.\n const profileId = uuid4();\n\n // A couple of important things to note here:\n // `CpuProfilerBindings.stopProfiling` will be scheduled to run in 30seconds in order to exceed max profile duration.\n // Whichever of the two (transaction.finish/timeout) is first to run, the profiling will be stopped and the gathered profile\n // will be processed when the original transaction is finished. Since onProfileHandler can be invoked multiple times in the\n // event of an error or user mistake (calling transaction.finish multiple times), it is important that the behavior of onProfileHandler\n // is idempotent as we do not want any timings or profiles to be overriden by the last call to onProfileHandler.\n // After the original finish method is called, the event will be reported through the integration and delegated to transport.\n const processedProfile: JSSelfProfile | null = null;\n\n /**\n * Idempotent handler for profile stop\n */\n async function onProfileHandler(): Promise<null> {\n // Check if the profile exists and return it the behavior has to be idempotent as users may call transaction.finish multiple times.\n if (!transaction) {\n return null;\n }\n // Satisfy the type checker, but profiler will always be defined here.\n if (!profiler) {\n return null;\n }\n if (processedProfile) {\n if (__DEBUG_BUILD__) {\n logger.log(\n '[Profiling] profile for:',\n transaction.name || transaction.description,\n 'already exists, returning early',\n );\n }\n return null;\n }\n\n // This is temporary - we will use the collected span data to evaluate\n // if deferring txn.finish until profiler resolves is a viable approach.\n const stopProfilerSpan = transaction.startChild({\n description: 'profiler.stop',\n op: 'profiler',\n origin: 'auto.profiler.browser',\n });\n\n return profiler\n .stop()\n .then((p: JSSelfProfile): null => {\n stopProfilerSpan.finish();\n\n if (maxDurationTimeoutID) {\n WINDOW.clearTimeout(maxDurationTimeoutID);\n maxDurationTimeoutID = undefined;\n }\n\n if (__DEBUG_BUILD__) {\n logger.log(`[Profiling] stopped profiling of transaction: ${transaction.name || transaction.description}`);\n }\n\n // In case of an overlapping transaction, stopProfiling may return null and silently ignore the overlapping profile.\n if (!p) {\n if (__DEBUG_BUILD__) {\n logger.log(\n `[Profiling] profiler returned null profile for: ${transaction.name || transaction.description}`,\n 'this may indicate an overlapping transaction or a call to stopProfiling with a profile title that was never started',\n );\n }\n return null;\n }\n\n addProfileToMap(profileId, p);\n return null;\n })\n .catch(error => {\n stopProfilerSpan.finish();\n if (__DEBUG_BUILD__) {\n logger.log('[Profiling] error while stopping profiler:', error);\n }\n return null;\n });\n }\n\n // Enqueue a timeout to prevent profiles from running over max duration.\n let maxDurationTimeoutID: number | undefined = WINDOW.setTimeout(() => {\n if (__DEBUG_BUILD__) {\n logger.log(\n '[Profiling] max profile duration elapsed, stopping profiling for:',\n transaction.name || transaction.description,\n );\n }\n // If the timeout exceeds, we want to stop profiling, but not finish the transaction\n void onProfileHandler();\n }, MAX_PROFILE_DURATION_MS);\n\n // We need to reference the original finish call to avoid creating an infinite loop\n const originalFinish = transaction.finish.bind(transaction);\n\n /**\n * Wraps startTransaction and stopTransaction with profiling related logic.\n * startProfiling is called after the call to startTransaction in order to avoid our own code from\n * being profiled. Because of that same reason, stopProfiling is called before the call to stopTransaction.\n */\n function profilingWrappedTransactionFinish(): Transaction {\n if (!transaction) {\n return originalFinish();\n }\n // onProfileHandler should always return the same profile even if this is called multiple times.\n // Always call onProfileHandler to ensure stopProfiling is called and the timeout is cleared.\n void onProfileHandler().then(\n () => {\n transaction.setContext('profile', { profile_id: profileId });\n originalFinish();\n },\n () => {\n // If onProfileHandler fails, we still want to call the original finish method.\n originalFinish();\n },\n );\n\n return transaction;\n }\n\n transaction.finish = profilingWrappedTransactionFinish;\n return transaction;\n}\n","import type { EventProcessor, Hub, Integration, Transaction } from '@sentry/types';\nimport type { Profile } from '@sentry/types/src/profiling';\nimport { logger } from '@sentry/utils';\n\nimport type { BrowserClient } from './../client';\nimport { wrapTransactionWithProfiling } from './hubextensions';\nimport type { ProfiledEvent } from './utils';\nimport {\n addProfilesToEnvelope,\n createProfilingEvent,\n findProfiledTransactionsFromEnvelope,\n PROFILE_MAP,\n} from './utils';\n\n/**\n * Browser profiling integration. Stores any event that has contexts[\"profile\"][\"profile_id\"]\n * This exists because we do not want to await async profiler.stop calls as transaction.finish is called\n * in a synchronous context. Instead, we handle sending the profile async from the promise callback and\n * rely on being able to pull the event from the cache when we need to construct the envelope. This makes the\n * integration less reliable as we might be dropping profiles when the cache is full.\n *\n * @experimental\n */\nexport class BrowserProfilingIntegration implements Integration {\n public static id: string = 'BrowserProfilingIntegration';\n\n public readonly name: string;\n\n public getCurrentHub?: () => Hub;\n\n public constructor() {\n this.name = BrowserProfilingIntegration.id;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this.getCurrentHub = getCurrentHub;\n const client = this.getCurrentHub().getClient() as BrowserClient;\n\n if (client && typeof client.on === 'function') {\n client.on('startTransaction', (transaction: Transaction) => {\n wrapTransactionWithProfiling(transaction);\n });\n\n client.on('beforeEnvelope', (envelope): void => {\n // if not profiles are in queue, there is nothing to add to the envelope.\n if (!PROFILE_MAP['size']) {\n return;\n }\n\n const profiledTransactionEvents = findProfiledTransactionsFromEnvelope(envelope);\n if (!profiledTransactionEvents.length) {\n return;\n }\n\n const profilesToAddToEnvelope: Profile[] = [];\n\n for (const profiledTransaction of profiledTransactionEvents) {\n const context = profiledTransaction && profiledTransaction.contexts;\n const profile_id = context && context['profile'] && (context['profile']['profile_id'] as string);\n\n if (!profile_id) {\n __DEBUG_BUILD__ &&\n logger.log('[Profiling] cannot find profile for a transaction without a profile context');\n continue;\n }\n\n // Remove the profile from the transaction context before sending, relay will take care of the rest.\n if (context && context['profile']) {\n delete context.profile;\n }\n\n const profile = PROFILE_MAP.get(profile_id);\n if (!profile) {\n __DEBUG_BUILD__ && logger.log(`[Profiling] Could not retrieve profile for transaction: ${profile_id}`);\n continue;\n }\n\n PROFILE_MAP.delete(profile_id);\n const profileEvent = createProfilingEvent(profile_id, profile, profiledTransaction as ProfiledEvent);\n\n if (profileEvent) {\n profilesToAddToEnvelope.push(profileEvent);\n }\n }\n\n addProfilesToEnvelope(envelope, profilesToAddToEnvelope);\n });\n } else {\n logger.warn('[Profiling] Client does not support hooks, profiling will be disabled');\n }\n }\n}\n","export * from './exports';\n\nimport { Integrations as CoreIntegrations } from '@sentry/core';\n\nimport { WINDOW } from './helpers';\nimport * as BrowserIntegrations from './integrations';\n\nlet windowIntegrations = {};\n\n// This block is needed to add compatibility with the integrations packages when used with a CDN\nif (WINDOW.Sentry && WINDOW.Sentry.Integrations) {\n windowIntegrations = WINDOW.Sentry.Integrations;\n}\n\nconst INTEGRATIONS = {\n ...windowIntegrations,\n ...CoreIntegrations,\n ...BrowserIntegrations,\n};\n\nexport { INTEGRATIONS as Integrations };\n\nexport { Replay } from '@sentry/replay';\nexport type {\n ReplayEventType,\n ReplayEventWithTime,\n ReplayBreadcrumbFrame,\n ReplayBreadcrumbFrameEvent,\n ReplayOptionFrameEvent,\n ReplayFrame,\n ReplayFrameEvent,\n ReplaySpanFrame,\n ReplaySpanFrameEvent,\n} from '@sentry/replay';\n\nexport {\n BrowserTracing,\n defaultRequestInstrumentationOptions,\n instrumentOutgoingRequests,\n} from '@sentry-internal/tracing';\nexport type { RequestInstrumentationOptions } from '@sentry-internal/tracing';\nexport {\n addTracingExtensions,\n setMeasurement,\n extractTraceparentData,\n getActiveTransaction,\n spanStatusfromHttpCode,\n trace,\n makeMultiplexedTransport,\n ModuleMetadata,\n} from '@sentry/core';\nexport type { SpanStatusType } from '@sentry/core';\nexport type { Span } from '@sentry/types';\nexport { makeBrowserOfflineTransport } from './transports/offline';\nexport { onProfilingStartRouteTransaction } from './profiling/hubextensions';\nexport { BrowserProfilingIntegration } from './profiling/integration';\n"],"sourceRoot":""}