iureiure 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (1410) hide show
  1. package/.editorconfig +21 -0
  2. package/.env.example +8 -0
  3. package/.eslintignore +19 -0
  4. package/.eslintrc.json +155 -0
  5. package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
  6. package/.github/ISSUE_TEMPLATE/feature_request.md +19 -0
  7. package/.github/dependabot.yml +6 -0
  8. package/.github/pull_request_template.md +23 -0
  9. package/.github/workflows/build-and-quality-checks-v3.yml +51 -0
  10. package/.github/workflows/check_pr_title.yml +17 -0
  11. package/.github/workflows/codeql-analysis.yml +70 -0
  12. package/.github/workflows/create-hotfix-branch-v3.yml +21 -0
  13. package/.github/workflows/deploy-beta-v3.yml +82 -0
  14. package/.github/workflows/deploy-dev-v3.yml +71 -0
  15. package/.github/workflows/deploy-npm-v3.yml +169 -0
  16. package/.github/workflows/deploy-prod-v3.yml +194 -0
  17. package/.github/workflows/deploy-sanity-suite.yml +80 -0
  18. package/.github/workflows/deploy-staging-v3.yml +99 -0
  19. package/.github/workflows/draft-new-release-v3.yml +103 -0
  20. package/.github/workflows/housekeeping.yaml +40 -0
  21. package/.github/workflows/publish-new-release-v3.yml +136 -0
  22. package/.github/workflows/rollback-v3.yml +190 -0
  23. package/.github/workflows/test-v3.yml +60 -0
  24. package/.husky/commit-msg +1 -0
  25. package/.husky/pre-commit +1 -0
  26. package/.jscpd.json +17 -0
  27. package/.nvmrc +1 -0
  28. package/.nxignore +3 -0
  29. package/.prettierignore +18 -0
  30. package/.prettierrc +13 -0
  31. package/.versionrc +8 -0
  32. package/CODEOWNERS +2 -0
  33. package/__mocks__/BraveBrowser.js +9 -0
  34. package/assets/integrations/AdobeAnalytics/adobe-analytics-js-heartbeat.js +193 -0
  35. package/assets/integrations/AdobeAnalytics/adobe-analytics-js.js +116 -0
  36. package/assets/rs-logo-full-light.jpg +0 -0
  37. package/babel.config.json +14 -0
  38. package/commitlint.config.js +27 -0
  39. package/examples/angular/sample-app/.editorconfig +16 -0
  40. package/examples/angular/sample-app/README.md +27 -0
  41. package/examples/angular/sample-app/angular.json +83 -0
  42. package/examples/angular/sample-app/package-lock.json +12552 -0
  43. package/examples/angular/sample-app/package.json +39 -0
  44. package/examples/angular/sample-app/src/app/app-routing.module.ts +10 -0
  45. package/examples/angular/sample-app/src/app/app.component.css +0 -0
  46. package/examples/angular/sample-app/src/app/app.component.html +508 -0
  47. package/examples/angular/sample-app/src/app/app.component.spec.ts +33 -0
  48. package/examples/angular/sample-app/src/app/app.component.ts +104 -0
  49. package/examples/angular/sample-app/src/app/app.module.ts +12 -0
  50. package/examples/angular/sample-app/src/assets/.gitkeep +0 -0
  51. package/examples/angular/sample-app/src/favicon.ico +0 -0
  52. package/examples/angular/sample-app/src/index.html +45 -0
  53. package/examples/angular/sample-app/src/main.ts +7 -0
  54. package/examples/angular/sample-app/src/styles.css +1 -0
  55. package/examples/angular/sample-app/tsconfig.app.json +10 -0
  56. package/examples/angular/sample-app/tsconfig.json +30 -0
  57. package/examples/angular/sample-app/tsconfig.spec.json +9 -0
  58. package/examples/chrome-extension/USAGE.md +140 -0
  59. package/examples/chrome-extension/background-script/LICENSE +21 -0
  60. package/examples/chrome-extension/background-script/README.md +105 -0
  61. package/examples/chrome-extension/background-script/foreground.js +7 -0
  62. package/examples/chrome-extension/background-script/logo/logo-128.png +0 -0
  63. package/examples/chrome-extension/background-script/logo/logo-16.png +0 -0
  64. package/examples/chrome-extension/background-script/logo/logo-48.png +0 -0
  65. package/examples/chrome-extension/background-script/logo/logo.svg +138 -0
  66. package/examples/chrome-extension/background-script/manifest.json +36 -0
  67. package/examples/chrome-extension/background-script/popup/popup.css +11 -0
  68. package/examples/chrome-extension/background-script/popup/popup.html +11 -0
  69. package/examples/chrome-extension/background-script/rudderAnalytics.js +5133 -0
  70. package/examples/chrome-extension/background-script/service-worker.js +28 -0
  71. package/examples/chrome-extension/background-script/settings/settings.css +8 -0
  72. package/examples/chrome-extension/background-script/settings/settings.html +12 -0
  73. package/examples/chrome-extension/background-script-websockets/LICENSE +21 -0
  74. package/examples/chrome-extension/background-script-websockets/README.md +101 -0
  75. package/examples/chrome-extension/background-script-websockets/foreground.js +7 -0
  76. package/examples/chrome-extension/background-script-websockets/logo/logo-128.png +0 -0
  77. package/examples/chrome-extension/background-script-websockets/logo/logo-16.png +0 -0
  78. package/examples/chrome-extension/background-script-websockets/logo/logo-48.png +0 -0
  79. package/examples/chrome-extension/background-script-websockets/logo/logo.svg +138 -0
  80. package/examples/chrome-extension/background-script-websockets/manifest.json +37 -0
  81. package/examples/chrome-extension/background-script-websockets/popup/popup.css +11 -0
  82. package/examples/chrome-extension/background-script-websockets/popup/popup.html +11 -0
  83. package/examples/chrome-extension/background-script-websockets/rudderAnalytics.js +5133 -0
  84. package/examples/chrome-extension/background-script-websockets/service-worker.js +60 -0
  85. package/examples/chrome-extension/background-script-websockets/settings/settings.css +8 -0
  86. package/examples/chrome-extension/background-script-websockets/settings/settings.html +12 -0
  87. package/examples/chrome-extension/content-script-v1.1/LICENSE +21 -0
  88. package/examples/chrome-extension/content-script-v1.1/README.md +105 -0
  89. package/examples/chrome-extension/content-script-v1.1/foreground.js +65 -0
  90. package/examples/chrome-extension/content-script-v1.1/logo/logo-128.png +0 -0
  91. package/examples/chrome-extension/content-script-v1.1/logo/logo-16.png +0 -0
  92. package/examples/chrome-extension/content-script-v1.1/logo/logo-48.png +0 -0
  93. package/examples/chrome-extension/content-script-v1.1/logo/logo.svg +138 -0
  94. package/examples/chrome-extension/content-script-v1.1/manifest.json +35 -0
  95. package/examples/chrome-extension/content-script-v1.1/popup/popup.css +11 -0
  96. package/examples/chrome-extension/content-script-v1.1/popup/popup.html +11 -0
  97. package/examples/chrome-extension/content-script-v1.1/service-worker-utils.js +17 -0
  98. package/examples/chrome-extension/content-script-v1.1/service-worker.js +12 -0
  99. package/examples/chrome-extension/content-script-v1.1/settings/settings.css +8 -0
  100. package/examples/chrome-extension/content-script-v1.1/settings/settings.html +12 -0
  101. package/examples/chrome-extension/content-script-v3/LICENSE +21 -0
  102. package/examples/chrome-extension/content-script-v3/README.md +105 -0
  103. package/examples/chrome-extension/content-script-v3/foreground.js +3875 -0
  104. package/examples/chrome-extension/content-script-v3/logo/logo-128.png +0 -0
  105. package/examples/chrome-extension/content-script-v3/logo/logo-16.png +0 -0
  106. package/examples/chrome-extension/content-script-v3/logo/logo-48.png +0 -0
  107. package/examples/chrome-extension/content-script-v3/logo/logo.svg +138 -0
  108. package/examples/chrome-extension/content-script-v3/manifest.json +35 -0
  109. package/examples/chrome-extension/content-script-v3/popup/popup.css +11 -0
  110. package/examples/chrome-extension/content-script-v3/popup/popup.html +11 -0
  111. package/examples/chrome-extension/content-script-v3/service-worker-utils.js +17 -0
  112. package/examples/chrome-extension/content-script-v3/service-worker.js +12 -0
  113. package/examples/chrome-extension/content-script-v3/settings/settings.css +8 -0
  114. package/examples/chrome-extension/content-script-v3/settings/settings.html +12 -0
  115. package/examples/chrome-extension/websocket-server/server.mjs +19 -0
  116. package/examples/gatsby/sample-gatsby-plugin-usage/README.md +49 -0
  117. package/examples/gatsby/sample-gatsby-plugin-usage/gatsby-config.ts +27 -0
  118. package/examples/gatsby/sample-gatsby-plugin-usage/package-lock.json +16070 -0
  119. package/examples/gatsby/sample-gatsby-plugin-usage/package.json +31 -0
  120. package/examples/gatsby/sample-gatsby-plugin-usage/src/images/icon.png +0 -0
  121. package/examples/gatsby/sample-gatsby-plugin-usage/src/pages/404.tsx +49 -0
  122. package/examples/gatsby/sample-gatsby-plugin-usage/src/pages/index.tsx +193 -0
  123. package/examples/gatsby/sample-gatsby-plugin-usage/tsconfig.json +105 -0
  124. package/examples/gatsby/sample-gatsby-site/README.md +49 -0
  125. package/examples/gatsby/sample-gatsby-site/gatsby-config.ts +15 -0
  126. package/examples/gatsby/sample-gatsby-site/package-lock.json +15916 -0
  127. package/examples/gatsby/sample-gatsby-site/package.json +37 -0
  128. package/examples/gatsby/sample-gatsby-site/src/images/icon.png +0 -0
  129. package/examples/gatsby/sample-gatsby-site/src/pages/404.tsx +49 -0
  130. package/examples/gatsby/sample-gatsby-site/src/pages/index.tsx +209 -0
  131. package/examples/gatsby/sample-gatsby-site/tsconfig.json +105 -0
  132. package/examples/html/autotrack-test.html +94 -0
  133. package/examples/html/ecomm_test.html +358 -0
  134. package/examples/html/script-test.html +968 -0
  135. package/examples/html/segment.html +177 -0
  136. package/examples/html/test_poster.jpg +0 -0
  137. package/examples/nextjs/hooks/sample-app/.eslintrc.json +3 -0
  138. package/examples/nextjs/hooks/sample-app/README.md +36 -0
  139. package/examples/nextjs/hooks/sample-app/next.config.js +4 -0
  140. package/examples/nextjs/hooks/sample-app/package-lock.json +4766 -0
  141. package/examples/nextjs/hooks/sample-app/package.json +28 -0
  142. package/examples/nextjs/hooks/sample-app/postcss.config.js +6 -0
  143. package/examples/nextjs/hooks/sample-app/public/next.svg +1 -0
  144. package/examples/nextjs/hooks/sample-app/public/vercel.svg +1 -0
  145. package/examples/nextjs/hooks/sample-app/src/app/favicon.ico +0 -0
  146. package/examples/nextjs/hooks/sample-app/src/app/globals.css +27 -0
  147. package/examples/nextjs/hooks/sample-app/src/app/layout.tsx +55 -0
  148. package/examples/nextjs/hooks/sample-app/src/app/page.tsx +137 -0
  149. package/examples/nextjs/hooks/sample-app/src/app/useRudderAnalytics.ts +29 -0
  150. package/examples/nextjs/hooks/sample-app/tailwind.config.ts +19 -0
  151. package/examples/nextjs/hooks/sample-app/tsconfig.json +27 -0
  152. package/examples/nextjs/js/sample-app/.eslintrc.json +3 -0
  153. package/examples/nextjs/js/sample-app/README.md +36 -0
  154. package/examples/nextjs/js/sample-app/jsconfig.json +7 -0
  155. package/examples/nextjs/js/sample-app/next.config.js +4 -0
  156. package/examples/nextjs/js/sample-app/package-lock.json +4710 -0
  157. package/examples/nextjs/js/sample-app/package.json +24 -0
  158. package/examples/nextjs/js/sample-app/postcss.config.js +6 -0
  159. package/examples/nextjs/js/sample-app/public/next.svg +1 -0
  160. package/examples/nextjs/js/sample-app/public/vercel.svg +1 -0
  161. package/examples/nextjs/js/sample-app/src/app/favicon.ico +0 -0
  162. package/examples/nextjs/js/sample-app/src/app/globals.css +27 -0
  163. package/examples/nextjs/js/sample-app/src/app/layout.js +54 -0
  164. package/examples/nextjs/js/sample-app/src/app/page.js +146 -0
  165. package/examples/nextjs/js/sample-app/tailwind.config.js +17 -0
  166. package/examples/nextjs/page-router/sample-app/.eslintrc.json +3 -0
  167. package/examples/nextjs/page-router/sample-app/README.md +40 -0
  168. package/examples/nextjs/page-router/sample-app/next.config.js +6 -0
  169. package/examples/nextjs/page-router/sample-app/package-lock.json +4270 -0
  170. package/examples/nextjs/page-router/sample-app/package.json +28 -0
  171. package/examples/nextjs/page-router/sample-app/postcss.config.js +6 -0
  172. package/examples/nextjs/page-router/sample-app/public/favicon.ico +0 -0
  173. package/examples/nextjs/page-router/sample-app/public/next.svg +1 -0
  174. package/examples/nextjs/page-router/sample-app/public/vercel.svg +1 -0
  175. package/examples/nextjs/page-router/sample-app/src/pages/_app.tsx +35 -0
  176. package/examples/nextjs/page-router/sample-app/src/pages/_document.tsx +49 -0
  177. package/examples/nextjs/page-router/sample-app/src/pages/api/hello.ts +10 -0
  178. package/examples/nextjs/page-router/sample-app/src/pages/index.tsx +138 -0
  179. package/examples/nextjs/page-router/sample-app/src/pages/page2.tsx +18 -0
  180. package/examples/nextjs/page-router/sample-app/src/styles/globals.css +27 -0
  181. package/examples/nextjs/page-router/sample-app/src/useRudderAnalytics.ts +29 -0
  182. package/examples/nextjs/page-router/sample-app/tailwind.config.ts +19 -0
  183. package/examples/nextjs/page-router/sample-app/tsconfig.json +22 -0
  184. package/examples/nextjs/ts/sample-app/.eslintrc.json +3 -0
  185. package/examples/nextjs/ts/sample-app/README.md +36 -0
  186. package/examples/nextjs/ts/sample-app/next.config.js +4 -0
  187. package/examples/nextjs/ts/sample-app/package-lock.json +4766 -0
  188. package/examples/nextjs/ts/sample-app/package.json +28 -0
  189. package/examples/nextjs/ts/sample-app/postcss.config.js +6 -0
  190. package/examples/nextjs/ts/sample-app/public/next.svg +1 -0
  191. package/examples/nextjs/ts/sample-app/public/vercel.svg +1 -0
  192. package/examples/nextjs/ts/sample-app/src/app/favicon.ico +0 -0
  193. package/examples/nextjs/ts/sample-app/src/app/globals.css +27 -0
  194. package/examples/nextjs/ts/sample-app/src/app/layout.tsx +55 -0
  195. package/examples/nextjs/ts/sample-app/src/app/page.tsx +147 -0
  196. package/examples/nextjs/ts/sample-app/tailwind.config.ts +19 -0
  197. package/examples/nextjs/ts/sample-app/tsconfig.json +27 -0
  198. package/examples/reactjs/hooks/sample-app/README.md +46 -0
  199. package/examples/reactjs/hooks/sample-app/package-lock.json +16203 -0
  200. package/examples/reactjs/hooks/sample-app/package.json +47 -0
  201. package/examples/reactjs/hooks/sample-app/public/favicon.ico +0 -0
  202. package/examples/reactjs/hooks/sample-app/public/index.html +75 -0
  203. package/examples/reactjs/hooks/sample-app/public/logo192.png +0 -0
  204. package/examples/reactjs/hooks/sample-app/public/logo512.png +0 -0
  205. package/examples/reactjs/hooks/sample-app/public/manifest.json +25 -0
  206. package/examples/reactjs/hooks/sample-app/public/robots.txt +3 -0
  207. package/examples/reactjs/hooks/sample-app/src/App.css +38 -0
  208. package/examples/reactjs/hooks/sample-app/src/App.test.tsx +9 -0
  209. package/examples/reactjs/hooks/sample-app/src/App.tsx +95 -0
  210. package/examples/reactjs/hooks/sample-app/src/index.css +32 -0
  211. package/examples/reactjs/hooks/sample-app/src/index.tsx +19 -0
  212. package/examples/reactjs/hooks/sample-app/src/logo.svg +1 -0
  213. package/examples/reactjs/hooks/sample-app/src/react-app-env.d.ts +1 -0
  214. package/examples/reactjs/hooks/sample-app/src/reportWebVitals.ts +15 -0
  215. package/examples/reactjs/hooks/sample-app/src/setupTests.ts +5 -0
  216. package/examples/reactjs/hooks/sample-app/src/useRudderAnalytics.ts +23 -0
  217. package/examples/reactjs/hooks/sample-app/tsconfig.json +20 -0
  218. package/examples/reactjs/js/sample-app/README.md +70 -0
  219. package/examples/reactjs/js/sample-app/package-lock.json +17665 -0
  220. package/examples/reactjs/js/sample-app/package.json +42 -0
  221. package/examples/reactjs/js/sample-app/public/favicon.ico +0 -0
  222. package/examples/reactjs/js/sample-app/public/index.html +75 -0
  223. package/examples/reactjs/js/sample-app/public/logo192.png +0 -0
  224. package/examples/reactjs/js/sample-app/public/logo512.png +0 -0
  225. package/examples/reactjs/js/sample-app/public/manifest.json +25 -0
  226. package/examples/reactjs/js/sample-app/public/robots.txt +3 -0
  227. package/examples/reactjs/js/sample-app/src/App.css +38 -0
  228. package/examples/reactjs/js/sample-app/src/App.js +101 -0
  229. package/examples/reactjs/js/sample-app/src/App.test.js +8 -0
  230. package/examples/reactjs/js/sample-app/src/index.css +34 -0
  231. package/examples/reactjs/js/sample-app/src/index.js +17 -0
  232. package/examples/reactjs/js/sample-app/src/logo.svg +1 -0
  233. package/examples/reactjs/js/sample-app/src/reportWebVitals.js +13 -0
  234. package/examples/reactjs/js/sample-app/src/setupTests.js +5 -0
  235. package/examples/reactjs/ts/sample-app/README.md +46 -0
  236. package/examples/reactjs/ts/sample-app/package-lock.json +17653 -0
  237. package/examples/reactjs/ts/sample-app/package.json +47 -0
  238. package/examples/reactjs/ts/sample-app/public/favicon.ico +0 -0
  239. package/examples/reactjs/ts/sample-app/public/index.html +75 -0
  240. package/examples/reactjs/ts/sample-app/public/logo192.png +0 -0
  241. package/examples/reactjs/ts/sample-app/public/logo512.png +0 -0
  242. package/examples/reactjs/ts/sample-app/public/manifest.json +25 -0
  243. package/examples/reactjs/ts/sample-app/public/robots.txt +3 -0
  244. package/examples/reactjs/ts/sample-app/src/App.css +38 -0
  245. package/examples/reactjs/ts/sample-app/src/App.test.tsx +9 -0
  246. package/examples/reactjs/ts/sample-app/src/App.tsx +101 -0
  247. package/examples/reactjs/ts/sample-app/src/index.css +34 -0
  248. package/examples/reactjs/ts/sample-app/src/index.tsx +19 -0
  249. package/examples/reactjs/ts/sample-app/src/logo.svg +1 -0
  250. package/examples/reactjs/ts/sample-app/src/react-app-env.d.ts +1 -0
  251. package/examples/reactjs/ts/sample-app/src/reportWebVitals.ts +15 -0
  252. package/examples/reactjs/ts/sample-app/src/setupTests.ts +5 -0
  253. package/examples/reactjs/ts/sample-app/tsconfig.json +20 -0
  254. package/examples/reactjs/vite/sample-app/.eslintrc.cjs +18 -0
  255. package/examples/reactjs/vite/sample-app/README.md +27 -0
  256. package/examples/reactjs/vite/sample-app/index.html +45 -0
  257. package/examples/reactjs/vite/sample-app/package-lock.json +3427 -0
  258. package/examples/reactjs/vite/sample-app/package.json +29 -0
  259. package/examples/reactjs/vite/sample-app/public/vite.svg +1 -0
  260. package/examples/reactjs/vite/sample-app/src/App.css +42 -0
  261. package/examples/reactjs/vite/sample-app/src/App.tsx +105 -0
  262. package/examples/reactjs/vite/sample-app/src/assets/react.svg +1 -0
  263. package/examples/reactjs/vite/sample-app/src/index.css +70 -0
  264. package/examples/reactjs/vite/sample-app/src/main.tsx +10 -0
  265. package/examples/reactjs/vite/sample-app/src/vite-env.d.ts +1 -0
  266. package/examples/reactjs/vite/sample-app/tsconfig.json +25 -0
  267. package/examples/reactjs/vite/sample-app/tsconfig.node.json +10 -0
  268. package/examples/reactjs/vite/sample-app/vite.config.ts +7 -0
  269. package/examples/serverless/USAGE.md +85 -0
  270. package/examples/serverless/cloudflare-worker/.editorconfig +13 -0
  271. package/examples/serverless/cloudflare-worker/.prettierrc +6 -0
  272. package/examples/serverless/cloudflare-worker/package-lock.json +2646 -0
  273. package/examples/serverless/cloudflare-worker/package.json +18 -0
  274. package/examples/serverless/cloudflare-worker/src/worker.js +54 -0
  275. package/examples/serverless/cloudflare-worker/wrangler.toml +52 -0
  276. package/examples/serverless/vercel-edge/.eslintrc.json +3 -0
  277. package/examples/serverless/vercel-edge/README.md +34 -0
  278. package/examples/serverless/vercel-edge/app/api/edge-function-example/route.ts +32 -0
  279. package/examples/serverless/vercel-edge/app/favicon.ico +0 -0
  280. package/examples/serverless/vercel-edge/app/globals.css +27 -0
  281. package/examples/serverless/vercel-edge/app/layout.tsx +22 -0
  282. package/examples/serverless/vercel-edge/app/page.tsx +113 -0
  283. package/examples/serverless/vercel-edge/next.config.js +4 -0
  284. package/examples/serverless/vercel-edge/package-lock.json +5351 -0
  285. package/examples/serverless/vercel-edge/package.json +26 -0
  286. package/examples/serverless/vercel-edge/postcss.config.js +6 -0
  287. package/examples/serverless/vercel-edge/public/next.svg +1 -0
  288. package/examples/serverless/vercel-edge/public/vercel.svg +1 -0
  289. package/examples/serverless/vercel-edge/tailwind.config.ts +19 -0
  290. package/examples/serverless/vercel-edge/tsconfig.json +27 -0
  291. package/examples/symfony/USAGE.md +57 -0
  292. package/examples/symfony/sample/.env.test +6 -0
  293. package/examples/symfony/sample/assets/app.js +15 -0
  294. package/examples/symfony/sample/assets/styles/app.css +3 -0
  295. package/examples/symfony/sample/compose.override.yaml +14 -0
  296. package/examples/symfony/sample/compose.yaml +21 -0
  297. package/examples/symfony/sample/composer.json +104 -0
  298. package/examples/symfony/sample/composer.lock +9921 -0
  299. package/examples/symfony/sample/config/bundles.php +15 -0
  300. package/examples/symfony/sample/config/packages/cache.yaml +19 -0
  301. package/examples/symfony/sample/config/packages/debug.yaml +5 -0
  302. package/examples/symfony/sample/config/packages/doctrine.yaml +43 -0
  303. package/examples/symfony/sample/config/packages/doctrine_migrations.yaml +6 -0
  304. package/examples/symfony/sample/config/packages/framework.yaml +24 -0
  305. package/examples/symfony/sample/config/packages/mailer.yaml +3 -0
  306. package/examples/symfony/sample/config/packages/messenger.yaml +24 -0
  307. package/examples/symfony/sample/config/packages/monolog.yaml +61 -0
  308. package/examples/symfony/sample/config/packages/notifier.yaml +12 -0
  309. package/examples/symfony/sample/config/packages/routing.yaml +12 -0
  310. package/examples/symfony/sample/config/packages/security.yaml +40 -0
  311. package/examples/symfony/sample/config/packages/translation.yaml +13 -0
  312. package/examples/symfony/sample/config/packages/twig.yaml +6 -0
  313. package/examples/symfony/sample/config/packages/validator.yaml +13 -0
  314. package/examples/symfony/sample/config/packages/web_profiler.yaml +15 -0
  315. package/examples/symfony/sample/config/packages/webpack_encore.yaml +45 -0
  316. package/examples/symfony/sample/config/preload.php +5 -0
  317. package/examples/symfony/sample/config/routes/framework.yaml +4 -0
  318. package/examples/symfony/sample/config/routes/web_profiler.yaml +8 -0
  319. package/examples/symfony/sample/config/routes.yaml +7 -0
  320. package/examples/symfony/sample/config/services.yaml +24 -0
  321. package/examples/symfony/sample/package-lock.json +8082 -0
  322. package/examples/symfony/sample/package.json +23 -0
  323. package/examples/symfony/sample/phpunit.xml.dist +38 -0
  324. package/examples/symfony/sample/public/index.php +9 -0
  325. package/examples/symfony/sample/src/Controller/LuckyController.php +18 -0
  326. package/examples/symfony/sample/src/Kernel.php +11 -0
  327. package/examples/symfony/sample/symfony.lock +277 -0
  328. package/examples/symfony/sample/templates/base.html.twig +19 -0
  329. package/examples/symfony/sample/templates/lucky/number.html.twig +20 -0
  330. package/examples/symfony/sample/tests/bootstrap.php +11 -0
  331. package/examples/symfony/sample/webpack.config.js +72 -0
  332. package/examples/v1/index.html +229 -0
  333. package/examples/v1.1/index.html +229 -0
  334. package/examples/v2-beacon/index.html +229 -0
  335. package/examples/v3/index.html +266 -0
  336. package/examples/v3-beacon/index.html +270 -0
  337. package/examples/v3-legacy/index.html +266 -0
  338. package/examples/v3-legacy-minimum-plugins/index.html +270 -0
  339. package/examples/v3-minimum-plugins/index.html +270 -0
  340. package/jest/jest.global-setup.js +3 -0
  341. package/jest/jest.polyfills.js +18 -0
  342. package/jest/jest.setup-dom.js +54 -0
  343. package/jest/jsdom-extended.js +26 -0
  344. package/jest.config.ts +5 -0
  345. package/jest.preset.js +83 -0
  346. package/migrations.json +34 -0
  347. package/nx.json +69 -0
  348. package/package.json +170 -0
  349. package/packages/analytics-js/.env.example +9 -0
  350. package/packages/analytics-js/.jscpd.json +17 -0
  351. package/packages/analytics-js/.size-limit.js +31 -0
  352. package/packages/analytics-js/CHANGELOG.md +283 -0
  353. package/packages/analytics-js/CHANGELOG_LATEST.md +2 -0
  354. package/packages/analytics-js/LICENSE +21 -0
  355. package/packages/analytics-js/README.md +100 -0
  356. package/packages/analytics-js/__fixtures__/fixtures.ts +765 -0
  357. package/packages/analytics-js/__fixtures__/msw.handlers.ts +82 -0
  358. package/packages/analytics-js/__fixtures__/msw.server.ts +6 -0
  359. package/packages/analytics-js/__mocks__/remotePlugins/BeaconQueue.ts +9 -0
  360. package/packages/analytics-js/__mocks__/remotePlugins/Bugsnag.ts +10 -0
  361. package/packages/analytics-js/__mocks__/remotePlugins/CustomConsentManager.ts +10 -0
  362. package/packages/analytics-js/__mocks__/remotePlugins/DeviceModeDestinations.ts +9 -0
  363. package/packages/analytics-js/__mocks__/remotePlugins/DeviceModeTransformation.ts +9 -0
  364. package/packages/analytics-js/__mocks__/remotePlugins/ErrorReporting.ts +10 -0
  365. package/packages/analytics-js/__mocks__/remotePlugins/ExternalAnonymousId.ts +10 -0
  366. package/packages/analytics-js/__mocks__/remotePlugins/GoogleLinker.ts +8 -0
  367. package/packages/analytics-js/__mocks__/remotePlugins/KetchConsentManager.ts +10 -0
  368. package/packages/analytics-js/__mocks__/remotePlugins/NativeDestinationQueue.ts +10 -0
  369. package/packages/analytics-js/__mocks__/remotePlugins/OneTrustConsentManager.ts +10 -0
  370. package/packages/analytics-js/__mocks__/remotePlugins/StorageEncryption.ts +9 -0
  371. package/packages/analytics-js/__mocks__/remotePlugins/StorageEncryptionLegacy.ts +9 -0
  372. package/packages/analytics-js/__mocks__/remotePlugins/StorageMigrator.ts +8 -0
  373. package/packages/analytics-js/__mocks__/remotePlugins/XhrQueue.ts +9 -0
  374. package/packages/analytics-js/__tests__/app/RudderAnalytics.test.ts +286 -0
  375. package/packages/analytics-js/__tests__/components/capabilitiesManager/detection/adBlockers.test.ts +78 -0
  376. package/packages/analytics-js/__tests__/components/capabilitiesManager/detection/browser.test.ts +24 -0
  377. package/packages/analytics-js/__tests__/components/capabilitiesManager/detection/clientHint.test.ts +87 -0
  378. package/packages/analytics-js/__tests__/components/capabilitiesManager/detection/dom.test.ts +13 -0
  379. package/packages/analytics-js/__tests__/components/capabilitiesManager/detection/screen.test.ts +13 -0
  380. package/packages/analytics-js/__tests__/components/capabilitiesManager/detection/storage.test.ts +27 -0
  381. package/packages/analytics-js/__tests__/components/configManager/ConfigManager.test.ts +222 -0
  382. package/packages/analytics-js/__tests__/components/configManager/cdnPaths.test.ts +70 -0
  383. package/packages/analytics-js/__tests__/components/configManager/commonUtil.test.ts +531 -0
  384. package/packages/analytics-js/__tests__/components/configManager/dataPlaneResolver.test.ts +163 -0
  385. package/packages/analytics-js/__tests__/components/configManager/validate.test.ts +31 -0
  386. package/packages/analytics-js/__tests__/components/core/Analytics.test.ts +628 -0
  387. package/packages/analytics-js/__tests__/components/eventManager/EventManager.test.ts +78 -0
  388. package/packages/analytics-js/__tests__/components/eventManager/RudderEventFactory.test.ts +514 -0
  389. package/packages/analytics-js/__tests__/components/eventManager/utilities.test.ts +1043 -0
  390. package/packages/analytics-js/__tests__/components/eventRepository/EventRepository.test.ts +324 -0
  391. package/packages/analytics-js/__tests__/components/pluginsManager/.gitkeep +0 -0
  392. package/packages/analytics-js/__tests__/components/preloadBuffer/index.test.ts +130 -0
  393. package/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts +1386 -0
  394. package/packages/analytics-js/__tests__/components/userSessionManager/utils.test.ts +103 -0
  395. package/packages/analytics-js/__tests__/components/utilities/consent.test.ts +192 -0
  396. package/packages/analytics-js/__tests__/components/utilities/destinations.test.ts +201 -0
  397. package/packages/analytics-js/__tests__/components/utilities/event.test.ts +8 -0
  398. package/packages/analytics-js/__tests__/components/utilities/globals.test.ts +42 -0
  399. package/packages/analytics-js/__tests__/components/utilities/page.test.ts +235 -0
  400. package/packages/analytics-js/__tests__/components/utilities/sort.test.ts +17 -0
  401. package/packages/analytics-js/__tests__/components/utilities/statsCollection.test.ts +84 -0
  402. package/packages/analytics-js/__tests__/components/utilities/url.test.ts +51 -0
  403. package/packages/analytics-js/__tests__/services/ErrorHandler/ErrorHandler.test.ts +272 -0
  404. package/packages/analytics-js/__tests__/services/ErrorHandler/processError.test.ts +33 -0
  405. package/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts +255 -0
  406. package/packages/analytics-js/__tests__/services/Logger/Logger.test.ts +204 -0
  407. package/packages/analytics-js/__tests__/services/PluginEngine/PluginEngine.test.ts +206 -0
  408. package/packages/analytics-js/__tests__/services/StoreManager/Store.test.ts +152 -0
  409. package/packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts +272 -0
  410. package/packages/analytics-js/__tests__/services/StoreManager/component-cookie/index.test.ts +65 -0
  411. package/packages/analytics-js/__tests__/services/StoreManager/storages/CookieStorage.test.ts +42 -0
  412. package/packages/analytics-js/__tests__/services/StoreManager/storages/InMemoryStorage.test.ts +26 -0
  413. package/packages/analytics-js/__tests__/services/StoreManager/storages/LocalStorage.test.ts +26 -0
  414. package/packages/analytics-js/__tests__/services/StoreManager/storages/sessionStorage.test.ts +26 -0
  415. package/packages/analytics-js/__tests__/services/StoreManager/top-domain/index.test.ts +60 -0
  416. package/packages/analytics-js/babel.config.json +15 -0
  417. package/packages/analytics-js/jest.config.mjs +14 -0
  418. package/packages/analytics-js/package.json +114 -0
  419. package/packages/analytics-js/project.json +138 -0
  420. package/packages/analytics-js/public/index-legacy-only.html +308 -0
  421. package/packages/analytics-js/public/index.html +324 -0
  422. package/packages/analytics-js/public/list_integration_sdks.html +408 -0
  423. package/packages/analytics-js/rollup.config.mjs +387 -0
  424. package/packages/analytics-js/src/app/IRudderStackGlobals.ts +21 -0
  425. package/packages/analytics-js/src/app/RudderAnalytics.ts +296 -0
  426. package/packages/analytics-js/src/browser.ts +55 -0
  427. package/packages/analytics-js/src/components/capabilitiesManager/CapabilitiesManager.ts +199 -0
  428. package/packages/analytics-js/src/components/capabilitiesManager/detection/adBlockers.ts +38 -0
  429. package/packages/analytics-js/src/components/capabilitiesManager/detection/browser.ts +24 -0
  430. package/packages/analytics-js/src/components/capabilitiesManager/detection/clientHint.ts +31 -0
  431. package/packages/analytics-js/src/components/capabilitiesManager/detection/dom.ts +54 -0
  432. package/packages/analytics-js/src/components/capabilitiesManager/detection/index.ts +6 -0
  433. package/packages/analytics-js/src/components/capabilitiesManager/detection/screen.ts +23 -0
  434. package/packages/analytics-js/src/components/capabilitiesManager/detection/storage.ts +77 -0
  435. package/packages/analytics-js/src/components/capabilitiesManager/index.ts +1 -0
  436. package/packages/analytics-js/src/components/capabilitiesManager/polyfill/index.ts +14 -0
  437. package/packages/analytics-js/src/components/capabilitiesManager/types.ts +14 -0
  438. package/packages/analytics-js/src/components/configManager/ConfigManager.ts +218 -0
  439. package/packages/analytics-js/src/components/configManager/constants.ts +21 -0
  440. package/packages/analytics-js/src/components/configManager/index.ts +1 -0
  441. package/packages/analytics-js/src/components/configManager/types.ts +90 -0
  442. package/packages/analytics-js/src/components/configManager/util/cdnPaths.ts +80 -0
  443. package/packages/analytics-js/src/components/configManager/util/commonUtil.ts +262 -0
  444. package/packages/analytics-js/src/components/configManager/util/dataPlaneResolver.ts +79 -0
  445. package/packages/analytics-js/src/components/configManager/util/validate.ts +46 -0
  446. package/packages/analytics-js/src/components/core/Analytics.ts +824 -0
  447. package/packages/analytics-js/src/components/core/IAnalytics.ts +218 -0
  448. package/packages/analytics-js/src/components/core/utilities.ts +12 -0
  449. package/packages/analytics-js/src/components/eventManager/EventManager.ts +80 -0
  450. package/packages/analytics-js/src/components/eventManager/RudderEventFactory.ts +171 -0
  451. package/packages/analytics-js/src/components/eventManager/constants.ts +29 -0
  452. package/packages/analytics-js/src/components/eventManager/index.ts +1 -0
  453. package/packages/analytics-js/src/components/eventManager/types.ts +7 -0
  454. package/packages/analytics-js/src/components/eventManager/utilities.ts +341 -0
  455. package/packages/analytics-js/src/components/eventRepository/EventRepository.ts +225 -0
  456. package/packages/analytics-js/src/components/eventRepository/constants.ts +9 -0
  457. package/packages/analytics-js/src/components/eventRepository/index.ts +1 -0
  458. package/packages/analytics-js/src/components/eventRepository/types.ts +10 -0
  459. package/packages/analytics-js/src/components/eventRepository/utils.ts +53 -0
  460. package/packages/analytics-js/src/components/pluginsManager/PluginsManager.ts +332 -0
  461. package/packages/analytics-js/src/components/pluginsManager/bundledBuildPluginImports.ts +39 -0
  462. package/packages/analytics-js/src/components/pluginsManager/defaultPluginsList.ts +24 -0
  463. package/packages/analytics-js/src/components/pluginsManager/federatedModulesBuildPluginImports.ts +68 -0
  464. package/packages/analytics-js/src/components/pluginsManager/index.ts +1 -0
  465. package/packages/analytics-js/src/components/pluginsManager/pluginNames.ts +29 -0
  466. package/packages/analytics-js/src/components/pluginsManager/pluginsInventory.ts +47 -0
  467. package/packages/analytics-js/src/components/pluginsManager/types.ts +4 -0
  468. package/packages/analytics-js/src/components/preloadBuffer/index.ts +187 -0
  469. package/packages/analytics-js/src/components/preloadBuffer/types.ts +5 -0
  470. package/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts +642 -0
  471. package/packages/analytics-js/src/components/userSessionManager/constants.ts +25 -0
  472. package/packages/analytics-js/src/components/userSessionManager/index.ts +1 -0
  473. package/packages/analytics-js/src/components/userSessionManager/types.ts +29 -0
  474. package/packages/analytics-js/src/components/userSessionManager/utils.ts +109 -0
  475. package/packages/analytics-js/src/components/utilities/consent.ts +163 -0
  476. package/packages/analytics-js/src/components/utilities/destinations.ts +31 -0
  477. package/packages/analytics-js/src/components/utilities/event.ts +3 -0
  478. package/packages/analytics-js/src/components/utilities/globals.ts +54 -0
  479. package/packages/analytics-js/src/components/utilities/loadOptions.ts +176 -0
  480. package/packages/analytics-js/src/components/utilities/number.ts +23 -0
  481. package/packages/analytics-js/src/components/utilities/page.ts +103 -0
  482. package/packages/analytics-js/src/components/utilities/sort.ts +15 -0
  483. package/packages/analytics-js/src/components/utilities/statsCollection.ts +16 -0
  484. package/packages/analytics-js/src/components/utilities/url.ts +90 -0
  485. package/packages/analytics-js/src/constants/app.ts +24 -0
  486. package/packages/analytics-js/src/constants/encryption.ts +6 -0
  487. package/packages/analytics-js/src/constants/errors.ts +4 -0
  488. package/packages/analytics-js/src/constants/logMessages.ts +282 -0
  489. package/packages/analytics-js/src/constants/queryParams.ts +13 -0
  490. package/packages/analytics-js/src/constants/storage.ts +40 -0
  491. package/packages/analytics-js/src/constants/timeouts.ts +15 -0
  492. package/packages/analytics-js/src/constants/urls.ts +21 -0
  493. package/packages/analytics-js/src/index.ts +40 -0
  494. package/packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts +204 -0
  495. package/packages/analytics-js/src/services/ErrorHandler/constant.ts +3 -0
  496. package/packages/analytics-js/src/services/ErrorHandler/index.ts +1 -0
  497. package/packages/analytics-js/src/services/ErrorHandler/processError.ts +61 -0
  498. package/packages/analytics-js/src/services/HttpClient/HttpClient.ts +112 -0
  499. package/packages/analytics-js/src/services/HttpClient/index.ts +7 -0
  500. package/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts +140 -0
  501. package/packages/analytics-js/src/services/HttpClient/xhr/xhrResponseHandler.ts +25 -0
  502. package/packages/analytics-js/src/services/Logger/Logger.ts +123 -0
  503. package/packages/analytics-js/src/services/Logger/index.ts +1 -0
  504. package/packages/analytics-js/src/services/Logger/types.ts +6 -0
  505. package/packages/analytics-js/src/services/PluginEngine/PluginEngine.ts +200 -0
  506. package/packages/analytics-js/src/services/PluginEngine/README.md +152 -0
  507. package/packages/analytics-js/src/services/PluginEngine/index.ts +1 -0
  508. package/packages/analytics-js/src/services/StoreManager/Store.ts +218 -0
  509. package/packages/analytics-js/src/services/StoreManager/StoreManager.ts +231 -0
  510. package/packages/analytics-js/src/services/StoreManager/component-cookie/README.md +23 -0
  511. package/packages/analytics-js/src/services/StoreManager/component-cookie/index.ts +138 -0
  512. package/packages/analytics-js/src/services/StoreManager/index.ts +2 -0
  513. package/packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts +80 -0
  514. package/packages/analytics-js/src/services/StoreManager/storages/InMemoryStorage.ts +66 -0
  515. package/packages/analytics-js/src/services/StoreManager/storages/LocalStorage.ts +68 -0
  516. package/packages/analytics-js/src/services/StoreManager/storages/defaultOptions.ts +39 -0
  517. package/packages/analytics-js/src/services/StoreManager/storages/index.ts +18 -0
  518. package/packages/analytics-js/src/services/StoreManager/storages/sessionStorage.ts +64 -0
  519. package/packages/analytics-js/src/services/StoreManager/storages/storageEngine.ts +91 -0
  520. package/packages/analytics-js/src/services/StoreManager/top-domain/README.md +21 -0
  521. package/packages/analytics-js/src/services/StoreManager/top-domain/index.ts +83 -0
  522. package/packages/analytics-js/src/services/StoreManager/types.ts +32 -0
  523. package/packages/analytics-js/src/services/StoreManager/utils.ts +33 -0
  524. package/packages/analytics-js/src/state/index.ts +53 -0
  525. package/packages/analytics-js/src/state/slices/capabilities.ts +19 -0
  526. package/packages/analytics-js/src/state/slices/consents.ts +16 -0
  527. package/packages/analytics-js/src/state/slices/context.ts +36 -0
  528. package/packages/analytics-js/src/state/slices/eventBuffer.ts +9 -0
  529. package/packages/analytics-js/src/state/slices/lifecycle.ts +19 -0
  530. package/packages/analytics-js/src/state/slices/loadOptions.ts +44 -0
  531. package/packages/analytics-js/src/state/slices/metrics.ts +12 -0
  532. package/packages/analytics-js/src/state/slices/nativeDestinations.ts +15 -0
  533. package/packages/analytics-js/src/state/slices/plugins.ts +13 -0
  534. package/packages/analytics-js/src/state/slices/reporting.ts +11 -0
  535. package/packages/analytics-js/src/state/slices/session.ts +24 -0
  536. package/packages/analytics-js/src/state/slices/source.ts +6 -0
  537. package/packages/analytics-js/src/state/slices/storage.ts +13 -0
  538. package/packages/analytics-js/src/types/index.ts +1 -0
  539. package/packages/analytics-js/src/types/remote-plugins.d.ts +15 -0
  540. package/packages/analytics-js/src/types/rudderanalytics.d.ts +16 -0
  541. package/packages/analytics-js/tsconfig.json +14 -0
  542. package/packages/analytics-js/tsconfig.spec.json +26 -0
  543. package/packages/analytics-js-common/.jscpd.json +17 -0
  544. package/packages/analytics-js-common/.size-limit.js +11 -0
  545. package/packages/analytics-js-common/CHANGELOG.md +180 -0
  546. package/packages/analytics-js-common/CHANGELOG_LATEST.md +7 -0
  547. package/packages/analytics-js-common/LICENSE +21 -0
  548. package/packages/analytics-js-common/README.md +42 -0
  549. package/packages/analytics-js-common/__fixtures__/fixtures.ts +161 -0
  550. package/packages/analytics-js-common/__fixtures__/msw.handlers.ts +82 -0
  551. package/packages/analytics-js-common/__fixtures__/msw.server.ts +6 -0
  552. package/packages/analytics-js-common/__mocks__/.gitkeep +0 -0
  553. package/packages/analytics-js-common/__tests__/services/BufferQueue/BufferQueue.test.ts +55 -0
  554. package/packages/analytics-js-common/__tests__/services/ExternalSrcLoader/ExternalSrcLoader.test.ts +170 -0
  555. package/packages/analytics-js-common/__tests__/utilities/checks.test.ts +95 -0
  556. package/packages/analytics-js-common/__tests__/utilities/destinations.test.ts +44 -0
  557. package/packages/analytics-js-common/__tests__/utilities/detect.test.ts +22 -0
  558. package/packages/analytics-js-common/__tests__/utilities/eventMethodOverloads.test.ts +260 -0
  559. package/packages/analytics-js-common/__tests__/utilities/json.test.ts +155 -0
  560. package/packages/analytics-js-common/__tests__/utilities/object.test.ts +287 -0
  561. package/packages/analytics-js-common/__tests__/utilities/string.test.ts +104 -0
  562. package/packages/analytics-js-common/__tests__/utilities/timezone.test.ts +9 -0
  563. package/packages/analytics-js-common/__tests__/utilities/uuid.test.ts +35 -0
  564. package/packages/analytics-js-common/__tests__/v1.1/utils/ObjectUtils.test.js +113 -0
  565. package/packages/analytics-js-common/__tests__/v1.1/utils/errorHandler.test.js +60 -0
  566. package/packages/analytics-js-common/babel.config.json +14 -0
  567. package/packages/analytics-js-common/jest.config.mjs +14 -0
  568. package/packages/analytics-js-common/package.json +92 -0
  569. package/packages/analytics-js-common/project.json +107 -0
  570. package/packages/analytics-js-common/src/constants/QueueStatuses.ts +10 -0
  571. package/packages/analytics-js-common/src/constants/consent.ts +6 -0
  572. package/packages/analytics-js-common/src/constants/destDisplayNamesToFileNamesMap.ts +243 -0
  573. package/packages/analytics-js-common/src/constants/destinationNames.ts +312 -0
  574. package/packages/analytics-js-common/src/constants/htmlAttributes.ts +3 -0
  575. package/packages/analytics-js-common/src/constants/index.ts +11 -0
  576. package/packages/analytics-js-common/src/constants/integrations/ActiveCampaign/constants.js +18 -0
  577. package/packages/analytics-js-common/src/constants/integrations/AdobeAnalytics/constants.ts +18 -0
  578. package/packages/analytics-js-common/src/constants/integrations/Adroll/constants.ts +14 -0
  579. package/packages/analytics-js-common/src/constants/integrations/Amplitude/constants.ts +13 -0
  580. package/packages/analytics-js-common/src/constants/integrations/Appcues/constants.ts +13 -0
  581. package/packages/analytics-js-common/src/constants/integrations/Axeptio/constants.ts +12 -0
  582. package/packages/analytics-js-common/src/constants/integrations/BingAds/constants.ts +16 -0
  583. package/packages/analytics-js-common/src/constants/integrations/Braze/constants.ts +22 -0
  584. package/packages/analytics-js-common/src/constants/integrations/Bugsnag/constants.ts +12 -0
  585. package/packages/analytics-js-common/src/constants/integrations/Chartbeat/constants.ts +14 -0
  586. package/packages/analytics-js-common/src/constants/integrations/Clevertap/constants.ts +12 -0
  587. package/packages/analytics-js-common/src/constants/integrations/CommandBar/constants.ts +21 -0
  588. package/packages/analytics-js-common/src/constants/integrations/CommonIntegrationsConstant/constants.ts +194 -0
  589. package/packages/analytics-js-common/src/constants/integrations/Comscore/constants.ts +15 -0
  590. package/packages/analytics-js-common/src/constants/integrations/ConvertFlow/constants.ts +19 -0
  591. package/packages/analytics-js-common/src/constants/integrations/Criteo/constants.ts +22 -0
  592. package/packages/analytics-js-common/src/constants/integrations/CustomerIO/constants.ts +14 -0
  593. package/packages/analytics-js-common/src/constants/integrations/DCMFloodlight/constants.ts +19 -0
  594. package/packages/analytics-js-common/src/constants/integrations/Drip/constants.ts +12 -0
  595. package/packages/analytics-js-common/src/constants/integrations/Engage/constants.ts +27 -0
  596. package/packages/analytics-js-common/src/constants/integrations/FacebookPixel/constants.ts +89 -0
  597. package/packages/analytics-js-common/src/constants/integrations/Fullstory/constants.ts +17 -0
  598. package/packages/analytics-js-common/src/constants/integrations/GA/constants.ts +14 -0
  599. package/packages/analytics-js-common/src/constants/integrations/GA360/constants.ts +18 -0
  600. package/packages/analytics-js-common/src/constants/integrations/GA4/constants.ts +19 -0
  601. package/packages/analytics-js-common/src/constants/integrations/GoogleAds/constants.ts +15 -0
  602. package/packages/analytics-js-common/src/constants/integrations/GoogleOptimize/constants.ts +17 -0
  603. package/packages/analytics-js-common/src/constants/integrations/GoogleTagManager/constants.ts +14 -0
  604. package/packages/analytics-js-common/src/constants/integrations/Heap/constants.ts +13 -0
  605. package/packages/analytics-js-common/src/constants/integrations/Hotjar/constants.ts +14 -0
  606. package/packages/analytics-js-common/src/constants/integrations/HubSpot/constants.ts +15 -0
  607. package/packages/analytics-js-common/src/constants/integrations/INTERCOM/constants.ts +12 -0
  608. package/packages/analytics-js-common/src/constants/integrations/Iterable/constants.ts +12 -0
  609. package/packages/analytics-js-common/src/constants/integrations/June/constants.ts +12 -0
  610. package/packages/analytics-js-common/src/constants/integrations/Keen/constants.ts +14 -0
  611. package/packages/analytics-js-common/src/constants/integrations/Kissmetrics/constants.ts +12 -0
  612. package/packages/analytics-js-common/src/constants/integrations/Klaviyo/constants.ts +12 -0
  613. package/packages/analytics-js-common/src/constants/integrations/LaunchDarkly/constants.ts +15 -0
  614. package/packages/analytics-js-common/src/constants/integrations/Lemnisk/constants.ts +17 -0
  615. package/packages/analytics-js-common/src/constants/integrations/LinkedInInsightTag/constants.ts +20 -0
  616. package/packages/analytics-js-common/src/constants/integrations/LiveChat/constants.ts +16 -0
  617. package/packages/analytics-js-common/src/constants/integrations/Lotame/constants.ts +12 -0
  618. package/packages/analytics-js-common/src/constants/integrations/Lytics/constants.ts +12 -0
  619. package/packages/analytics-js-common/src/constants/integrations/Matomo/constants.ts +12 -0
  620. package/packages/analytics-js-common/src/constants/integrations/MicrosoftClarity/constants.ts +18 -0
  621. package/packages/analytics-js-common/src/constants/integrations/Mixpanel/constants.ts +15 -0
  622. package/packages/analytics-js-common/src/constants/integrations/MoEngage/constants.ts +16 -0
  623. package/packages/analytics-js-common/src/constants/integrations/Mouseflow/constants.ts +18 -0
  624. package/packages/analytics-js-common/src/constants/integrations/Ninetailed/constants.ts +13 -0
  625. package/packages/analytics-js-common/src/constants/integrations/Olark/constants.ts +12 -0
  626. package/packages/analytics-js-common/src/constants/integrations/Optimizely/constants.ts +12 -0
  627. package/packages/analytics-js-common/src/constants/integrations/Pendo/constants.ts +12 -0
  628. package/packages/analytics-js-common/src/constants/integrations/PinterestTag/constants.ts +23 -0
  629. package/packages/analytics-js-common/src/constants/integrations/Podsights/constants.ts +24 -0
  630. package/packages/analytics-js-common/src/constants/integrations/PostAffiliatePro/constants.ts +17 -0
  631. package/packages/analytics-js-common/src/constants/integrations/Posthog/constants.ts +16 -0
  632. package/packages/analytics-js-common/src/constants/integrations/ProfitWell/constants.ts +16 -0
  633. package/packages/analytics-js-common/src/constants/integrations/Qualaroo/constants.ts +12 -0
  634. package/packages/analytics-js-common/src/constants/integrations/Qualtrics/constants.ts +12 -0
  635. package/packages/analytics-js-common/src/constants/integrations/QuantumMetric/constants.ts +17 -0
  636. package/packages/analytics-js-common/src/constants/integrations/QuoraPixel/constants.ts +19 -0
  637. package/packages/analytics-js-common/src/constants/integrations/RedditPixel/constants.ts +17 -0
  638. package/packages/analytics-js-common/src/constants/integrations/Refiner/constants.ts +12 -0
  639. package/packages/analytics-js-common/src/constants/integrations/Rockerbox/constants.ts +16 -0
  640. package/packages/analytics-js-common/src/constants/integrations/RollBar/constants.ts +17 -0
  641. package/packages/analytics-js-common/src/constants/integrations/Satismeter/constants.ts +12 -0
  642. package/packages/analytics-js-common/src/constants/integrations/Sendinblue/constants.ts +37 -0
  643. package/packages/analytics-js-common/src/constants/integrations/Sentry/constants.ts +12 -0
  644. package/packages/analytics-js-common/src/constants/integrations/Shynet/constants.ts +18 -0
  645. package/packages/analytics-js-common/src/constants/integrations/SnapEngage/constants.ts +16 -0
  646. package/packages/analytics-js-common/src/constants/integrations/SnapPixel/constants.ts +17 -0
  647. package/packages/analytics-js-common/src/constants/integrations/SpotifyPixel/constants.ts +20 -0
  648. package/packages/analytics-js-common/src/constants/integrations/Sprig/constants.ts +12 -0
  649. package/packages/analytics-js-common/src/constants/integrations/TVSquared/constants.ts +18 -0
  650. package/packages/analytics-js-common/src/constants/integrations/TiktokAds/constants.ts +97 -0
  651. package/packages/analytics-js-common/src/constants/integrations/VWO/constants.ts +17 -0
  652. package/packages/analytics-js-common/src/constants/integrations/Vero/constants.ts +12 -0
  653. package/packages/analytics-js-common/src/constants/integrations/Woopra/constants.ts +12 -0
  654. package/packages/analytics-js-common/src/constants/integrations/YandexMetrica/constants.ts +14 -0
  655. package/packages/analytics-js-common/src/constants/integrationsConfig.ts +5 -0
  656. package/packages/analytics-js-common/src/constants/logMessages.ts +24 -0
  657. package/packages/analytics-js-common/src/constants/loggerContexts.ts +33 -0
  658. package/packages/analytics-js-common/src/constants/storages.ts +9 -0
  659. package/packages/analytics-js-common/src/constants/timeouts.ts +3 -0
  660. package/packages/analytics-js-common/src/constants/urls.ts +4 -0
  661. package/packages/analytics-js-common/src/index.ts +4 -0
  662. package/packages/analytics-js-common/src/services/BufferQueue/BufferQueue.ts +37 -0
  663. package/packages/analytics-js-common/src/services/ExternalSrcLoader/ExternalSrcLoader.ts +63 -0
  664. package/packages/analytics-js-common/src/services/ExternalSrcLoader/index.ts +1 -0
  665. package/packages/analytics-js-common/src/services/ExternalSrcLoader/jsFileLoader.ts +124 -0
  666. package/packages/analytics-js-common/src/services/ExternalSrcLoader/types.ts +26 -0
  667. package/packages/analytics-js-common/src/types/ApiObject.ts +14 -0
  668. package/packages/analytics-js-common/src/types/ApplicationLifecycle.ts +12 -0
  669. package/packages/analytics-js-common/src/types/ApplicationState.ts +172 -0
  670. package/packages/analytics-js-common/src/types/Consent.ts +47 -0
  671. package/packages/analytics-js-common/src/types/DataResidency.ts +9 -0
  672. package/packages/analytics-js-common/src/types/Destination.ts +85 -0
  673. package/packages/analytics-js-common/src/types/ErrorHandler.ts +39 -0
  674. package/packages/analytics-js-common/src/types/Event.ts +54 -0
  675. package/packages/analytics-js-common/src/types/EventApi.ts +45 -0
  676. package/packages/analytics-js-common/src/types/EventContext.ts +26 -0
  677. package/packages/analytics-js-common/src/types/HttpClient.ts +63 -0
  678. package/packages/analytics-js-common/src/types/IRudderAnalytics.ts +204 -0
  679. package/packages/analytics-js-common/src/types/Integration.ts +18 -0
  680. package/packages/analytics-js-common/src/types/LoadOptions.ts +159 -0
  681. package/packages/analytics-js-common/src/types/Logger.ts +19 -0
  682. package/packages/analytics-js-common/src/types/Nullable.ts +1 -0
  683. package/packages/analytics-js-common/src/types/PluginEngine.ts +41 -0
  684. package/packages/analytics-js-common/src/types/PluginsManager.ts +29 -0
  685. package/packages/analytics-js-common/src/types/Session.ts +8 -0
  686. package/packages/analytics-js-common/src/types/Source.ts +21 -0
  687. package/packages/analytics-js-common/src/types/Storage.ts +49 -0
  688. package/packages/analytics-js-common/src/types/Store.ts +82 -0
  689. package/packages/analytics-js-common/src/types/UserSessionStorage.ts +10 -0
  690. package/packages/analytics-js-common/src/types/traits.ts +91 -0
  691. package/packages/analytics-js-common/src/utilities/checks.ts +77 -0
  692. package/packages/analytics-js-common/src/utilities/crypto.ts +6 -0
  693. package/packages/analytics-js-common/src/utilities/destinations.ts +31 -0
  694. package/packages/analytics-js-common/src/utilities/detect.ts +8 -0
  695. package/packages/analytics-js-common/src/utilities/errors.ts +20 -0
  696. package/packages/analytics-js-common/src/utilities/eventMethodOverloads.ts +407 -0
  697. package/packages/analytics-js-common/src/utilities/http.ts +13 -0
  698. package/packages/analytics-js-common/src/utilities/index.ts +14 -0
  699. package/packages/analytics-js-common/src/utilities/json.ts +69 -0
  700. package/packages/analytics-js-common/src/utilities/object.ts +119 -0
  701. package/packages/analytics-js-common/src/utilities/string.ts +64 -0
  702. package/packages/analytics-js-common/src/utilities/timestamp.ts +10 -0
  703. package/packages/analytics-js-common/src/utilities/timezone.ts +11 -0
  704. package/packages/analytics-js-common/src/utilities/url.ts +3 -0
  705. package/packages/analytics-js-common/src/utilities/uuId.ts +13 -0
  706. package/packages/analytics-js-common/src/v1.1/utils/ObjectUtils.js +54 -0
  707. package/packages/analytics-js-common/src/v1.1/utils/ScriptLoader.js +51 -0
  708. package/packages/analytics-js-common/src/v1.1/utils/client_server_name.js +82 -0
  709. package/packages/analytics-js-common/src/v1.1/utils/config_to_integration_names.js +83 -0
  710. package/packages/analytics-js-common/src/v1.1/utils/constants.js +15 -0
  711. package/packages/analytics-js-common/src/v1.1/utils/errorHandler.js +88 -0
  712. package/packages/analytics-js-common/src/v1.1/utils/index.ts +10 -0
  713. package/packages/analytics-js-common/src/v1.1/utils/integration_cname.js +164 -0
  714. package/packages/analytics-js-common/src/v1.1/utils/logUtil.js +51 -0
  715. package/packages/analytics-js-common/src/v1.1/utils/notifyError.js +16 -0
  716. package/packages/analytics-js-common/src/v1.1/utils/storage/cookie.js +98 -0
  717. package/packages/analytics-js-common/src/v1.1/utils/storage/index.js +5 -0
  718. package/packages/analytics-js-common/src/v1.1/utils/storage/storage.js +384 -0
  719. package/packages/analytics-js-common/src/v1.1/utils/storage/store.js +79 -0
  720. package/packages/analytics-js-common/src/v1.1/utils/storage/v3DecryptionUtils.js +19 -0
  721. package/packages/analytics-js-common/tsconfig.json +14 -0
  722. package/packages/analytics-js-common/tsconfig.spec.json +23 -0
  723. package/packages/analytics-js-common/types/rudderanalytics.d.ts +16 -0
  724. package/packages/analytics-js-integrations/.jscpd.json +17 -0
  725. package/packages/analytics-js-integrations/.size-limit.js +11 -0
  726. package/packages/analytics-js-integrations/CHANGELOG.md +241 -0
  727. package/packages/analytics-js-integrations/CHANGELOG_LATEST.md +12 -0
  728. package/packages/analytics-js-integrations/LICENSE +21 -0
  729. package/packages/analytics-js-integrations/README.md +35 -0
  730. package/packages/analytics-js-integrations/__fixtures__/.gitkeep +0 -0
  731. package/packages/analytics-js-integrations/__mocks__/.gitkeep +0 -0
  732. package/packages/analytics-js-integrations/__tests__/common/common.test.js +49 -0
  733. package/packages/analytics-js-integrations/__tests__/integrations/Amplitude/browser.test.js +926 -0
  734. package/packages/analytics-js-integrations/__tests__/integrations/Amplitude/util.test.js +190 -0
  735. package/packages/analytics-js-integrations/__tests__/integrations/Appcues/appcues.test.js +163 -0
  736. package/packages/analytics-js-integrations/__tests__/integrations/BingAds/__fixtures__/data.js +17 -0
  737. package/packages/analytics-js-integrations/__tests__/integrations/BingAds/browser.test.js +166 -0
  738. package/packages/analytics-js-integrations/__tests__/integrations/BingAds/utils.test.js +138 -0
  739. package/packages/analytics-js-integrations/__tests__/integrations/Braze/browser.test.js +1077 -0
  740. package/packages/analytics-js-integrations/__tests__/integrations/Clevertap/browser.test.js +43 -0
  741. package/packages/analytics-js-integrations/__tests__/integrations/CommandBar/browser.test.js +115 -0
  742. package/packages/analytics-js-integrations/__tests__/integrations/FacebookPixel/browser.test.js +410 -0
  743. package/packages/analytics-js-integrations/__tests__/integrations/FacebookPixel/utils.test.js +775 -0
  744. package/packages/analytics-js-integrations/__tests__/integrations/Fullstory/browser.test.js +173 -0
  745. package/packages/analytics-js-integrations/__tests__/integrations/GA/browser.test.js +179 -0
  746. package/packages/analytics-js-integrations/__tests__/integrations/GA4/__mocks__/data.js +1563 -0
  747. package/packages/analytics-js-integrations/__tests__/integrations/GA4/browser.test.js +212 -0
  748. package/packages/analytics-js-integrations/__tests__/integrations/GA4/utils.test.js +380 -0
  749. package/packages/analytics-js-integrations/__tests__/integrations/GoogleAds/__fixtures__/data.js +256 -0
  750. package/packages/analytics-js-integrations/__tests__/integrations/GoogleAds/browser.test.js +372 -0
  751. package/packages/analytics-js-integrations/__tests__/integrations/GoogleAds/utils.test.js +121 -0
  752. package/packages/analytics-js-integrations/__tests__/integrations/Hotjar/browser.test.js +108 -0
  753. package/packages/analytics-js-integrations/__tests__/integrations/Intercom/browser.test.js +135 -0
  754. package/packages/analytics-js-integrations/__tests__/integrations/Intercom/util.test.js +69 -0
  755. package/packages/analytics-js-integrations/__tests__/integrations/LaunchDarkly/__fixtures__/data.js +61 -0
  756. package/packages/analytics-js-integrations/__tests__/integrations/LaunchDarkly/browser.test.js +151 -0
  757. package/packages/analytics-js-integrations/__tests__/integrations/LaunchDarkly/utils.test.js +36 -0
  758. package/packages/analytics-js-integrations/__tests__/integrations/Lemnisk/browser.test.js +172 -0
  759. package/packages/analytics-js-integrations/__tests__/integrations/Matomo/browser.test.js +208 -0
  760. package/packages/analytics-js-integrations/__tests__/integrations/Mixpanel/browser.test.js +117 -0
  761. package/packages/analytics-js-integrations/__tests__/integrations/Mixpanel/util.test.js +504 -0
  762. package/packages/analytics-js-integrations/__tests__/integrations/Ninetailed/browser.test.js +148 -0
  763. package/packages/analytics-js-integrations/__tests__/integrations/PinterestTag/__fixtures__/data.js +24 -0
  764. package/packages/analytics-js-integrations/__tests__/integrations/PinterestTag/utils.test.js +19 -0
  765. package/packages/analytics-js-integrations/__tests__/integrations/Podsights/utils.test.js +394 -0
  766. package/packages/analytics-js-integrations/__tests__/integrations/Posthog/browser.test.js +420 -0
  767. package/packages/analytics-js-integrations/__tests__/integrations/Posthog/utils.test.js +111 -0
  768. package/packages/analytics-js-integrations/__tests__/integrations/SpotifyPixel/browser.test.js +630 -0
  769. package/packages/analytics-js-integrations/__tests__/integrations/Sprig/browser.test.js +85 -0
  770. package/packages/analytics-js-integrations/__tests__/integrations/TikTokAds/browser.test.js +421 -0
  771. package/packages/analytics-js-integrations/__tests__/integrations/VWO/browser.test.js +143 -0
  772. package/packages/analytics-js-integrations/__tests__/integrations/VWO/utils.test.js +36 -0
  773. package/packages/analytics-js-integrations/__tests__/utils/camelcase.test.js +29 -0
  774. package/packages/analytics-js-integrations/__tests__/utils/commonUtils.test.js +347 -0
  775. package/packages/analytics-js-integrations/__tests__/utils/utils.test.js +337 -0
  776. package/packages/analytics-js-integrations/babel.config.json +14 -0
  777. package/packages/analytics-js-integrations/jest.config.mjs +21 -0
  778. package/packages/analytics-js-integrations/package.json +143 -0
  779. package/packages/analytics-js-integrations/project.json +106 -0
  780. package/packages/analytics-js-integrations/public/list_integration_sdks.html +408 -0
  781. package/packages/analytics-js-integrations/rollup.config.mjs +151 -0
  782. package/packages/analytics-js-integrations/scripts/integrationBuildScript.js +79 -0
  783. package/packages/analytics-js-integrations/src/integrations/ActiveCampaign/browser.js +53 -0
  784. package/packages/analytics-js-integrations/src/integrations/ActiveCampaign/index.js +1 -0
  785. package/packages/analytics-js-integrations/src/integrations/ActiveCampaign/nativeSdkLoader.js +24 -0
  786. package/packages/analytics-js-integrations/src/integrations/AdobeAnalytics/browser.js +279 -0
  787. package/packages/analytics-js-integrations/src/integrations/AdobeAnalytics/eCommHandle.js +56 -0
  788. package/packages/analytics-js-integrations/src/integrations/AdobeAnalytics/heartbeatHandle.js +268 -0
  789. package/packages/analytics-js-integrations/src/integrations/AdobeAnalytics/index.js +1 -0
  790. package/packages/analytics-js-integrations/src/integrations/AdobeAnalytics/util.js +681 -0
  791. package/packages/analytics-js-integrations/src/integrations/Adroll/browser.js +123 -0
  792. package/packages/analytics-js-integrations/src/integrations/Adroll/index.js +1 -0
  793. package/packages/analytics-js-integrations/src/integrations/Adroll/util.js +48 -0
  794. package/packages/analytics-js-integrations/src/integrations/Amplitude/browser.js +374 -0
  795. package/packages/analytics-js-integrations/src/integrations/Amplitude/index.js +1 -0
  796. package/packages/analytics-js-integrations/src/integrations/Amplitude/nativeSdkLoader.js +114 -0
  797. package/packages/analytics-js-integrations/src/integrations/Amplitude/test/test_amplitude.html +157 -0
  798. package/packages/analytics-js-integrations/src/integrations/Amplitude/utils.js +67 -0
  799. package/packages/analytics-js-integrations/src/integrations/Appcues/browser.js +89 -0
  800. package/packages/analytics-js-integrations/src/integrations/Appcues/index.js +1 -0
  801. package/packages/analytics-js-integrations/src/integrations/Axeptio/browser.js +61 -0
  802. package/packages/analytics-js-integrations/src/integrations/Axeptio/index.js +1 -0
  803. package/packages/analytics-js-integrations/src/integrations/Axeptio/nativeSdkLoader.js +14 -0
  804. package/packages/analytics-js-integrations/src/integrations/Axeptio/utils.js +16 -0
  805. package/packages/analytics-js-integrations/src/integrations/BingAds/browser.js +81 -0
  806. package/packages/analytics-js-integrations/src/integrations/BingAds/index.js +1 -0
  807. package/packages/analytics-js-integrations/src/integrations/BingAds/nativeSdkLoader.js +30 -0
  808. package/packages/analytics-js-integrations/src/integrations/BingAds/utils.js +100 -0
  809. package/packages/analytics-js-integrations/src/integrations/Braze/browser.js +297 -0
  810. package/packages/analytics-js-integrations/src/integrations/Braze/index.js +1 -0
  811. package/packages/analytics-js-integrations/src/integrations/Braze/nativeSdkLoader.js +35 -0
  812. package/packages/analytics-js-integrations/src/integrations/Braze/utils.js +51 -0
  813. package/packages/analytics-js-integrations/src/integrations/Bugsnag/browser.js +62 -0
  814. package/packages/analytics-js-integrations/src/integrations/Bugsnag/index.js +1 -0
  815. package/packages/analytics-js-integrations/src/integrations/Chartbeat/browser.js +143 -0
  816. package/packages/analytics-js-integrations/src/integrations/Chartbeat/index.js +1 -0
  817. package/packages/analytics-js-integrations/src/integrations/Chartbeat/nativeSdkLoader.js +7 -0
  818. package/packages/analytics-js-integrations/src/integrations/Clevertap/browser.js +202 -0
  819. package/packages/analytics-js-integrations/src/integrations/Clevertap/index.js +1 -0
  820. package/packages/analytics-js-integrations/src/integrations/Clevertap/utils.js +17 -0
  821. package/packages/analytics-js-integrations/src/integrations/CommandBar/browser.js +78 -0
  822. package/packages/analytics-js-integrations/src/integrations/CommandBar/index.js +1 -0
  823. package/packages/analytics-js-integrations/src/integrations/CommandBar/nativeSdkLoader.js +85 -0
  824. package/packages/analytics-js-integrations/src/integrations/Comscore/browser.js +126 -0
  825. package/packages/analytics-js-integrations/src/integrations/Comscore/index.js +1 -0
  826. package/packages/analytics-js-integrations/src/integrations/Comscore/nativeSdkLoader.js +10 -0
  827. package/packages/analytics-js-integrations/src/integrations/ConvertFlow/browser.js +60 -0
  828. package/packages/analytics-js-integrations/src/integrations/ConvertFlow/index.js +1 -0
  829. package/packages/analytics-js-integrations/src/integrations/ConvertFlow/utils.js +107 -0
  830. package/packages/analytics-js-integrations/src/integrations/Criteo/browser.js +144 -0
  831. package/packages/analytics-js-integrations/src/integrations/Criteo/index.js +1 -0
  832. package/packages/analytics-js-integrations/src/integrations/Criteo/utils.js +346 -0
  833. package/packages/analytics-js-integrations/src/integrations/CustomerIO/browser.js +85 -0
  834. package/packages/analytics-js-integrations/src/integrations/CustomerIO/index.js +1 -0
  835. package/packages/analytics-js-integrations/src/integrations/CustomerIO/nativeSdkLoader.js +33 -0
  836. package/packages/analytics-js-integrations/src/integrations/DCMFloodlight/browser.js +228 -0
  837. package/packages/analytics-js-integrations/src/integrations/DCMFloodlight/index.js +1 -0
  838. package/packages/analytics-js-integrations/src/integrations/DCMFloodlight/utils.js +353 -0
  839. package/packages/analytics-js-integrations/src/integrations/Drip/browser.js +165 -0
  840. package/packages/analytics-js-integrations/src/integrations/Drip/index.js +1 -0
  841. package/packages/analytics-js-integrations/src/integrations/Drip/nativeSdkLoader.js +10 -0
  842. package/packages/analytics-js-integrations/src/integrations/Drip/utils.js +29 -0
  843. package/packages/analytics-js-integrations/src/integrations/Engage/browser.js +119 -0
  844. package/packages/analytics-js-integrations/src/integrations/Engage/index.js +1 -0
  845. package/packages/analytics-js-integrations/src/integrations/Engage/nativeSdkLoader.js +25 -0
  846. package/packages/analytics-js-integrations/src/integrations/Engage/utils.js +69 -0
  847. package/packages/analytics-js-integrations/src/integrations/FacebookPixel/browser.js +326 -0
  848. package/packages/analytics-js-integrations/src/integrations/FacebookPixel/index.js +1 -0
  849. package/packages/analytics-js-integrations/src/integrations/FacebookPixel/utils.js +332 -0
  850. package/packages/analytics-js-integrations/src/integrations/Fullstory/browser.js +175 -0
  851. package/packages/analytics-js-integrations/src/integrations/Fullstory/index.js +1 -0
  852. package/packages/analytics-js-integrations/src/integrations/Fullstory/nativeSdkLoader.js +69 -0
  853. package/packages/analytics-js-integrations/src/integrations/Fullstory/utils.js +17 -0
  854. package/packages/analytics-js-integrations/src/integrations/GA/browser.js +817 -0
  855. package/packages/analytics-js-integrations/src/integrations/GA/index.js +1 -0
  856. package/packages/analytics-js-integrations/src/integrations/GA360/browser.js +58 -0
  857. package/packages/analytics-js-integrations/src/integrations/GA360/index.js +1 -0
  858. package/packages/analytics-js-integrations/src/integrations/GA4/browser.js +264 -0
  859. package/packages/analytics-js-integrations/src/integrations/GA4/config.js +296 -0
  860. package/packages/analytics-js-integrations/src/integrations/GA4/index.js +1 -0
  861. package/packages/analytics-js-integrations/src/integrations/GA4/utils.js +374 -0
  862. package/packages/analytics-js-integrations/src/integrations/GoogleAds/browser.js +219 -0
  863. package/packages/analytics-js-integrations/src/integrations/GoogleAds/browser.test.js +16 -0
  864. package/packages/analytics-js-integrations/src/integrations/GoogleAds/index.js +1 -0
  865. package/packages/analytics-js-integrations/src/integrations/GoogleAds/nativeSdkLoader.js +28 -0
  866. package/packages/analytics-js-integrations/src/integrations/GoogleAds/utils.js +135 -0
  867. package/packages/analytics-js-integrations/src/integrations/GoogleOptimize/browser.js +81 -0
  868. package/packages/analytics-js-integrations/src/integrations/GoogleOptimize/index.js +1 -0
  869. package/packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js +96 -0
  870. package/packages/analytics-js-integrations/src/integrations/GoogleTagManager/index.js +1 -0
  871. package/packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js +21 -0
  872. package/packages/analytics-js-integrations/src/integrations/Heap/browser.js +64 -0
  873. package/packages/analytics-js-integrations/src/integrations/Heap/index.js +1 -0
  874. package/packages/analytics-js-integrations/src/integrations/Heap/nativeSdkLoader.js +40 -0
  875. package/packages/analytics-js-integrations/src/integrations/Heap/util.js +23 -0
  876. package/packages/analytics-js-integrations/src/integrations/Hotjar/browser.js +79 -0
  877. package/packages/analytics-js-integrations/src/integrations/Hotjar/index.js +1 -0
  878. package/packages/analytics-js-integrations/src/integrations/Hotjar/nativeSdkLoader.js +21 -0
  879. package/packages/analytics-js-integrations/src/integrations/HubSpot/browser.js +91 -0
  880. package/packages/analytics-js-integrations/src/integrations/HubSpot/index.js +1 -0
  881. package/packages/analytics-js-integrations/src/integrations/INTERCOM/browser.js +112 -0
  882. package/packages/analytics-js-integrations/src/integrations/INTERCOM/index.js +1 -0
  883. package/packages/analytics-js-integrations/src/integrations/INTERCOM/nativeSdkLoader.js +46 -0
  884. package/packages/analytics-js-integrations/src/integrations/INTERCOM/utils.js +68 -0
  885. package/packages/analytics-js-integrations/src/integrations/Iterable/browser.js +179 -0
  886. package/packages/analytics-js-integrations/src/integrations/Iterable/index.js +1 -0
  887. package/packages/analytics-js-integrations/src/integrations/Iterable/utils.js +127 -0
  888. package/packages/analytics-js-integrations/src/integrations/June/browser.js +96 -0
  889. package/packages/analytics-js-integrations/src/integrations/June/index.js +1 -0
  890. package/packages/analytics-js-integrations/src/integrations/Keen/browser.js +150 -0
  891. package/packages/analytics-js-integrations/src/integrations/Keen/index.js +1 -0
  892. package/packages/analytics-js-integrations/src/integrations/Kissmetrics/browser.js +245 -0
  893. package/packages/analytics-js-integrations/src/integrations/Kissmetrics/index.js +1 -0
  894. package/packages/analytics-js-integrations/src/integrations/Kissmetrics/nativeSdkLoader.js +23 -0
  895. package/packages/analytics-js-integrations/src/integrations/Klaviyo/browser.js +197 -0
  896. package/packages/analytics-js-integrations/src/integrations/Klaviyo/index.js +1 -0
  897. package/packages/analytics-js-integrations/src/integrations/Klaviyo/util.js +91 -0
  898. package/packages/analytics-js-integrations/src/integrations/LaunchDarkly/browser.js +75 -0
  899. package/packages/analytics-js-integrations/src/integrations/LaunchDarkly/index.js +1 -0
  900. package/packages/analytics-js-integrations/src/integrations/LaunchDarkly/utils.js +40 -0
  901. package/packages/analytics-js-integrations/src/integrations/Lemnisk/browser.js +81 -0
  902. package/packages/analytics-js-integrations/src/integrations/Lemnisk/index.js +1 -0
  903. package/packages/analytics-js-integrations/src/integrations/Lemnisk/nativeSdkLoader.js +34 -0
  904. package/packages/analytics-js-integrations/src/integrations/LinkedInInsightTag/browser.js +79 -0
  905. package/packages/analytics-js-integrations/src/integrations/LinkedInInsightTag/index.js +1 -0
  906. package/packages/analytics-js-integrations/src/integrations/LiveChat/browser.js +81 -0
  907. package/packages/analytics-js-integrations/src/integrations/LiveChat/index.js +1 -0
  908. package/packages/analytics-js-integrations/src/integrations/LiveChat/nativeSdkLoader.js +40 -0
  909. package/packages/analytics-js-integrations/src/integrations/LiveChat/util.js +71 -0
  910. package/packages/analytics-js-integrations/src/integrations/Lotame/LotameStorage.js +21 -0
  911. package/packages/analytics-js-integrations/src/integrations/Lotame/browser.js +152 -0
  912. package/packages/analytics-js-integrations/src/integrations/Lotame/index.js +1 -0
  913. package/packages/analytics-js-integrations/src/integrations/Lytics/browser.js +103 -0
  914. package/packages/analytics-js-integrations/src/integrations/Lytics/index.js +1 -0
  915. package/packages/analytics-js-integrations/src/integrations/Lytics/nativeSdkLoader.js +77 -0
  916. package/packages/analytics-js-integrations/src/integrations/Lytics/test/script-test-lytics.html +250 -0
  917. package/packages/analytics-js-integrations/src/integrations/Matomo/browser.js +184 -0
  918. package/packages/analytics-js-integrations/src/integrations/Matomo/index.js +1 -0
  919. package/packages/analytics-js-integrations/src/integrations/Matomo/nativeSdkLoader.js +20 -0
  920. package/packages/analytics-js-integrations/src/integrations/Matomo/util.js +433 -0
  921. package/packages/analytics-js-integrations/src/integrations/MicrosoftClarity/browser.js +69 -0
  922. package/packages/analytics-js-integrations/src/integrations/MicrosoftClarity/index.js +1 -0
  923. package/packages/analytics-js-integrations/src/integrations/MicrosoftClarity/nativeSdkLoader.js +22 -0
  924. package/packages/analytics-js-integrations/src/integrations/Mixpanel/browser.js +353 -0
  925. package/packages/analytics-js-integrations/src/integrations/Mixpanel/index.js +1 -0
  926. package/packages/analytics-js-integrations/src/integrations/Mixpanel/nativeSdkLoader.js +71 -0
  927. package/packages/analytics-js-integrations/src/integrations/Mixpanel/util.js +288 -0
  928. package/packages/analytics-js-integrations/src/integrations/MoEngage/browser.js +131 -0
  929. package/packages/analytics-js-integrations/src/integrations/MoEngage/index.js +1 -0
  930. package/packages/analytics-js-integrations/src/integrations/MoEngage/nativeSdkLoader.js +65 -0
  931. package/packages/analytics-js-integrations/src/integrations/MoEngage/test/script-test-moengage.html +216 -0
  932. package/packages/analytics-js-integrations/src/integrations/Mouseflow/browser.js +97 -0
  933. package/packages/analytics-js-integrations/src/integrations/Mouseflow/index.js +1 -0
  934. package/packages/analytics-js-integrations/src/integrations/Mouseflow/utils.js +41 -0
  935. package/packages/analytics-js-integrations/src/integrations/Ninetailed/browser.js +65 -0
  936. package/packages/analytics-js-integrations/src/integrations/Ninetailed/index.js +1 -0
  937. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/README.md +70 -0
  938. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/package-lock.json +17843 -0
  939. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/package.json +43 -0
  940. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/public/favicon.ico +0 -0
  941. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/public/index.html +75 -0
  942. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/public/logo192.png +0 -0
  943. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/public/logo512.png +0 -0
  944. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/public/manifest.json +25 -0
  945. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/public/robots.txt +3 -0
  946. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/src/App.css +38 -0
  947. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/src/App.js +108 -0
  948. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/src/index.css +34 -0
  949. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/src/index.js +17 -0
  950. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/src/logo.svg +1 -0
  951. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/src/reportWebVitals.js +13 -0
  952. package/packages/analytics-js-integrations/src/integrations/Ninetailed/sample-app/src/setupTests.js +5 -0
  953. package/packages/analytics-js-integrations/src/integrations/Olark/browser.js +92 -0
  954. package/packages/analytics-js-integrations/src/integrations/Olark/index.js +1 -0
  955. package/packages/analytics-js-integrations/src/integrations/Olark/nativeSdkLoader.js +31 -0
  956. package/packages/analytics-js-integrations/src/integrations/Olark/utils.js +51 -0
  957. package/packages/analytics-js-integrations/src/integrations/Optimizely/browser.js +244 -0
  958. package/packages/analytics-js-integrations/src/integrations/Optimizely/index.js +1 -0
  959. package/packages/analytics-js-integrations/src/integrations/Optimizely/utils.js +23 -0
  960. package/packages/analytics-js-integrations/src/integrations/Pendo/browser.js +123 -0
  961. package/packages/analytics-js-integrations/src/integrations/Pendo/index.js +1 -0
  962. package/packages/analytics-js-integrations/src/integrations/Pendo/nativeSdkLoader.js +32 -0
  963. package/packages/analytics-js-integrations/src/integrations/PinterestTag/browser.js +240 -0
  964. package/packages/analytics-js-integrations/src/integrations/PinterestTag/index.js +1 -0
  965. package/packages/analytics-js-integrations/src/integrations/PinterestTag/nativeSdkLoader.js +19 -0
  966. package/packages/analytics-js-integrations/src/integrations/PinterestTag/propertyMappingConfig.js +57 -0
  967. package/packages/analytics-js-integrations/src/integrations/PinterestTag/test/input.js +180 -0
  968. package/packages/analytics-js-integrations/src/integrations/PinterestTag/test/output.js +129 -0
  969. package/packages/analytics-js-integrations/src/integrations/PinterestTag/utils.js +50 -0
  970. package/packages/analytics-js-integrations/src/integrations/Podsights/browser.js +179 -0
  971. package/packages/analytics-js-integrations/src/integrations/Podsights/index.js +1 -0
  972. package/packages/analytics-js-integrations/src/integrations/Podsights/utils.js +64 -0
  973. package/packages/analytics-js-integrations/src/integrations/PostAffiliatePro/browser.js +132 -0
  974. package/packages/analytics-js-integrations/src/integrations/PostAffiliatePro/index.js +1 -0
  975. package/packages/analytics-js-integrations/src/integrations/PostAffiliatePro/utils.js +40 -0
  976. package/packages/analytics-js-integrations/src/integrations/Posthog/browser.js +147 -0
  977. package/packages/analytics-js-integrations/src/integrations/Posthog/index.js +1 -0
  978. package/packages/analytics-js-integrations/src/integrations/Posthog/nativeSdkLoader.js +48 -0
  979. package/packages/analytics-js-integrations/src/integrations/Posthog/test/test_posthog.html +77 -0
  980. package/packages/analytics-js-integrations/src/integrations/Posthog/utils.js +52 -0
  981. package/packages/analytics-js-integrations/src/integrations/ProfitWell/browser.js +71 -0
  982. package/packages/analytics-js-integrations/src/integrations/ProfitWell/index.js +1 -0
  983. package/packages/analytics-js-integrations/src/integrations/ProfitWell/nativeSdkLoader.js +25 -0
  984. package/packages/analytics-js-integrations/src/integrations/Qualaroo/browser.js +116 -0
  985. package/packages/analytics-js-integrations/src/integrations/Qualaroo/index.js +1 -0
  986. package/packages/analytics-js-integrations/src/integrations/Qualaroo/utils.js +83 -0
  987. package/packages/analytics-js-integrations/src/integrations/Qualtrics/browser.js +92 -0
  988. package/packages/analytics-js-integrations/src/integrations/Qualtrics/index.js +1 -0
  989. package/packages/analytics-js-integrations/src/integrations/Qualtrics/nativeSdkLoader.js +79 -0
  990. package/packages/analytics-js-integrations/src/integrations/QuantumMetric/browser.js +54 -0
  991. package/packages/analytics-js-integrations/src/integrations/QuantumMetric/index.js +1 -0
  992. package/packages/analytics-js-integrations/src/integrations/QuoraPixel/browser.js +77 -0
  993. package/packages/analytics-js-integrations/src/integrations/QuoraPixel/index.js +1 -0
  994. package/packages/analytics-js-integrations/src/integrations/QuoraPixel/nativeSdkLoader.js +21 -0
  995. package/packages/analytics-js-integrations/src/integrations/RedditPixel/browser.js +103 -0
  996. package/packages/analytics-js-integrations/src/integrations/RedditPixel/index.js +1 -0
  997. package/packages/analytics-js-integrations/src/integrations/RedditPixel/nativeSdkLoader.js +21 -0
  998. package/packages/analytics-js-integrations/src/integrations/Refiner/browser.js +117 -0
  999. package/packages/analytics-js-integrations/src/integrations/Refiner/index.js +1 -0
  1000. package/packages/analytics-js-integrations/src/integrations/Refiner/nativeSdkLoader.js +20 -0
  1001. package/packages/analytics-js-integrations/src/integrations/Refiner/utils.js +44 -0
  1002. package/packages/analytics-js-integrations/src/integrations/Rockerbox/browser.js +90 -0
  1003. package/packages/analytics-js-integrations/src/integrations/Rockerbox/index.js +1 -0
  1004. package/packages/analytics-js-integrations/src/integrations/Rockerbox/nativeSdkLoader.js +32 -0
  1005. package/packages/analytics-js-integrations/src/integrations/RollBar/browser.js +93 -0
  1006. package/packages/analytics-js-integrations/src/integrations/RollBar/index.js +1 -0
  1007. package/packages/analytics-js-integrations/src/integrations/RollBar/nativeSdkLoader.js +383 -0
  1008. package/packages/analytics-js-integrations/src/integrations/Satismeter/browser.js +92 -0
  1009. package/packages/analytics-js-integrations/src/integrations/Satismeter/index.js +1 -0
  1010. package/packages/analytics-js-integrations/src/integrations/Satismeter/nativeSdkLoader.js +23 -0
  1011. package/packages/analytics-js-integrations/src/integrations/Satismeter/util.js +54 -0
  1012. package/packages/analytics-js-integrations/src/integrations/Sendinblue/browser.js +111 -0
  1013. package/packages/analytics-js-integrations/src/integrations/Sendinblue/index.js +1 -0
  1014. package/packages/analytics-js-integrations/src/integrations/Sendinblue/nativeSdkLoader.js +36 -0
  1015. package/packages/analytics-js-integrations/src/integrations/Sendinblue/utils.js +129 -0
  1016. package/packages/analytics-js-integrations/src/integrations/Sentry/browser.js +120 -0
  1017. package/packages/analytics-js-integrations/src/integrations/Sentry/index.js +1 -0
  1018. package/packages/analytics-js-integrations/src/integrations/Sentry/utils.js +84 -0
  1019. package/packages/analytics-js-integrations/src/integrations/Shynet/browser.js +99 -0
  1020. package/packages/analytics-js-integrations/src/integrations/Shynet/index.js +1 -0
  1021. package/packages/analytics-js-integrations/src/integrations/SnapEngage/browser.js +74 -0
  1022. package/packages/analytics-js-integrations/src/integrations/SnapEngage/index.js +1 -0
  1023. package/packages/analytics-js-integrations/src/integrations/SnapEngage/nativeSdkLoader.js +24 -0
  1024. package/packages/analytics-js-integrations/src/integrations/SnapEngage/util.js +63 -0
  1025. package/packages/analytics-js-integrations/src/integrations/SnapPixel/browser.js +226 -0
  1026. package/packages/analytics-js-integrations/src/integrations/SnapPixel/index.js +1 -0
  1027. package/packages/analytics-js-integrations/src/integrations/SnapPixel/nativeSdkLoader.js +20 -0
  1028. package/packages/analytics-js-integrations/src/integrations/SnapPixel/util.js +214 -0
  1029. package/packages/analytics-js-integrations/src/integrations/SpotifyPixel/browser.js +180 -0
  1030. package/packages/analytics-js-integrations/src/integrations/SpotifyPixel/index.js +1 -0
  1031. package/packages/analytics-js-integrations/src/integrations/Sprig/browser.js +89 -0
  1032. package/packages/analytics-js-integrations/src/integrations/Sprig/index.js +1 -0
  1033. package/packages/analytics-js-integrations/src/integrations/Sprig/nativeSdkLoader.js +19 -0
  1034. package/packages/analytics-js-integrations/src/integrations/TVSquared/browser.js +99 -0
  1035. package/packages/analytics-js-integrations/src/integrations/TVSquared/index.js +1 -0
  1036. package/packages/analytics-js-integrations/src/integrations/TVSquared/utils.js +41 -0
  1037. package/packages/analytics-js-integrations/src/integrations/TiktokAds/browser.js +111 -0
  1038. package/packages/analytics-js-integrations/src/integrations/TiktokAds/index.js +1 -0
  1039. package/packages/analytics-js-integrations/src/integrations/TiktokAds/nativeSdkLoader.js +52 -0
  1040. package/packages/analytics-js-integrations/src/integrations/TiktokAds/util.js +70 -0
  1041. package/packages/analytics-js-integrations/src/integrations/VWO/browser.js +155 -0
  1042. package/packages/analytics-js-integrations/src/integrations/VWO/index.js +1 -0
  1043. package/packages/analytics-js-integrations/src/integrations/VWO/nativeSdkLoader.js +64 -0
  1044. package/packages/analytics-js-integrations/src/integrations/VWO/utils.js +42 -0
  1045. package/packages/analytics-js-integrations/src/integrations/Vero/browser.js +166 -0
  1046. package/packages/analytics-js-integrations/src/integrations/Vero/index.js +1 -0
  1047. package/packages/analytics-js-integrations/src/integrations/Vero/utils.js +17 -0
  1048. package/packages/analytics-js-integrations/src/integrations/Woopra/browser.js +82 -0
  1049. package/packages/analytics-js-integrations/src/integrations/Woopra/index.js +1 -0
  1050. package/packages/analytics-js-integrations/src/integrations/Woopra/nativeSdkLoader.js +43 -0
  1051. package/packages/analytics-js-integrations/src/integrations/YandexMetrica/browser.js +139 -0
  1052. package/packages/analytics-js-integrations/src/integrations/YandexMetrica/index.js +1 -0
  1053. package/packages/analytics-js-integrations/src/integrations/YandexMetrica/nativeSdkLoader.js +35 -0
  1054. package/packages/analytics-js-integrations/src/integrations/YandexMetrica/utils.js +140 -0
  1055. package/packages/analytics-js-integrations/src/integrations/index.js +163 -0
  1056. package/packages/analytics-js-integrations/src/utils/camelcase.js +48 -0
  1057. package/packages/analytics-js-integrations/src/utils/commonUtils.js +214 -0
  1058. package/packages/analytics-js-integrations/src/utils/constants.js +4 -0
  1059. package/packages/analytics-js-integrations/src/utils/logger.js +106 -0
  1060. package/packages/analytics-js-integrations/src/utils/utils.js +585 -0
  1061. package/packages/analytics-js-integrations/tsconfig.json +8 -0
  1062. package/packages/analytics-js-integrations/tsconfig.spec.json +26 -0
  1063. package/packages/analytics-js-plugins/.jscpd.json +17 -0
  1064. package/packages/analytics-js-plugins/.size-limit.js +16 -0
  1065. package/packages/analytics-js-plugins/CHANGELOG.md +212 -0
  1066. package/packages/analytics-js-plugins/CHANGELOG_LATEST.md +7 -0
  1067. package/packages/analytics-js-plugins/LICENSE +21 -0
  1068. package/packages/analytics-js-plugins/README.md +57 -0
  1069. package/packages/analytics-js-plugins/__fixtures__/.gitkeep +0 -0
  1070. package/packages/analytics-js-plugins/__fixtures__/fixtures.ts +174 -0
  1071. package/packages/analytics-js-plugins/__fixtures__/msw.handlers.js +45 -0
  1072. package/packages/analytics-js-plugins/__fixtures__/msw.server.js +6 -0
  1073. package/packages/analytics-js-plugins/__mocks__/.gitkeep +0 -0
  1074. package/packages/analytics-js-plugins/__tests__/beaconQueue/.gitkeep +0 -0
  1075. package/packages/analytics-js-plugins/__tests__/bugsnag/index.test.ts +116 -0
  1076. package/packages/analytics-js-plugins/__tests__/bugsnag/utils.test.ts +555 -0
  1077. package/packages/analytics-js-plugins/__tests__/customConsentManager/index.test.ts +264 -0
  1078. package/packages/analytics-js-plugins/__tests__/deviceModeDestinations/utils.test.ts +260 -0
  1079. package/packages/analytics-js-plugins/__tests__/deviceModeTransformation/.gitkeep +0 -0
  1080. package/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts +287 -0
  1081. package/packages/analytics-js-plugins/__tests__/deviceModeTransformation/utilities.test.ts +22 -0
  1082. package/packages/analytics-js-plugins/__tests__/errorReporting/index.test.ts +102 -0
  1083. package/packages/analytics-js-plugins/__tests__/externalAnonymousId/.gitkeep +0 -0
  1084. package/packages/analytics-js-plugins/__tests__/googleLinker/.gitkeep +0 -0
  1085. package/packages/analytics-js-plugins/__tests__/ketchConsentManager/index.test.ts +498 -0
  1086. package/packages/analytics-js-plugins/__tests__/ketchConsentManager/utils.test.ts +189 -0
  1087. package/packages/analytics-js-plugins/__tests__/nativeDestinationQueue/utilities.test.ts +98 -0
  1088. package/packages/analytics-js-plugins/__tests__/oneTrustConsentManager/index.test.ts +395 -0
  1089. package/packages/analytics-js-plugins/__tests__/storageEncryption/index.test.ts +37 -0
  1090. package/packages/analytics-js-plugins/__tests__/storageEncryptionLegacy/index.test.ts +41 -0
  1091. package/packages/analytics-js-plugins/__tests__/storageMigrator/.gitkeep +0 -0
  1092. package/packages/analytics-js-plugins/__tests__/storageMigrator/index.test.ts +144 -0
  1093. package/packages/analytics-js-plugins/__tests__/utilities/destination.test.ts +133 -0
  1094. package/packages/analytics-js-plugins/__tests__/utilities/queue.test.ts +327 -0
  1095. package/packages/analytics-js-plugins/__tests__/utilities/retryQueue/RetryQueue.test.ts +1077 -0
  1096. package/packages/analytics-js-plugins/__tests__/utilities/retryQueue/Schedule.test.ts +78 -0
  1097. package/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts +320 -0
  1098. package/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts +388 -0
  1099. package/packages/analytics-js-plugins/babel.config.json +14 -0
  1100. package/packages/analytics-js-plugins/jest.config.mjs +14 -0
  1101. package/packages/analytics-js-plugins/package.json +106 -0
  1102. package/packages/analytics-js-plugins/project.json +131 -0
  1103. package/packages/analytics-js-plugins/public/.gitkeep +0 -0
  1104. package/packages/analytics-js-plugins/rollup.config.mjs +245 -0
  1105. package/packages/analytics-js-plugins/src/beaconQueue/constants.ts +27 -0
  1106. package/packages/analytics-js-plugins/src/beaconQueue/index.ts +146 -0
  1107. package/packages/analytics-js-plugins/src/beaconQueue/logMessages.ts +24 -0
  1108. package/packages/analytics-js-plugins/src/beaconQueue/types.ts +12 -0
  1109. package/packages/analytics-js-plugins/src/beaconQueue/utilities.ts +68 -0
  1110. package/packages/analytics-js-plugins/src/bugsnag/constants.ts +52 -0
  1111. package/packages/analytics-js-plugins/src/bugsnag/index.ts +65 -0
  1112. package/packages/analytics-js-plugins/src/bugsnag/logMessages.ts +19 -0
  1113. package/packages/analytics-js-plugins/src/bugsnag/utils.ts +214 -0
  1114. package/packages/analytics-js-plugins/src/customConsentManager/constants.ts +3 -0
  1115. package/packages/analytics-js-plugins/src/customConsentManager/index.ts +86 -0
  1116. package/packages/analytics-js-plugins/src/customConsentManager/logMessages.ts +3 -0
  1117. package/packages/analytics-js-plugins/src/deviceModeDestinations/constants.ts +6 -0
  1118. package/packages/analytics-js-plugins/src/deviceModeDestinations/index.ts +138 -0
  1119. package/packages/analytics-js-plugins/src/deviceModeDestinations/logMessages.ts +24 -0
  1120. package/packages/analytics-js-plugins/src/deviceModeDestinations/types.ts +28 -0
  1121. package/packages/analytics-js-plugins/src/deviceModeDestinations/utils.ts +249 -0
  1122. package/packages/analytics-js-plugins/src/deviceModeTransformation/constants.ts +12 -0
  1123. package/packages/analytics-js-plugins/src/deviceModeTransformation/index.ts +111 -0
  1124. package/packages/analytics-js-plugins/src/deviceModeTransformation/logMessages.ts +28 -0
  1125. package/packages/analytics-js-plugins/src/deviceModeTransformation/types.ts +38 -0
  1126. package/packages/analytics-js-plugins/src/deviceModeTransformation/utilities.ts +155 -0
  1127. package/packages/analytics-js-plugins/src/errorReporting/index.ts +62 -0
  1128. package/packages/analytics-js-plugins/src/errorReporting/logMessages.ts +3 -0
  1129. package/packages/analytics-js-plugins/src/externalAnonymousId/constants.ts +5 -0
  1130. package/packages/analytics-js-plugins/src/externalAnonymousId/index.ts +47 -0
  1131. package/packages/analytics-js-plugins/src/externalAnonymousId/util.ts +25 -0
  1132. package/packages/analytics-js-plugins/src/googleLinker/base64Decoder.ts +33 -0
  1133. package/packages/analytics-js-plugins/src/googleLinker/constants.ts +1 -0
  1134. package/packages/analytics-js-plugins/src/googleLinker/crc32.ts +44 -0
  1135. package/packages/analytics-js-plugins/src/googleLinker/index.ts +30 -0
  1136. package/packages/analytics-js-plugins/src/googleLinker/userLib.ts +16 -0
  1137. package/packages/analytics-js-plugins/src/googleLinker/utils.ts +156 -0
  1138. package/packages/analytics-js-plugins/src/index.ts +15 -0
  1139. package/packages/analytics-js-plugins/src/ketchConsentManager/constants.ts +4 -0
  1140. package/packages/analytics-js-plugins/src/ketchConsentManager/index.ts +120 -0
  1141. package/packages/analytics-js-plugins/src/ketchConsentManager/logMessages.ts +15 -0
  1142. package/packages/analytics-js-plugins/src/ketchConsentManager/types.ts +11 -0
  1143. package/packages/analytics-js-plugins/src/ketchConsentManager/utils.ts +95 -0
  1144. package/packages/analytics-js-plugins/src/nativeDestinationQueue/constants.ts +9 -0
  1145. package/packages/analytics-js-plugins/src/nativeDestinationQueue/index.ts +159 -0
  1146. package/packages/analytics-js-plugins/src/nativeDestinationQueue/logMessages.ts +14 -0
  1147. package/packages/analytics-js-plugins/src/nativeDestinationQueue/utilities.ts +81 -0
  1148. package/packages/analytics-js-plugins/src/oneTrustConsentManager/constants.ts +3 -0
  1149. package/packages/analytics-js-plugins/src/oneTrustConsentManager/index.ts +131 -0
  1150. package/packages/analytics-js-plugins/src/oneTrustConsentManager/logMessages.ts +8 -0
  1151. package/packages/analytics-js-plugins/src/oneTrustConsentManager/types.ts +4 -0
  1152. package/packages/analytics-js-plugins/src/shared-chunks/common.ts +13 -0
  1153. package/packages/analytics-js-plugins/src/shared-chunks/deviceModeDestinations.ts +3 -0
  1154. package/packages/analytics-js-plugins/src/storageEncryption/constants.ts +1 -0
  1155. package/packages/analytics-js-plugins/src/storageEncryption/encryptionUtils.ts +14 -0
  1156. package/packages/analytics-js-plugins/src/storageEncryption/index.ts +26 -0
  1157. package/packages/analytics-js-plugins/src/storageEncryptionLegacy/constants.ts +2 -0
  1158. package/packages/analytics-js-plugins/src/storageEncryptionLegacy/index.ts +26 -0
  1159. package/packages/analytics-js-plugins/src/storageEncryptionLegacy/legacyEncryptionUtils.ts +18 -0
  1160. package/packages/analytics-js-plugins/src/storageMigrator/constants.ts +3 -0
  1161. package/packages/analytics-js-plugins/src/storageMigrator/index.ts +59 -0
  1162. package/packages/analytics-js-plugins/src/storageMigrator/logMessages.ts +4 -0
  1163. package/packages/analytics-js-plugins/src/types/plugins.ts +69 -0
  1164. package/packages/analytics-js-plugins/src/utilities/constants.ts +3 -0
  1165. package/packages/analytics-js-plugins/src/utilities/destination.ts +40 -0
  1166. package/packages/analytics-js-plugins/src/utilities/eventsDelivery.ts +85 -0
  1167. package/packages/analytics-js-plugins/src/utilities/retryQueue/README.md +135 -0
  1168. package/packages/analytics-js-plugins/src/utilities/retryQueue/RetryQueue.ts +736 -0
  1169. package/packages/analytics-js-plugins/src/utilities/retryQueue/Schedule.ts +101 -0
  1170. package/packages/analytics-js-plugins/src/utilities/retryQueue/constants.ts +32 -0
  1171. package/packages/analytics-js-plugins/src/utilities/retryQueue/logMessages.ts +9 -0
  1172. package/packages/analytics-js-plugins/src/utilities/retryQueue/types.ts +21 -0
  1173. package/packages/analytics-js-plugins/src/xhrQueue/constants.ts +23 -0
  1174. package/packages/analytics-js-plugins/src/xhrQueue/index.ts +158 -0
  1175. package/packages/analytics-js-plugins/src/xhrQueue/logMessages.ts +6 -0
  1176. package/packages/analytics-js-plugins/src/xhrQueue/types.ts +16 -0
  1177. package/packages/analytics-js-plugins/src/xhrQueue/utilities.ts +103 -0
  1178. package/packages/analytics-js-plugins/tsconfig.json +14 -0
  1179. package/packages/analytics-js-plugins/tsconfig.spec.json +24 -0
  1180. package/packages/analytics-js-service-worker/.env.example +8 -0
  1181. package/packages/analytics-js-service-worker/.jscpd.json +17 -0
  1182. package/packages/analytics-js-service-worker/.size-limit.js +11 -0
  1183. package/packages/analytics-js-service-worker/CHANGELOG.md +91 -0
  1184. package/packages/analytics-js-service-worker/CHANGELOG_LATEST.md +7 -0
  1185. package/packages/analytics-js-service-worker/LICENSE +21 -0
  1186. package/packages/analytics-js-service-worker/README.md +74 -0
  1187. package/packages/analytics-js-service-worker/__fixtures__/fixtures.ts +79 -0
  1188. package/packages/analytics-js-service-worker/__fixtures__/msw.server.ts +13 -0
  1189. package/packages/analytics-js-service-worker/__mocks__/.gitkeep +0 -0
  1190. package/packages/analytics-js-service-worker/__tests__/Analytics.test.ts +120 -0
  1191. package/packages/analytics-js-service-worker/__tests__/loosely-validate-event/index.test.ts +140 -0
  1192. package/packages/analytics-js-service-worker/babel.config.json +15 -0
  1193. package/packages/analytics-js-service-worker/jest.config.mjs +14 -0
  1194. package/packages/analytics-js-service-worker/package.json +103 -0
  1195. package/packages/analytics-js-service-worker/project.json +104 -0
  1196. package/packages/analytics-js-service-worker/public/.gitkeep +0 -0
  1197. package/packages/analytics-js-service-worker/rollup.config.mjs +140 -0
  1198. package/packages/analytics-js-service-worker/src/Analytics.ts +564 -0
  1199. package/packages/analytics-js-service-worker/src/IAnalytics.ts +141 -0
  1200. package/packages/analytics-js-service-worker/src/index.ts +9 -0
  1201. package/packages/analytics-js-service-worker/src/loosely-validate-event/index.ts +136 -0
  1202. package/packages/analytics-js-service-worker/src/types.ts +67 -0
  1203. package/packages/analytics-js-service-worker/tsconfig.json +8 -0
  1204. package/packages/analytics-js-service-worker/tsconfig.spec.json +22 -0
  1205. package/packages/analytics-v1.1/.env.example +8 -0
  1206. package/packages/analytics-v1.1/.jscpd.json +17 -0
  1207. package/packages/analytics-v1.1/.size-limit.js +16 -0
  1208. package/packages/analytics-v1.1/.versionrc +12 -0
  1209. package/packages/analytics-v1.1/CHANGELOG.md +3859 -0
  1210. package/packages/analytics-v1.1/CHANGELOG_LATEST.md +5 -0
  1211. package/packages/analytics-v1.1/LICENSE +21 -0
  1212. package/packages/analytics-v1.1/README.md +321 -0
  1213. package/packages/analytics-v1.1/__fixtures__/fixtures.js +130 -0
  1214. package/packages/analytics-v1.1/__fixtures__/msw.handlers.js +51 -0
  1215. package/packages/analytics-v1.1/__fixtures__/msw.server.js +6 -0
  1216. package/packages/analytics-v1.1/__mocks__/.gitkeep +0 -0
  1217. package/packages/analytics-v1.1/__tests__/data-residency.test.js +236 -0
  1218. package/packages/analytics-v1.1/__tests__/features/core/metrics/errorReporting/ErrorReportingService.test.js +80 -0
  1219. package/packages/analytics-v1.1/__tests__/ketchConsent.test.js +49 -0
  1220. package/packages/analytics-v1.1/__tests__/oneTrustCookieConsent.test.js +89 -0
  1221. package/packages/analytics-v1.1/__tests__/script.test.js +167 -0
  1222. package/packages/analytics-v1.1/__tests__/transformationHandler.test.js +179 -0
  1223. package/packages/analytics-v1.1/__tests__/utils/IntegrationsData.test.js +105 -0
  1224. package/packages/analytics-v1.1/__tests__/utils/cdnPaths.test.js +63 -0
  1225. package/packages/analytics-v1.1/__tests__/utils/clientHint.test.js +87 -0
  1226. package/packages/analytics-v1.1/__tests__/utils/eventProcessorUtils.test.js +264 -0
  1227. package/packages/analytics-v1.1/__tests__/utils/navigator.test.js +38 -0
  1228. package/packages/analytics-v1.1/__tests__/utils/preProcessQueue.test.js +78 -0
  1229. package/packages/analytics-v1.1/__tests__/utils/screenDetails.test.js +19 -0
  1230. package/packages/analytics-v1.1/__tests__/utils/utils.test.js +69 -0
  1231. package/packages/analytics-v1.1/babel.config.json +14 -0
  1232. package/packages/analytics-v1.1/jest.config.mjs +14 -0
  1233. package/packages/analytics-v1.1/package.json +115 -0
  1234. package/packages/analytics-v1.1/project.json +119 -0
  1235. package/packages/analytics-v1.1/public/index.html +137 -0
  1236. package/packages/analytics-v1.1/rollup-configs/rollup.sdk.browser.mjs +32 -0
  1237. package/packages/analytics-v1.1/rollup-configs/rollup.sdk.npm.mjs +53 -0
  1238. package/packages/analytics-v1.1/rollup-configs/rollup.utilities.mjs +160 -0
  1239. package/packages/analytics-v1.1/src/core/analytics.js +1669 -0
  1240. package/packages/analytics-v1.1/src/features/core/cookieConsent/CookieConsentFactory.js +32 -0
  1241. package/packages/analytics-v1.1/src/features/core/cookieConsent/OneTrust/browser.js +102 -0
  1242. package/packages/analytics-v1.1/src/features/core/cookieConsent/OneTrust/index.js +1 -0
  1243. package/packages/analytics-v1.1/src/features/core/cookieConsent/ketch/browser.js +114 -0
  1244. package/packages/analytics-v1.1/src/features/core/cookieConsent/ketch/index.js +1 -0
  1245. package/packages/analytics-v1.1/src/features/core/deviceModeTransformation/transformationHandler.js +196 -0
  1246. package/packages/analytics-v1.1/src/features/core/deviceModeTransformation/util.js +23 -0
  1247. package/packages/analytics-v1.1/src/features/core/metrics/errorReporting/ErrorReportingService.js +116 -0
  1248. package/packages/analytics-v1.1/src/features/core/metrics/errorReporting/providers/Bugsnag.js +247 -0
  1249. package/packages/analytics-v1.1/src/features/core/session/index.js +207 -0
  1250. package/packages/analytics-v1.1/src/utils/EventRepository.js +79 -0
  1251. package/packages/analytics-v1.1/src/utils/IntegrationsData.js +56 -0
  1252. package/packages/analytics-v1.1/src/utils/JSFileLoader.js +66 -0
  1253. package/packages/analytics-v1.1/src/utils/PreProcessQueue.js +66 -0
  1254. package/packages/analytics-v1.1/src/utils/RudderApp.js +9 -0
  1255. package/packages/analytics-v1.1/src/utils/RudderContext.js +23 -0
  1256. package/packages/analytics-v1.1/src/utils/RudderElement.js +33 -0
  1257. package/packages/analytics-v1.1/src/utils/RudderElementBuilder.js +29 -0
  1258. package/packages/analytics-v1.1/src/utils/RudderInfo.js +41 -0
  1259. package/packages/analytics-v1.1/src/utils/RudderMessage.js +28 -0
  1260. package/packages/analytics-v1.1/src/utils/beaconQueue.js +140 -0
  1261. package/packages/analytics-v1.1/src/utils/cdnPaths.js +43 -0
  1262. package/packages/analytics-v1.1/src/utils/clientHint.js +28 -0
  1263. package/packages/analytics-v1.1/src/utils/constants.js +70 -0
  1264. package/packages/analytics-v1.1/src/utils/eventProcessorUtils.js +53 -0
  1265. package/packages/analytics-v1.1/src/utils/linker/base64decoder.js +29 -0
  1266. package/packages/analytics-v1.1/src/utils/linker/crc32.js +42 -0
  1267. package/packages/analytics-v1.1/src/utils/linker/index.js +134 -0
  1268. package/packages/analytics-v1.1/src/utils/linker/userLib.js +20 -0
  1269. package/packages/analytics-v1.1/src/utils/navigator.js +32 -0
  1270. package/packages/analytics-v1.1/src/utils/pageProperties.js +74 -0
  1271. package/packages/analytics-v1.1/src/utils/screenDetails.js +23 -0
  1272. package/packages/analytics-v1.1/src/utils/utils.js +423 -0
  1273. package/packages/analytics-v1.1/src/utils/xhrModule.js +117 -0
  1274. package/packages/analytics-v1.1/tsconfig.json +8 -0
  1275. package/packages/analytics-v1.1/tsconfig.spec.json +26 -0
  1276. package/packages/analytics-v1.1/types/index.d.ts +472 -0
  1277. package/packages/analytics-v1.1/types/service-worker/index.d.ts +220 -0
  1278. package/packages/loading-scripts/.env.example +11 -0
  1279. package/packages/loading-scripts/.jscpd.json +17 -0
  1280. package/packages/loading-scripts/CHANGELOG.md +130 -0
  1281. package/packages/loading-scripts/CHANGELOG_LATEST.md +2 -0
  1282. package/packages/loading-scripts/LICENSE +21 -0
  1283. package/packages/loading-scripts/README.md +26 -0
  1284. package/packages/loading-scripts/__fixtures__/.gitkeep +0 -0
  1285. package/packages/loading-scripts/__mocks__/.gitkeep +0 -0
  1286. package/packages/loading-scripts/__tests__/.gitkeep +0 -0
  1287. package/packages/loading-scripts/babel.config.json +14 -0
  1288. package/packages/loading-scripts/jest.config.mjs +14 -0
  1289. package/packages/loading-scripts/package.json +62 -0
  1290. package/packages/loading-scripts/project.json +101 -0
  1291. package/packages/loading-scripts/public/index.html +180 -0
  1292. package/packages/loading-scripts/rollup.config.mjs +112 -0
  1293. package/packages/loading-scripts/src/index.ts +106 -0
  1294. package/packages/loading-scripts/src/types/rudderanalytics.d.ts +16 -0
  1295. package/packages/loading-scripts/tsconfig.json +15 -0
  1296. package/packages/loading-scripts/tsconfig.spec.json +22 -0
  1297. package/packages/sanity-suite/.env.example +39 -0
  1298. package/packages/sanity-suite/.jscpd.json +17 -0
  1299. package/packages/sanity-suite/CHANGELOG.md +154 -0
  1300. package/packages/sanity-suite/LICENSE +21 -0
  1301. package/packages/sanity-suite/README.md +37 -0
  1302. package/packages/sanity-suite/__fixtures__/alias1.json +141 -0
  1303. package/packages/sanity-suite/__fixtures__/alias2.json +101 -0
  1304. package/packages/sanity-suite/__fixtures__/alias3.json +101 -0
  1305. package/packages/sanity-suite/__fixtures__/alias4.json +101 -0
  1306. package/packages/sanity-suite/__fixtures__/alias5.json +107 -0
  1307. package/packages/sanity-suite/__fixtures__/alias6.json +141 -0
  1308. package/packages/sanity-suite/__fixtures__/eventFiltering1.json +69 -0
  1309. package/packages/sanity-suite/__fixtures__/eventFiltering2.json +69 -0
  1310. package/packages/sanity-suite/__fixtures__/eventFiltering3.json +69 -0
  1311. package/packages/sanity-suite/__fixtures__/group1.json +124 -0
  1312. package/packages/sanity-suite/__fixtures__/group2.json +90 -0
  1313. package/packages/sanity-suite/__fixtures__/group3.json +90 -0
  1314. package/packages/sanity-suite/__fixtures__/group4.json +105 -0
  1315. package/packages/sanity-suite/__fixtures__/group5.json +71 -0
  1316. package/packages/sanity-suite/__fixtures__/group6.json +70 -0
  1317. package/packages/sanity-suite/__fixtures__/identify1.json +140 -0
  1318. package/packages/sanity-suite/__fixtures__/identify2.json +106 -0
  1319. package/packages/sanity-suite/__fixtures__/identify3.json +103 -0
  1320. package/packages/sanity-suite/__fixtures__/identify4.json +69 -0
  1321. package/packages/sanity-suite/__fixtures__/identify5.json +106 -0
  1322. package/packages/sanity-suite/__fixtures__/identify6.json +107 -0
  1323. package/packages/sanity-suite/__fixtures__/identify7.json +106 -0
  1324. package/packages/sanity-suite/__fixtures__/identify8.json +107 -0
  1325. package/packages/sanity-suite/__fixtures__/page1.json +123 -0
  1326. package/packages/sanity-suite/__fixtures__/page2.json +90 -0
  1327. package/packages/sanity-suite/__fixtures__/page3.json +90 -0
  1328. package/packages/sanity-suite/__fixtures__/page4.json +116 -0
  1329. package/packages/sanity-suite/__fixtures__/page5.json +83 -0
  1330. package/packages/sanity-suite/__fixtures__/page6.json +81 -0
  1331. package/packages/sanity-suite/__fixtures__/page7.json +81 -0
  1332. package/packages/sanity-suite/__fixtures__/page8.json +79 -0
  1333. package/packages/sanity-suite/__fixtures__/sourceConfig1.json +1536 -0
  1334. package/packages/sanity-suite/__fixtures__/sourceConfigDMT1.json +665 -0
  1335. package/packages/sanity-suite/__fixtures__/sourceConfigDev1.json +892 -0
  1336. package/packages/sanity-suite/__fixtures__/track1.json +154 -0
  1337. package/packages/sanity-suite/__fixtures__/track2.json +122 -0
  1338. package/packages/sanity-suite/__fixtures__/track3.json +122 -0
  1339. package/packages/sanity-suite/__fixtures__/track4.json +138 -0
  1340. package/packages/sanity-suite/__fixtures__/track5.json +106 -0
  1341. package/packages/sanity-suite/__fixtures__/track6.json +85 -0
  1342. package/packages/sanity-suite/__fixtures__/track7.json +85 -0
  1343. package/packages/sanity-suite/babel.config.json +14 -0
  1344. package/packages/sanity-suite/jest.config.mjs +14 -0
  1345. package/packages/sanity-suite/package.json +83 -0
  1346. package/packages/sanity-suite/project.json +55 -0
  1347. package/packages/sanity-suite/public/v1.1/index-cdn.html +135 -0
  1348. package/packages/sanity-suite/public/v1.1/index-local.html +141 -0
  1349. package/packages/sanity-suite/public/v1.1/index-npm.html +107 -0
  1350. package/packages/sanity-suite/public/v1.1/integrations/index-cdn.html +172 -0
  1351. package/packages/sanity-suite/public/v1.1/integrations/index-local.html +171 -0
  1352. package/packages/sanity-suite/public/v1.1/integrations/index-npm.html +140 -0
  1353. package/packages/sanity-suite/public/v1.1/manualLoadCall/index-cdn.html +172 -0
  1354. package/packages/sanity-suite/public/v1.1/manualLoadCall/index-local.html +171 -0
  1355. package/packages/sanity-suite/public/v1.1/manualLoadCall/index-npm.html +140 -0
  1356. package/packages/sanity-suite/public/v3/index-cdn.html +165 -0
  1357. package/packages/sanity-suite/public/v3/index-local.html +169 -0
  1358. package/packages/sanity-suite/public/v3/index-npm.html +99 -0
  1359. package/packages/sanity-suite/public/v3/integrations/index-cdn.html +196 -0
  1360. package/packages/sanity-suite/public/v3/integrations/index-local.html +198 -0
  1361. package/packages/sanity-suite/public/v3/integrations/index-npm.html +138 -0
  1362. package/packages/sanity-suite/public/v3/manualLoadCall/index-cdn.html +196 -0
  1363. package/packages/sanity-suite/public/v3/manualLoadCall/index-local.html +198 -0
  1364. package/packages/sanity-suite/public/v3/manualLoadCall/index-npm.html +138 -0
  1365. package/packages/sanity-suite/rollup.config.mjs +247 -0
  1366. package/packages/sanity-suite/serve.json +4 -0
  1367. package/packages/sanity-suite/src/ignoredProperties/ignoredProperties.js +183 -0
  1368. package/packages/sanity-suite/src/ignoredProperties/sourceConfigIgnoredProperties.js +144 -0
  1369. package/packages/sanity-suite/src/index-npm-v1.1.ts +53 -0
  1370. package/packages/sanity-suite/src/index-npm.ts +57 -0
  1371. package/packages/sanity-suite/src/index.ts +6 -0
  1372. package/packages/sanity-suite/src/testBook/ResultAssertions.js +77 -0
  1373. package/packages/sanity-suite/src/testBook/TestBook.js +360 -0
  1374. package/packages/sanity-suite/src/testBook/index.js +13 -0
  1375. package/packages/sanity-suite/src/testBookSuites/alias.js +289 -0
  1376. package/packages/sanity-suite/src/testBookSuites/eventFiltering.js +77 -0
  1377. package/packages/sanity-suite/src/testBookSuites/group.js +241 -0
  1378. package/packages/sanity-suite/src/testBookSuites/identify.js +455 -0
  1379. package/packages/sanity-suite/src/testBookSuites/index.js +40 -0
  1380. package/packages/sanity-suite/src/testBookSuites/page.js +259 -0
  1381. package/packages/sanity-suite/src/testBookSuites/sourceConfig.js +89 -0
  1382. package/packages/sanity-suite/src/testBookSuites/sourceConfigDev.js +20 -0
  1383. package/packages/sanity-suite/src/testBookSuites/track.js +448 -0
  1384. package/packages/sanity-suite/src/types/global.d.ts +2 -0
  1385. package/packages/sanity-suite/src/types/rudderanalytics.d.ts +16 -0
  1386. package/packages/sanity-suite/tsconfig.json +14 -0
  1387. package/packages/sanity-suite/tsconfig.spec.json +22 -0
  1388. package/patches/@originjs+vite-plugin-federation+1.3.5.patch +170 -0
  1389. package/patches/@segment+localstorage-retry+1.3.0.patch +123 -0
  1390. package/patches/@segment+top-domain+3.0.1.patch +34 -0
  1391. package/patches/@vespaiach+axios-fetch-adapter+0.3.1.patch +43 -0
  1392. package/patches/crypto-es+2.1.0.patch +103 -0
  1393. package/patches/nx+18.0.5.patch +83 -0
  1394. package/patches/rollup-plugin-generate-html-template+1.7.0.patch +46 -0
  1395. package/scripts/commitizen.js +26 -0
  1396. package/scripts/fix-reports-path-in-github-runner.sh +16 -0
  1397. package/scripts/generate-last-release-changelog.sh +32 -0
  1398. package/scripts/sync-tags-in-nx-projects.sh +24 -0
  1399. package/sonar-project.properties +37 -0
  1400. package/tsconfig.build.json +12 -0
  1401. package/tsconfig.json +49 -0
  1402. package/tsconfig.paths.json +27 -0
  1403. package/types/clipboardJs.d.ts +1 -0
  1404. package/types/component-querystring.d.ts +1 -0
  1405. package/types/component-type.d.ts +1 -0
  1406. package/types/global.d.ts +18 -0
  1407. package/types/join-component.d.ts +1 -0
  1408. package/types/localstorage-retry.d.ts +1 -0
  1409. package/types/loosely-validate-event.d.ts +1 -0
  1410. package/types/user-agent-data-types.d.ts +3 -0
@@ -0,0 +1,3875 @@
1
+ // This script gets injected into any opened page
2
+ // whose URL matches the pattern defined in the manifest
3
+ // (see "content_script" key).
4
+ // Several foreground scripts can be declared
5
+ // and injected into the same or different pages.
6
+ (() => {
7
+ //======================== npm cjs package code ==========================================
8
+
9
+ function ownKeys(e, r) {
10
+ var t = Object.keys(e);
11
+ if (Object.getOwnPropertySymbols) {
12
+ var o = Object.getOwnPropertySymbols(e);
13
+ r && (o = o.filter(function (r) {
14
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
15
+ })), t.push.apply(t, o);
16
+ }
17
+ return t;
18
+ }
19
+ function _objectSpread2(e) {
20
+ for (var r = 1; r < arguments.length; r++) {
21
+ var t = null != arguments[r] ? arguments[r] : {};
22
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
23
+ _defineProperty(e, r, t[r]);
24
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
25
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
26
+ });
27
+ }
28
+ return e;
29
+ }
30
+ function _regeneratorRuntime() {
31
+ _regeneratorRuntime = function () {
32
+ return e;
33
+ };
34
+ var t,
35
+ e = {},
36
+ r = Object.prototype,
37
+ n = r.hasOwnProperty,
38
+ o = Object.defineProperty || function (t, e, r) {
39
+ t[e] = r.value;
40
+ },
41
+ i = "function" == typeof Symbol ? Symbol : {},
42
+ a = i.iterator || "@@iterator",
43
+ c = i.asyncIterator || "@@asyncIterator",
44
+ u = i.toStringTag || "@@toStringTag";
45
+ function define(t, e, r) {
46
+ return Object.defineProperty(t, e, {
47
+ value: r,
48
+ enumerable: !0,
49
+ configurable: !0,
50
+ writable: !0
51
+ }), t[e];
52
+ }
53
+ try {
54
+ define({}, "");
55
+ } catch (t) {
56
+ define = function (t, e, r) {
57
+ return t[e] = r;
58
+ };
59
+ }
60
+ function wrap(t, e, r, n) {
61
+ var i = e && e.prototype instanceof Generator ? e : Generator,
62
+ a = Object.create(i.prototype),
63
+ c = new Context(n || []);
64
+ return o(a, "_invoke", {
65
+ value: makeInvokeMethod(t, r, c)
66
+ }), a;
67
+ }
68
+ function tryCatch(t, e, r) {
69
+ try {
70
+ return {
71
+ type: "normal",
72
+ arg: t.call(e, r)
73
+ };
74
+ } catch (t) {
75
+ return {
76
+ type: "throw",
77
+ arg: t
78
+ };
79
+ }
80
+ }
81
+ e.wrap = wrap;
82
+ var h = "suspendedStart",
83
+ l = "suspendedYield",
84
+ f = "executing",
85
+ s = "completed",
86
+ y = {};
87
+ function Generator() {}
88
+ function GeneratorFunction() {}
89
+ function GeneratorFunctionPrototype() {}
90
+ var p = {};
91
+ define(p, a, function () {
92
+ return this;
93
+ });
94
+ var d = Object.getPrototypeOf,
95
+ v = d && d(d(values([])));
96
+ v && v !== r && n.call(v, a) && (p = v);
97
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
98
+ function defineIteratorMethods(t) {
99
+ ["next", "throw", "return"].forEach(function (e) {
100
+ define(t, e, function (t) {
101
+ return this._invoke(e, t);
102
+ });
103
+ });
104
+ }
105
+ function AsyncIterator(t, e) {
106
+ function invoke(r, o, i, a) {
107
+ var c = tryCatch(t[r], t, o);
108
+ if ("throw" !== c.type) {
109
+ var u = c.arg,
110
+ h = u.value;
111
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
112
+ invoke("next", t, i, a);
113
+ }, function (t) {
114
+ invoke("throw", t, i, a);
115
+ }) : e.resolve(h).then(function (t) {
116
+ u.value = t, i(u);
117
+ }, function (t) {
118
+ return invoke("throw", t, i, a);
119
+ });
120
+ }
121
+ a(c.arg);
122
+ }
123
+ var r;
124
+ o(this, "_invoke", {
125
+ value: function (t, n) {
126
+ function callInvokeWithMethodAndArg() {
127
+ return new e(function (e, r) {
128
+ invoke(t, n, e, r);
129
+ });
130
+ }
131
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
132
+ }
133
+ });
134
+ }
135
+ function makeInvokeMethod(e, r, n) {
136
+ var o = h;
137
+ return function (i, a) {
138
+ if (o === f) throw new Error("Generator is already running");
139
+ if (o === s) {
140
+ if ("throw" === i) throw a;
141
+ return {
142
+ value: t,
143
+ done: !0
144
+ };
145
+ }
146
+ for (n.method = i, n.arg = a;;) {
147
+ var c = n.delegate;
148
+ if (c) {
149
+ var u = maybeInvokeDelegate(c, n);
150
+ if (u) {
151
+ if (u === y) continue;
152
+ return u;
153
+ }
154
+ }
155
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
156
+ if (o === h) throw o = s, n.arg;
157
+ n.dispatchException(n.arg);
158
+ } else "return" === n.method && n.abrupt("return", n.arg);
159
+ o = f;
160
+ var p = tryCatch(e, r, n);
161
+ if ("normal" === p.type) {
162
+ if (o = n.done ? s : l, p.arg === y) continue;
163
+ return {
164
+ value: p.arg,
165
+ done: n.done
166
+ };
167
+ }
168
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
169
+ }
170
+ };
171
+ }
172
+ function maybeInvokeDelegate(e, r) {
173
+ var n = r.method,
174
+ o = e.iterator[n];
175
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
176
+ var i = tryCatch(o, e.iterator, r.arg);
177
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
178
+ var a = i.arg;
179
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
180
+ }
181
+ function pushTryEntry(t) {
182
+ var e = {
183
+ tryLoc: t[0]
184
+ };
185
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
186
+ }
187
+ function resetTryEntry(t) {
188
+ var e = t.completion || {};
189
+ e.type = "normal", delete e.arg, t.completion = e;
190
+ }
191
+ function Context(t) {
192
+ this.tryEntries = [{
193
+ tryLoc: "root"
194
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
195
+ }
196
+ function values(e) {
197
+ if (e || "" === e) {
198
+ var r = e[a];
199
+ if (r) return r.call(e);
200
+ if ("function" == typeof e.next) return e;
201
+ if (!isNaN(e.length)) {
202
+ var o = -1,
203
+ i = function next() {
204
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
205
+ return next.value = t, next.done = !0, next;
206
+ };
207
+ return i.next = i;
208
+ }
209
+ }
210
+ throw new TypeError(typeof e + " is not iterable");
211
+ }
212
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
213
+ value: GeneratorFunctionPrototype,
214
+ configurable: !0
215
+ }), o(GeneratorFunctionPrototype, "constructor", {
216
+ value: GeneratorFunction,
217
+ configurable: !0
218
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
219
+ var e = "function" == typeof t && t.constructor;
220
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
221
+ }, e.mark = function (t) {
222
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
223
+ }, e.awrap = function (t) {
224
+ return {
225
+ __await: t
226
+ };
227
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
228
+ return this;
229
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
230
+ void 0 === i && (i = Promise);
231
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
232
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
233
+ return t.done ? t.value : a.next();
234
+ });
235
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
236
+ return this;
237
+ }), define(g, "toString", function () {
238
+ return "[object Generator]";
239
+ }), e.keys = function (t) {
240
+ var e = Object(t),
241
+ r = [];
242
+ for (var n in e) r.push(n);
243
+ return r.reverse(), function next() {
244
+ for (; r.length;) {
245
+ var t = r.pop();
246
+ if (t in e) return next.value = t, next.done = !1, next;
247
+ }
248
+ return next.done = !0, next;
249
+ };
250
+ }, e.values = values, Context.prototype = {
251
+ constructor: Context,
252
+ reset: function (e) {
253
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
254
+ },
255
+ stop: function () {
256
+ this.done = !0;
257
+ var t = this.tryEntries[0].completion;
258
+ if ("throw" === t.type) throw t.arg;
259
+ return this.rval;
260
+ },
261
+ dispatchException: function (e) {
262
+ if (this.done) throw e;
263
+ var r = this;
264
+ function handle(n, o) {
265
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
266
+ }
267
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
268
+ var i = this.tryEntries[o],
269
+ a = i.completion;
270
+ if ("root" === i.tryLoc) return handle("end");
271
+ if (i.tryLoc <= this.prev) {
272
+ var c = n.call(i, "catchLoc"),
273
+ u = n.call(i, "finallyLoc");
274
+ if (c && u) {
275
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
276
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
277
+ } else if (c) {
278
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
279
+ } else {
280
+ if (!u) throw new Error("try statement without catch or finally");
281
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
282
+ }
283
+ }
284
+ }
285
+ },
286
+ abrupt: function (t, e) {
287
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
288
+ var o = this.tryEntries[r];
289
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
290
+ var i = o;
291
+ break;
292
+ }
293
+ }
294
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
295
+ var a = i ? i.completion : {};
296
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
297
+ },
298
+ complete: function (t, e) {
299
+ if ("throw" === t.type) throw t.arg;
300
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
301
+ },
302
+ finish: function (t) {
303
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
304
+ var r = this.tryEntries[e];
305
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
306
+ }
307
+ },
308
+ catch: function (t) {
309
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
310
+ var r = this.tryEntries[e];
311
+ if (r.tryLoc === t) {
312
+ var n = r.completion;
313
+ if ("throw" === n.type) {
314
+ var o = n.arg;
315
+ resetTryEntry(r);
316
+ }
317
+ return o;
318
+ }
319
+ }
320
+ throw new Error("illegal catch attempt");
321
+ },
322
+ delegateYield: function (e, r, n) {
323
+ return this.delegate = {
324
+ iterator: values(e),
325
+ resultName: r,
326
+ nextLoc: n
327
+ }, "next" === this.method && (this.arg = t), y;
328
+ }
329
+ }, e;
330
+ }
331
+ function _typeof(o) {
332
+ "@babel/helpers - typeof";
333
+
334
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
335
+ return typeof o;
336
+ } : function (o) {
337
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
338
+ }, _typeof(o);
339
+ }
340
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
341
+ try {
342
+ var info = gen[key](arg);
343
+ var value = info.value;
344
+ } catch (error) {
345
+ reject(error);
346
+ return;
347
+ }
348
+ if (info.done) {
349
+ resolve(value);
350
+ } else {
351
+ Promise.resolve(value).then(_next, _throw);
352
+ }
353
+ }
354
+ function _asyncToGenerator(fn) {
355
+ return function () {
356
+ var self = this,
357
+ args = arguments;
358
+ return new Promise(function (resolve, reject) {
359
+ var gen = fn.apply(self, args);
360
+ function _next(value) {
361
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
362
+ }
363
+ function _throw(err) {
364
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
365
+ }
366
+ _next(undefined);
367
+ });
368
+ };
369
+ }
370
+ function _classCallCheck(instance, Constructor) {
371
+ if (!(instance instanceof Constructor)) {
372
+ throw new TypeError("Cannot call a class as a function");
373
+ }
374
+ }
375
+ function _defineProperties(target, props) {
376
+ for (var i = 0; i < props.length; i++) {
377
+ var descriptor = props[i];
378
+ descriptor.enumerable = descriptor.enumerable || false;
379
+ descriptor.configurable = true;
380
+ if ("value" in descriptor) descriptor.writable = true;
381
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
382
+ }
383
+ }
384
+ function _createClass(Constructor, protoProps, staticProps) {
385
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
386
+ if (staticProps) _defineProperties(Constructor, staticProps);
387
+ Object.defineProperty(Constructor, "prototype", {
388
+ writable: false
389
+ });
390
+ return Constructor;
391
+ }
392
+ function _defineProperty(obj, key, value) {
393
+ key = _toPropertyKey(key);
394
+ if (key in obj) {
395
+ Object.defineProperty(obj, key, {
396
+ value: value,
397
+ enumerable: true,
398
+ configurable: true,
399
+ writable: true
400
+ });
401
+ } else {
402
+ obj[key] = value;
403
+ }
404
+ return obj;
405
+ }
406
+ function _inherits(subClass, superClass) {
407
+ if (typeof superClass !== "function" && superClass !== null) {
408
+ throw new TypeError("Super expression must either be null or a function");
409
+ }
410
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
411
+ constructor: {
412
+ value: subClass,
413
+ writable: true,
414
+ configurable: true
415
+ }
416
+ });
417
+ Object.defineProperty(subClass, "prototype", {
418
+ writable: false
419
+ });
420
+ if (superClass) _setPrototypeOf(subClass, superClass);
421
+ }
422
+ function _getPrototypeOf(o) {
423
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
424
+ return o.__proto__ || Object.getPrototypeOf(o);
425
+ };
426
+ return _getPrototypeOf(o);
427
+ }
428
+ function _setPrototypeOf(o, p) {
429
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
430
+ o.__proto__ = p;
431
+ return o;
432
+ };
433
+ return _setPrototypeOf(o, p);
434
+ }
435
+ function _isNativeReflectConstruct() {
436
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
437
+ if (Reflect.construct.sham) return false;
438
+ if (typeof Proxy === "function") return true;
439
+ try {
440
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
441
+ return true;
442
+ } catch (e) {
443
+ return false;
444
+ }
445
+ }
446
+ function _construct(Parent, args, Class) {
447
+ if (_isNativeReflectConstruct()) {
448
+ _construct = Reflect.construct.bind();
449
+ } else {
450
+ _construct = function _construct(Parent, args, Class) {
451
+ var a = [null];
452
+ a.push.apply(a, args);
453
+ var Constructor = Function.bind.apply(Parent, a);
454
+ var instance = new Constructor();
455
+ if (Class) _setPrototypeOf(instance, Class.prototype);
456
+ return instance;
457
+ };
458
+ }
459
+ return _construct.apply(null, arguments);
460
+ }
461
+ function _assertThisInitialized(self) {
462
+ if (self === void 0) {
463
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
464
+ }
465
+ return self;
466
+ }
467
+ function _possibleConstructorReturn(self, call) {
468
+ if (call && (typeof call === "object" || typeof call === "function")) {
469
+ return call;
470
+ } else if (call !== void 0) {
471
+ throw new TypeError("Derived constructors may only return object or undefined");
472
+ }
473
+ return _assertThisInitialized(self);
474
+ }
475
+ function _createSuper(Derived) {
476
+ var hasNativeReflectConstruct = _isNativeReflectConstruct();
477
+ return function _createSuperInternal() {
478
+ var Super = _getPrototypeOf(Derived),
479
+ result;
480
+ if (hasNativeReflectConstruct) {
481
+ var NewTarget = _getPrototypeOf(this).constructor;
482
+ result = Reflect.construct(Super, arguments, NewTarget);
483
+ } else {
484
+ result = Super.apply(this, arguments);
485
+ }
486
+ return _possibleConstructorReturn(this, result);
487
+ };
488
+ }
489
+ function _superPropBase(object, property) {
490
+ while (!Object.prototype.hasOwnProperty.call(object, property)) {
491
+ object = _getPrototypeOf(object);
492
+ if (object === null) break;
493
+ }
494
+ return object;
495
+ }
496
+ function _get() {
497
+ if (typeof Reflect !== "undefined" && Reflect.get) {
498
+ _get = Reflect.get.bind();
499
+ } else {
500
+ _get = function _get(target, property, receiver) {
501
+ var base = _superPropBase(target, property);
502
+ if (!base) return;
503
+ var desc = Object.getOwnPropertyDescriptor(base, property);
504
+ if (desc.get) {
505
+ return desc.get.call(arguments.length < 3 ? target : receiver);
506
+ }
507
+ return desc.value;
508
+ };
509
+ }
510
+ return _get.apply(this, arguments);
511
+ }
512
+ function _toConsumableArray(arr) {
513
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
514
+ }
515
+ function _arrayWithoutHoles(arr) {
516
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
517
+ }
518
+ function _iterableToArray(iter) {
519
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
520
+ }
521
+ function _unsupportedIterableToArray(o, minLen) {
522
+ if (!o) return;
523
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
524
+ var n = Object.prototype.toString.call(o).slice(8, -1);
525
+ if (n === "Object" && o.constructor) n = o.constructor.name;
526
+ if (n === "Map" || n === "Set") return Array.from(o);
527
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
528
+ }
529
+ function _arrayLikeToArray(arr, len) {
530
+ if (len == null || len > arr.length) len = arr.length;
531
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
532
+ return arr2;
533
+ }
534
+ function _nonIterableSpread() {
535
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
536
+ }
537
+ function _toPrimitive(input, hint) {
538
+ if (typeof input !== "object" || input === null) return input;
539
+ var prim = input[Symbol.toPrimitive];
540
+ if (prim !== undefined) {
541
+ var res = prim.call(input, hint || "default");
542
+ if (typeof res !== "object") return res;
543
+ throw new TypeError("@@toPrimitive must return a primitive value.");
544
+ }
545
+ return (hint === "string" ? String : Number)(input);
546
+ }
547
+ function _toPropertyKey(arg) {
548
+ var key = _toPrimitive(arg, "string");
549
+ return typeof key === "symbol" ? key : String(key);
550
+ }
551
+
552
+ function _isPlaceholder(a){return a!=null&&_typeof(a)==='object'&&a['@@functional/placeholder']===true;}
553
+
554
+ /**
555
+ * Optimized internal one-arity curry function.
556
+ *
557
+ * @private
558
+ * @category Function
559
+ * @param {Function} fn The function to curry.
560
+ * @return {Function} The curried function.
561
+ */function _curry1(fn){return function f1(a){if(arguments.length===0||_isPlaceholder(a)){return f1;}else {return fn.apply(this,arguments);}};}
562
+
563
+ /**
564
+ * Optimized internal two-arity curry function.
565
+ *
566
+ * @private
567
+ * @category Function
568
+ * @param {Function} fn The function to curry.
569
+ * @return {Function} The curried function.
570
+ */function _curry2(fn){return function f2(a,b){switch(arguments.length){case 0:return f2;case 1:return _isPlaceholder(a)?f2:_curry1(function(_b){return fn(a,_b);});default:return _isPlaceholder(a)&&_isPlaceholder(b)?f2:_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b);}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b);}):fn(a,b);}};}
571
+
572
+ /**
573
+ * Optimized internal three-arity curry function.
574
+ *
575
+ * @private
576
+ * @category Function
577
+ * @param {Function} fn The function to curry.
578
+ * @return {Function} The curried function.
579
+ */function _curry3(fn){return function f3(a,b,c){switch(arguments.length){case 0:return f3;case 1:return _isPlaceholder(a)?f3:_curry2(function(_b,_c){return fn(a,_b,_c);});case 2:return _isPlaceholder(a)&&_isPlaceholder(b)?f3:_isPlaceholder(a)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_curry1(function(_c){return fn(a,b,_c);});default:return _isPlaceholder(a)&&_isPlaceholder(b)&&_isPlaceholder(c)?f3:_isPlaceholder(a)&&_isPlaceholder(b)?_curry2(function(_a,_b){return fn(_a,_b,c);}):_isPlaceholder(a)&&_isPlaceholder(c)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)&&_isPlaceholder(c)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b,c);}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b,c);}):_isPlaceholder(c)?_curry1(function(_c){return fn(a,b,_c);}):fn(a,b,c);}};}
580
+
581
+ function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
582
+
583
+ /**
584
+ * Gives a single-word string description of the (native) type of a value,
585
+ * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
586
+ * attempt to distinguish user Object types any further, reporting them all as
587
+ * 'Object'.
588
+ *
589
+ * @func
590
+ * @memberOf R
591
+ * @since v0.8.0
592
+ * @category Type
593
+ * @sig * -> String
594
+ * @param {*} val The value to test
595
+ * @return {String}
596
+ * @example
597
+ *
598
+ * R.type({}); //=> "Object"
599
+ * R.type(1); //=> "Number"
600
+ * R.type(false); //=> "Boolean"
601
+ * R.type('s'); //=> "String"
602
+ * R.type(null); //=> "Null"
603
+ * R.type([]); //=> "Array"
604
+ * R.type(/[A-z]/); //=> "RegExp"
605
+ * R.type(() => {}); //=> "Function"
606
+ * R.type(async () => {}); //=> "AsyncFunction"
607
+ * R.type(undefined); //=> "Undefined"
608
+ */var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});var type$1 = type;
609
+
610
+ function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
611
+
612
+ /**
613
+ * Determine if the passed argument is an integer.
614
+ *
615
+ * @private
616
+ * @param {*} n
617
+ * @category Type
618
+ * @return {Boolean}
619
+ */var _isInteger = Number.isInteger||function _isInteger(n){return n<<0===n;};
620
+
621
+ function _isString(x){return Object.prototype.toString.call(x)==='[object String]';}
622
+
623
+ /**
624
+ * Returns the nth element of the given list or string. If n is negative the
625
+ * element at index length + n is returned.
626
+ *
627
+ * @func
628
+ * @memberOf R
629
+ * @since v0.1.0
630
+ * @category List
631
+ * @sig Number -> [a] -> a | Undefined
632
+ * @sig Number -> String -> String
633
+ * @param {Number} offset
634
+ * @param {*} list
635
+ * @return {*}
636
+ * @example
637
+ *
638
+ * const list = ['foo', 'bar', 'baz', 'quux'];
639
+ * R.nth(1, list); //=> 'bar'
640
+ * R.nth(-1, list); //=> 'quux'
641
+ * R.nth(-99, list); //=> undefined
642
+ *
643
+ * R.nth(2, 'abc'); //=> 'c'
644
+ * R.nth(3, 'abc'); //=> ''
645
+ * @symb R.nth(-1, [a, b, c]) = c
646
+ * @symb R.nth(0, [a, b, c]) = a
647
+ * @symb R.nth(1, [a, b, c]) = b
648
+ */var nth=/*#__PURE__*/_curry2(function nth(offset,list){var idx=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(idx):list[idx];});var nth$1 = nth;
649
+
650
+ function _cloneRegExp(pattern){return new RegExp(pattern.source,pattern.flags?pattern.flags:(pattern.global?'g':'')+(pattern.ignoreCase?'i':'')+(pattern.multiline?'m':'')+(pattern.sticky?'y':'')+(pattern.unicode?'u':'')+(pattern.dotAll?'s':''));}
651
+
652
+ /**
653
+ * Copies an object.
654
+ *
655
+ * @private
656
+ * @param {*} value The value to be copied
657
+ * @param {Boolean} deep Whether or not to perform deep cloning.
658
+ * @return {*} The copied value.
659
+ */function _clone(value,deep,map){map||(map=new _ObjectMap());// this avoids the slower switch with a quick if decision removing some milliseconds in each run.
660
+ if(_isPrimitive(value)){return value;}var copy=function copy(copiedValue){// Check for circular and same references on the object graph and return its corresponding clone.
661
+ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,copiedValue);for(var key in value){if(Object.prototype.hasOwnProperty.call(value,key)){copiedValue[key]=deep?_clone(value[key],true,map):value[key];}}return copiedValue;};switch(type$1(value)){case'Object':return copy(Object.create(Object.getPrototypeOf(value)));case'Array':return copy([]);case'Date':return new Date(value.valueOf());case'RegExp':return _cloneRegExp(value);case'Int8Array':case'Uint8Array':case'Uint8ClampedArray':case'Int16Array':case'Uint16Array':case'Int32Array':case'Uint32Array':case'Float32Array':case'Float64Array':case'BigInt64Array':case'BigUint64Array':return value.slice();default:return value;}}function _isPrimitive(param){var type=_typeof(param);return param==null||type!='object'&&type!='function';}var _ObjectMap=/*#__PURE__*/function(){function _ObjectMap(){this.map={};this.length=0;}_ObjectMap.prototype.set=function(key,value){var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){this.map[hashedKey]=bucket=[];}bucket.push([key,value]);this.length+=1;};_ObjectMap.prototype.hash=function(key){var hashedKey=[];for(var value in key){hashedKey.push(Object.prototype.toString.call(key[value]));}return hashedKey.join();};_ObjectMap.prototype.get=function(key){/**
662
+ * depending on the number of objects to be cloned is faster to just iterate over the items in the map just because the hash function is so costly,
663
+ * on my tests this number is 180, anything above that using the hash function is faster.
664
+ */if(this.length<=180){for(var p in this.map){var _bucket=this.map[p];for(var i=0;i<_bucket.length;i+=1){var element=_bucket[i];if(element[0]===key){return element[1];}}}return;}var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){return;}for(var _i=0;_i<bucket.length;_i+=1){var _element=bucket[_i];if(_element[0]===key){return _element[1];}}};return _ObjectMap;}();
665
+
666
+ /**
667
+ * Creates a deep copy of the source that can be used in place of the source
668
+ * object without retaining any references to it.
669
+ * The source object may contain (nested) `Array`s and `Object`s,
670
+ * `Number`s, `String`s, `Boolean`s and `Date`s.
671
+ * `Function`s are assigned by reference rather than copied.
672
+ *
673
+ * Dispatches to a `clone` method if present.
674
+ *
675
+ * Note that if the source object has multiple nodes that share a reference,
676
+ * the returned object will have the same structure, but the references will
677
+ * be pointed to the location within the cloned value.
678
+ *
679
+ * @func
680
+ * @memberOf R
681
+ * @since v0.1.0
682
+ * @category Object
683
+ * @sig {*} -> {*}
684
+ * @param {*} value The object or array to clone
685
+ * @return {*} A deeply cloned copy of `val`
686
+ * @example
687
+ *
688
+ * const objects = [{}, {}, {}];
689
+ * const objectsClone = R.clone(objects);
690
+ * objects === objectsClone; //=> false
691
+ * objects[0] === objectsClone[0]; //=> false
692
+ */var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value,true);});var clone$1 = clone;
693
+
694
+ /**
695
+ * Retrieves the values at given paths of an object.
696
+ *
697
+ * @func
698
+ * @memberOf R
699
+ * @since v0.27.1
700
+ * @category Object
701
+ * @typedefn Idx = [String | Int | Symbol]
702
+ * @sig [Idx] -> {a} -> [a | Undefined]
703
+ * @param {Array} pathsArray The array of paths to be fetched.
704
+ * @param {Object} obj The object to retrieve the nested properties from.
705
+ * @return {Array} A list consisting of values at paths specified by "pathsArray".
706
+ * @see R.path
707
+ * @example
708
+ *
709
+ * R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3]
710
+ * R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined]
711
+ */var paths=/*#__PURE__*/_curry2(function paths(pathsArray,obj){return pathsArray.map(function(paths){var val=obj;var idx=0;var p;while(idx<paths.length){if(val==null){return;}p=paths[idx];val=_isInteger(p)?nth$1(p,val):val[p];idx+=1;}return val;});});var paths$1 = paths;
712
+
713
+ /**
714
+ * Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
715
+ * For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
716
+ *
717
+ * @func
718
+ * @memberOf R
719
+ * @since v0.2.0
720
+ * @category Object
721
+ * @typedefn Idx = String | Int | Symbol
722
+ * @sig [Idx] -> {a} -> a | Undefined
723
+ * @sig Idx = String | NonNegativeInt
724
+ * @param {Array} path The path to use.
725
+ * @param {Object} obj The object or array to retrieve the nested property from.
726
+ * @return {*} The data at `path`.
727
+ * @see R.prop, R.nth, R.assocPath, R.dissocPath
728
+ * @example
729
+ *
730
+ * R.path(['a', 'b'], {a: {b: 2}}); //=> 2
731
+ * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
732
+ * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
733
+ * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
734
+ * R.path([2], {'2': 2}); //=> 2
735
+ * R.path([-2], {'-2': 'a'}); //=> undefined
736
+ */var path=/*#__PURE__*/_curry2(function path(pathAr,obj){return paths$1([pathAr],obj)[0];});var path$1 = path;
737
+
738
+ /**
739
+ * Creates a new object with the own properties of the two provided objects. If
740
+ * a key exists in both objects, the provided function is applied to the key
741
+ * and the values associated with the key in each object, with the result being
742
+ * used as the value associated with the key in the returned object.
743
+ *
744
+ * @func
745
+ * @memberOf R
746
+ * @since v0.19.0
747
+ * @category Object
748
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
749
+ * @param {Function} fn
750
+ * @param {Object} l
751
+ * @param {Object} r
752
+ * @return {Object}
753
+ * @see R.mergeDeepWithKey, R.merge, R.mergeWith
754
+ * @example
755
+ *
756
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
757
+ * R.mergeWithKey(concatValues,
758
+ * { a: true, thing: 'foo', values: [10, 20] },
759
+ * { b: true, thing: 'bar', values: [15, 35] });
760
+ * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
761
+ * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }
762
+ */var mergeWithKey=/*#__PURE__*/_curry3(function mergeWithKey(fn,l,r){var result={};var k;l=l||{};r=r||{};for(k in l){if(_has(k,l)){result[k]=_has(k,r)?fn(k,l[k],r[k]):l[k];}}for(k in r){if(_has(k,r)&&!_has(k,result)){result[k]=r[k];}}return result;});var mergeWithKey$1 = mergeWithKey;
763
+
764
+ /**
765
+ * Creates a new object with the own properties of the two provided objects.
766
+ * If a key exists in both objects:
767
+ * - and both associated values are also objects then the values will be
768
+ * recursively merged.
769
+ * - otherwise the provided function is applied to the key and associated values
770
+ * using the resulting value as the new value associated with the key.
771
+ * If a key only exists in one object, the value will be associated with the key
772
+ * of the resulting object.
773
+ *
774
+ * @func
775
+ * @memberOf R
776
+ * @since v0.24.0
777
+ * @category Object
778
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
779
+ * @param {Function} fn
780
+ * @param {Object} lObj
781
+ * @param {Object} rObj
782
+ * @return {Object}
783
+ * @see R.mergeWithKey, R.mergeDeepWith
784
+ * @example
785
+ *
786
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
787
+ * R.mergeDeepWithKey(concatValues,
788
+ * { a: true, c: { thing: 'foo', values: [10, 20] }},
789
+ * { b: true, c: { thing: 'bar', values: [15, 35] }});
790
+ * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}
791
+ */var mergeDeepWithKey=/*#__PURE__*/_curry3(function mergeDeepWithKey(fn,lObj,rObj){return mergeWithKey$1(function(k,lVal,rVal){if(_isObject(lVal)&&_isObject(rVal)){return mergeDeepWithKey(fn,lVal,rVal);}else {return fn(k,lVal,rVal);}},lObj,rObj);});var mergeDeepWithKey$1 = mergeDeepWithKey;
792
+
793
+ /**
794
+ * Creates a new object with the own properties of the two provided objects.
795
+ * If a key exists in both objects:
796
+ * - and both associated values are also objects then the values will be
797
+ * recursively merged.
798
+ * - otherwise the provided function is applied to associated values using the
799
+ * resulting value as the new value associated with the key.
800
+ * If a key only exists in one object, the value will be associated with the key
801
+ * of the resulting object.
802
+ *
803
+ * @func
804
+ * @memberOf R
805
+ * @since v0.24.0
806
+ * @category Object
807
+ * @sig ((a, a) -> a) -> {a} -> {a} -> {a}
808
+ * @param {Function} fn
809
+ * @param {Object} lObj
810
+ * @param {Object} rObj
811
+ * @return {Object}
812
+ * @see R.mergeWith, R.mergeDeepWithKey
813
+ * @example
814
+ *
815
+ * R.mergeDeepWith(R.concat,
816
+ * { a: true, c: { values: [10, 20] }},
817
+ * { b: true, c: { values: [15, 35] }});
818
+ * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
819
+ */var mergeDeepWith=/*#__PURE__*/_curry3(function mergeDeepWith(fn,lObj,rObj){return mergeDeepWithKey$1(function(k,lVal,rVal){return fn(lVal,rVal);},lObj,rObj);});var mergeDeepWith$1 = mergeDeepWith;
820
+
821
+ /**
822
+ * Returns a partial copy of an object containing only the keys that satisfy
823
+ * the supplied predicate.
824
+ *
825
+ * @func
826
+ * @memberOf R
827
+ * @since v0.8.0
828
+ * @category Object
829
+ * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}
830
+ * @param {Function} pred A predicate to determine whether or not a key
831
+ * should be included on the output object.
832
+ * @param {Object} obj The object to copy from
833
+ * @return {Object} A new object with only properties that satisfy `pred`
834
+ * on it.
835
+ * @see R.pick, R.filter
836
+ * @example
837
+ *
838
+ * const isUpperCase = (val, key) => key.toUpperCase() === key;
839
+ * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
840
+ */var pickBy=/*#__PURE__*/_curry2(function pickBy(test,obj){var result={};for(var prop in obj){if(test(obj[prop],prop,obj)){result[prop]=obj[prop];}}return result;});var pickBy$1 = pickBy;
841
+
842
+ /**
843
+ * A function to check given value is a function
844
+ * @param value input value
845
+ * @returns boolean
846
+ */ // eslint-disable-next-line @typescript-eslint/ban-types
847
+ var isFunction=function isFunction(value){return typeof value==='function'&&Boolean(value.constructor&&value.call&&value.apply);};/**
848
+ * A function to check given value is a string
849
+ * @param value input value
850
+ * @returns boolean
851
+ */var isString=function isString(value){return typeof value==='string';};/**
852
+ * A function to check given value is null or not
853
+ * @param value input value
854
+ * @returns boolean
855
+ */var isNull=function isNull(value){return value===null;};/**
856
+ * A function to check given value is undefined
857
+ * @param value input value
858
+ * @returns boolean
859
+ */var isUndefined=function isUndefined(value){return typeof value==='undefined';};/**
860
+ * A function to check given value is null or undefined
861
+ * @param value input value
862
+ * @returns boolean
863
+ */var isNullOrUndefined=function isNullOrUndefined(value){return isNull(value)||isUndefined(value);};/**
864
+ * A function to check given value is defined
865
+ * @param value input value
866
+ * @returns boolean
867
+ */var isDefined=function isDefined(value){return !isUndefined(value);};/**
868
+ * A function to check given value is defined and not null
869
+ * @param value input value
870
+ * @returns boolean
871
+ */var isDefinedAndNotNull=function isDefinedAndNotNull(value){return !isNullOrUndefined(value);};/**
872
+ * A function to check given value is defined and not null
873
+ * @param value input value
874
+ * @returns boolean
875
+ */var isDefinedNotNullAndNotEmptyString=function isDefinedNotNullAndNotEmptyString(value){return isDefinedAndNotNull(value)&&value!=='';};/**
876
+ * Determines if the input is an instance of Error
877
+ * @param obj input value
878
+ * @returns true if the input is an instance of Error and false otherwise
879
+ */var isTypeOfError=function isTypeOfError(obj){return obj instanceof Error;};
880
+
881
+ var getValueByPath=function getValueByPath(obj,keyPath){var pathParts=keyPath.split('.');return path$1(pathParts,obj);};var hasValueByPath=function hasValueByPath(obj,path){return Boolean(getValueByPath(obj,path));};/**
882
+ * Checks if the input is an object literal or built-in object type and not null
883
+ * @param value Input value
884
+ * @returns true if the input is an object and not null
885
+ */var isObjectAndNotNull=function isObjectAndNotNull(value){return !isNull(value)&&_typeof(value)==='object'&&!Array.isArray(value);};/**
886
+ * Checks if the input is an object literal and not null
887
+ * @param value Input value
888
+ * @returns true if the input is an object and not null
889
+ */var isObjectLiteralAndNotNull=function isObjectLiteralAndNotNull(value){return !isNull(value)&&Object.prototype.toString.call(value)==='[object Object]';};var mergeDeepRightObjectArrays=function mergeDeepRightObjectArrays(leftValue,rightValue){if(!Array.isArray(leftValue)||!Array.isArray(rightValue)){return clone$1(rightValue);}var mergedArray=clone$1(leftValue);rightValue.forEach(function(value,index){mergedArray[index]=Array.isArray(value)||isObjectAndNotNull(value)?// eslint-disable-next-line @typescript-eslint/no-use-before-define
890
+ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};var mergeDeepRight=function mergeDeepRight(leftObject,rightObject){return mergeDeepWith$1(mergeDeepRightObjectArrays,leftObject,rightObject);};/**
891
+ Checks if the input is a non-empty object literal type and not undefined or null
892
+ * @param value input any
893
+ * @returns boolean
894
+ */var isNonEmptyObject=function isNonEmptyObject(value){return isObjectLiteralAndNotNull(value)&&Object.keys(value).length>0;};/**
895
+ * A utility to recursively remove undefined values from an object
896
+ * @param obj input object
897
+ * @returns a new object
898
+ */var removeUndefinedValues=function removeUndefinedValues(obj){var result=pickBy$1(isDefined,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=removeUndefinedValues(value);}});return result;};/**
899
+ * A utility to recursively remove undefined and null values from an object
900
+ * @param obj input object
901
+ * @returns a new object
902
+ */var removeUndefinedAndNullValues=function removeUndefinedAndNullValues(obj){var result=pickBy$1(isDefinedAndNotNull,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=removeUndefinedAndNullValues(value);}});return result;};
903
+
904
+ var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeDoubleSpaces=function removeDoubleSpaces(value){return value.replace(/ {2,}/g,' ');};/**
905
+ * A function to convert values to string
906
+ * @param val input value
907
+ * @returns stringified value
908
+ */var tryStringify=function tryStringify(val){var retVal=val;if(!isString(val)&&!isNullOrUndefined(val)){try{retVal=JSON.stringify(val);}catch(e){retVal=null;}}return retVal;};// The following text encoding and decoding is done before base64 encoding to prevent
909
+ // https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
910
+ /**
911
+ * Converts a base64 encoded string to bytes array
912
+ * @param base64Str base64 encoded string
913
+ * @returns bytes array
914
+ */var base64ToBytes=function base64ToBytes(base64Str){var binString=globalThis.atob(base64Str);var bytes=binString.split('').map(function(char){return char.charCodeAt(0);});return new Uint8Array(bytes);};/**
915
+ * Converts a bytes array to base64 encoded string
916
+ * @param bytes bytes array to be converted to base64
917
+ * @returns base64 encoded string
918
+ */var bytesToBase64=function bytesToBase64(bytes){var binString=Array.from(bytes,function(x){return String.fromCodePoint(x);}).join('');return globalThis.btoa(binString);};/**
919
+ * Encodes a string to base64 even with unicode characters
920
+ * @param value input string
921
+ * @returns base64 encoded string
922
+ */var toBase64=function toBase64(value){return bytesToBase64(new TextEncoder().encode(value));};/**
923
+ * Decodes a base64 encoded string
924
+ * @param value base64 encoded string
925
+ * @returns decoded string
926
+ */var fromBase64=function fromBase64(value){return new TextDecoder().decode(base64ToBytes(value));};
927
+
928
+ // if yes make them null instead of omitting in overloaded cases
929
+ /*
930
+ * Normalise the overloaded arguments of the page call facade
931
+ */var pageArgumentsToCallOptions=function pageArgumentsToCallOptions(category,name,properties,options,callback){var payload={category:category,name:name,properties:properties,options:options};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.category=category;payload.name=name;payload.properties=properties;delete payload.options;payload.callback=options;}if(isFunction(properties)){payload.category=category;payload.name=name;delete payload.properties;delete payload.options;payload.callback=properties;}if(isFunction(name)){payload.category=category;delete payload.name;delete payload.properties;delete payload.options;payload.callback=name;}if(isFunction(category)){delete payload.category;delete payload.name;delete payload.properties;delete payload.options;payload.callback=category;}if(isObjectLiteralAndNotNull(category)){delete payload.name;delete payload.category;payload.properties=category;payload.options=name;}else if(isObjectLiteralAndNotNull(name)){delete payload.name;payload.properties=name;payload.options=!isFunction(properties)?properties:null;}// if the category argument alone is provided b/w category and name,
932
+ // use it as name and set category to undefined
933
+ if(isString(category)&&!isString(name)){delete payload.category;payload.name=category;}// Rest of the code is just to clean up undefined values
934
+ // and set some proper defaults
935
+ // Also, to clone the incoming object type arguments
936
+ if(!isDefined(payload.category)){delete payload.category;}if(!isDefined(payload.name)){delete payload.name;}payload.properties=payload.properties?clone$1(payload.properties):{};if(isDefined(payload.options)){payload.options=clone$1(payload.options);}else {delete payload.options;}// add name and category to properties
937
+ payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},{name:isString(payload.name)?payload.name:null,category:isString(payload.category)?payload.category:null});return payload;};/*
938
+ * Normalise the overloaded arguments of the track call facade
939
+ */var trackArgumentsToCallOptions=function trackArgumentsToCallOptions(event,properties,options,callback){var payload={name:event,properties:properties,options:options};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.properties=properties;delete payload.options;payload.callback=options;}if(isFunction(properties)){delete payload.properties;delete payload.options;payload.callback=properties;}// Rest of the code is just to clean up undefined values
940
+ // and set some proper defaults
941
+ // Also, to clone the incoming object type arguments
942
+ payload.properties=isDefinedAndNotNull(payload.properties)?clone$1(payload.properties):{};if(isDefined(payload.options)){payload.options=clone$1(payload.options);}else {delete payload.options;}return payload;};/*
943
+ * Normalise the overloaded arguments of the identify call facade
944
+ */var identifyArgumentsToCallOptions=function identifyArgumentsToCallOptions(userId,traits,options,callback){var payload={userId:userId,traits:traits,options:options};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.userId=userId;payload.traits=traits;delete payload.options;payload.callback=options;}if(isFunction(traits)){payload.userId=userId;delete payload.traits;delete payload.options;payload.callback=traits;}if(isObjectLiteralAndNotNull(userId)||isNull(userId)){// Explicitly set null to prevent resetting the existing value
945
+ // in the Analytics class
946
+ payload.userId=null;payload.traits=userId;payload.options=traits;}// Rest of the code is just to clean up undefined values
947
+ // and set some proper defaults
948
+ // Also, to clone the incoming object type arguments
949
+ if(isDefined(payload.userId)){payload.userId=tryStringify(payload.userId);}else {delete payload.userId;}if(isObjectLiteralAndNotNull(payload.traits)){payload.traits=clone$1(payload.traits);}else {delete payload.traits;}if(isDefined(payload.options)){payload.options=clone$1(payload.options);}else {delete payload.options;}return payload;};/*
950
+ * Normalise the overloaded arguments of the alias call facade
951
+ */var aliasArgumentsToCallOptions=function aliasArgumentsToCallOptions(to,from,options,callback){var payload={to:to,from:from,options:options};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.to=to;payload.from=from;delete payload.options;payload.callback=options;}if(isFunction(from)){payload.to=to;delete payload.from;delete payload.options;payload.callback=from;}else if(isObjectLiteralAndNotNull(from)||isNull(from)){payload.to=to;delete payload.from;payload.options=from;}if(isFunction(to)){delete payload.to;delete payload.from;delete payload.options;payload.callback=to;}else if(isObjectLiteralAndNotNull(to)||isNull(to)){delete payload.to;delete payload.from;payload.options=to;}// Rest of the code is just to clean up undefined values
952
+ // and set some proper defaults
953
+ // Also, to clone the incoming object type arguments
954
+ if(isDefined(payload.to)){payload.to=tryStringify(payload.to);}else {delete payload.to;}if(isDefined(payload.from)){payload.from=tryStringify(payload.from);}else {delete payload.from;}if(isDefined(payload.options)){payload.options=clone$1(payload.options);}else {delete payload.options;}return payload;};/*
955
+ * Normalise the overloaded arguments of the group call facade
956
+ */var groupArgumentsToCallOptions=function groupArgumentsToCallOptions(groupId,traits,options,callback){var payload={groupId:groupId,traits:traits,options:options};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.groupId=groupId;payload.traits=traits;delete payload.options;payload.callback=options;}if(isFunction(traits)){payload.groupId=groupId;delete payload.traits;delete payload.options;payload.callback=traits;}// TODO: why do we enable overload for group that only passes callback? is there any use case?
957
+ if(isFunction(groupId)){// Explicitly set null to prevent resetting the existing value
958
+ payload.groupId=null;delete payload.traits;delete payload.options;payload.callback=groupId;}else if(isObjectLiteralAndNotNull(groupId)||isNull(groupId)){// Explicitly set null to prevent resetting the existing value
959
+ // in the Analytics class
960
+ payload.groupId=null;payload.traits=groupId;payload.options=!isFunction(traits)?traits:null;}// Rest of the code is just to clean up undefined values
961
+ // and set some proper defaults
962
+ // Also, to clone the incoming object type arguments
963
+ if(isDefined(payload.groupId)){payload.groupId=tryStringify(payload.groupId);}else {delete payload.groupId;}payload.traits=isObjectLiteralAndNotNull(payload.traits)?clone$1(payload.traits):{};if(isDefined(payload.options)){payload.options=clone$1(payload.options);}else {delete payload.options;}return payload;};
964
+
965
+ var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RS_APP='RudderStackApplication';var ANALYTICS_CORE='AnalyticsCore';
966
+
967
+ var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.0.0-beta.14';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
968
+
969
+ var QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';var QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';var QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';var QUERY_PARAM_USER_ID_KEY='ajs_uid';var QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
970
+
971
+ var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
972
+ var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
973
+ var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
974
+ var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
975
+ var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
976
+ var DEBOUNCED_TIMEOUT_MS=250;// 250 milliseconds
977
+
978
+ /**
979
+ * Create globally accessible RudderStackGlobals object
980
+ */var createExposedGlobals=function createExposedGlobals(){var analyticsInstanceId=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'app';if(!globalThis.RudderStackGlobals){globalThis.RudderStackGlobals={};}if(!globalThis.RudderStackGlobals[analyticsInstanceId]){globalThis.RudderStackGlobals[analyticsInstanceId]={};}};/**
981
+ * Add move values to globally accessible RudderStackGlobals object per analytics instance
982
+ */var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
983
+ * Get values from globally accessible RudderStackGlobals object by analytics instance
984
+ */var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};function debounce(func,thisArg){var delay=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEBOUNCED_TIMEOUT_MS;var timeoutId;return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}globalThis.clearTimeout(timeoutId);timeoutId=globalThis.setTimeout(function(){func.apply(thisArg,args);},delay);};}
985
+
986
+ /**
987
+ * Parse query string params into object values for keys that start with a defined prefix
988
+ */var getEventDataFromQueryString=function getEventDataFromQueryString(params,dataTypeNamePrefix){var data={};params.forEach(function(value,key){if(key.startsWith(dataTypeNamePrefix)){// remove prefix from key name
989
+ var dataKey=key.substring(dataTypeNamePrefix.length);// add new key value pair in generated object
990
+ data[dataKey]=params.get(key);}});return data;};/**
991
+ * Parse query string into preload buffer events & push into existing array before any other events
992
+ */var retrieveEventsFromQueryString=function retrieveEventsFromQueryString(){var argumentsArray=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];// Mapping for trait and properties values based on key prefix
993
+ var eventArgumentToQueryParamMap={trait:QUERY_PARAM_TRAIT_PREFIX,properties:QUERY_PARAM_PROPERTY_PREFIX};var queryObject=new URLSearchParams(globalThis.location.search);// Add track events with name and properties
994
+ if(queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY)){argumentsArray.unshift(['track',queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY),getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.properties)]);}// Set userId and user traits
995
+ if(queryObject.get(QUERY_PARAM_USER_ID_KEY)){argumentsArray.unshift(['identify',queryObject.get(QUERY_PARAM_USER_ID_KEY),getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.trait)]);}// Set anonymousID
996
+ if(queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)){argumentsArray.unshift(['setAnonymousId',queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)]);}};/**
997
+ * Retrieve an existing buffered load method call and remove from the existing array
998
+ */var getPreloadedLoadEvent=function getPreloadedLoadEvent(preloadedEventsArray){var loadMethodName='load';var loadEvent=[];/**
999
+ * Iterate the buffered API calls until we find load call and process it separately
1000
+ */var i=0;while(i<preloadedEventsArray.length){if(preloadedEventsArray[i]&&preloadedEventsArray[i][0]===loadMethodName){loadEvent=preloadedEventsArray[i];preloadedEventsArray.splice(i,1);break;}i+=1;}return loadEvent;};/**
1001
+ * Retrieve any existing events that were triggered before SDK load and enqueue in buffer
1002
+ */var retrievePreloadBufferEvents=function retrievePreloadBufferEvents(instance){var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER)||[];// Get events that are pre-populated via query string params
1003
+ retrieveEventsFromQueryString(preloadedEventsArray);var sanitizedPreloadedEventsArray=preloadedEventsArray.filter(function(bufferedEvent){return bufferedEvent[0]!=='load';});// Enqueue the non load events in the buffer of the global rudder analytics singleton
1004
+ if(sanitizedPreloadedEventsArray.length>0){instance.enqueuePreloadBufferEvents(sanitizedPreloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,[]);}};var consumePreloadBufferedEvent=function consumePreloadBufferedEvent(event,analyticsInstance){var _ref;var methodName=event.shift();var callOptions;if(isFunction(analyticsInstance[methodName])){switch(methodName){case'page':callOptions=pageArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'track':callOptions=trackArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'identify':callOptions=identifyArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'alias':callOptions=aliasArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'group':callOptions=groupArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;default:(_ref=analyticsInstance)[methodName].apply(_ref,_toConsumableArray(event));break;}if(callOptions){analyticsInstance[methodName](callOptions);}}};
1005
+
1006
+ var DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
1007
+
1008
+ var LOG_CONTEXT_SEPARATOR=':: ';var SCRIPT_ALREADY_EXISTS_ERROR=function SCRIPT_ALREADY_EXISTS_ERROR(id){return "A script with the id \"".concat(id,"\" is already loaded. Skipping the loading of this script to prevent conflicts.");};var SCRIPT_LOAD_ERROR=function SCRIPT_LOAD_ERROR(id,url){return "Failed to load the script with the id \"".concat(id,"\" from URL \"").concat(url,"\".");};var SCRIPT_LOAD_TIMEOUT_ERROR=function SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout){return "A timeout of ".concat(timeout," ms occurred while trying to load the script with id \"").concat(id,"\" from URL \"").concat(url,"\".");};var CIRCULAR_REFERENCE_WARNING=function CIRCULAR_REFERENCE_WARNING(context,key){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"A circular reference has been detected in the object and the property \"").concat(key,"\" has been dropped from the output.");};var JSON_STRINGIFY_WARNING="Failed to convert the value to a JSON string.";
1009
+
1010
+ var JSON_STRINGIFY='JSONStringify';var getCircularReplacer=function getCircularReplacer(excludeNull,excludeKeys,logger){var ancestors=[];// Here we do not want to use arrow function to use "this" in function context
1011
+ // eslint-disable-next-line func-names
1012
+ return function(key,value){if(excludeKeys!==null&&excludeKeys!==void 0&&excludeKeys.includes(key)){return undefined;}if(excludeNull&&isNullOrUndefined(value)){return undefined;}if(_typeof(value)!=='object'||isNull(value)){return value;}// `this` is the object that value is contained in, i.e., its direct parent.
1013
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1014
+ // @ts-ignore-next-line
1015
+ while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return '[Circular Reference]';}ancestors.push(value);return value;};};/**
1016
+ * Utility method for JSON stringify object excluding null values & circular references
1017
+ *
1018
+ * @param {*} value input
1019
+ * @param {boolean} excludeNull if it should exclude nul or not
1020
+ * @param {function} logger optional logger methods for warning
1021
+ * @returns string
1022
+ */var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};
1023
+
1024
+ /**
1025
+ * Get mutated error with issue prepended to error message
1026
+ * @param err Original error
1027
+ * @param issue Issue to prepend to error message
1028
+ * @returns Instance of Error with message prepended with issue
1029
+ */var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};
1030
+
1031
+ var EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
1032
+
1033
+ /**
1034
+ * Create the DOM element to load a script marked as RS SDK originated
1035
+ *
1036
+ * @param {*} url The URL of the script to be loaded
1037
+ * @param {*} id ID for the script tag
1038
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
1039
+ * @param {*} onload callback to invoke onload [optional]
1040
+ * @param {*} onerror callback to invoke onerror [optional]
1041
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
1042
+ *
1043
+ * @returns HTMLScriptElement
1044
+ */var createScriptElement=function createScriptElement(url,id){var async=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var onload=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var onerror=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;var extraAttributes=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{};var scriptElement=document.createElement('script');scriptElement.type='text/javascript';scriptElement.onload=onload;scriptElement.onerror=onerror;scriptElement.src=url;scriptElement.id=id;scriptElement.async=async;scriptElement.setAttribute('data-append-origin',EXTERNAL_SOURCE_LOAD_ORIGIN);Object.keys(extraAttributes).forEach(function(attributeName){scriptElement.setAttribute(attributeName,extraAttributes[attributeName]);});return scriptElement;};/**
1045
+ * Add script DOM element to DOM
1046
+ *
1047
+ * @param {*} newScriptElement the script element to add
1048
+ *
1049
+ * @returns
1050
+ */var insertScript=function insertScript(newScriptElement){var _scriptElements$;// First try to add it to the head
1051
+ var headElements=document.getElementsByTagName('head');if(headElements.length>0){var _headElements$,_headElements$2;(_headElements$=headElements[0])===null||_headElements$===void 0||_headElements$.insertBefore(newScriptElement,(_headElements$2=headElements[0])===null||_headElements$2===void 0?void 0:_headElements$2.firstChild);return;}// Else wise add it before the first script tag
1052
+ var scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&(_scriptElements$=scriptElements[0])!==null&&_scriptElements$!==void 0&&_scriptElements$.parentNode){var _scriptElements$2;(_scriptElements$2=scriptElements[0])===null||_scriptElements$2===void 0||_scriptElements$2.parentNode.insertBefore(newScriptElement,scriptElements[0]);return;}// Create a new head element and add the script as fallback
1053
+ var headElement=document.createElement('head');headElement.appendChild(newScriptElement);var htmlElement=document.getElementsByTagName('html')[0];htmlElement===null||htmlElement===void 0||htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
1054
+ * Loads external js file as a script html tag
1055
+ *
1056
+ * @param {*} url The URL of the script to be loaded
1057
+ * @param {*} id ID for the script tag
1058
+ * @param {*} timeout loading timeout
1059
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
1060
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
1061
+ *
1062
+ * @returns
1063
+ */var jsFileLoader=function jsFileLoader(url,id,timeout){var async=arguments.length>3&&arguments[3]!==undefined?arguments[3]:true;var extraAttributes=arguments.length>4?arguments[4]:undefined;return new Promise(function(resolve,reject){var scriptExists=document.getElementById(id);if(scriptExists){reject(new Error(SCRIPT_ALREADY_EXISTS_ERROR(id)));}try{var timeoutID;var onload=function onload(){globalThis.clearTimeout(timeoutID);resolve(id);};var onerror=function onerror(){globalThis.clearTimeout(timeoutID);reject(new Error(SCRIPT_LOAD_ERROR(id,url)));};// Create the DOM element to load the script and add it to the DOM
1064
+ insertScript(createScriptElement(url,id,async,onload,onerror,extraAttributes));// Reject on timeout
1065
+ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout)));},timeout);}catch(err){reject(getMutatedError(err,SCRIPT_LOAD_ERROR(id,url)));}});};
1066
+
1067
+ /**
1068
+ * Service to load external resources/files
1069
+ */var ExternalSrcLoader=/*#__PURE__*/function(){function ExternalSrcLoader(errorHandler,logger){var timeout=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS;_classCallCheck(this,ExternalSrcLoader);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.timeout=timeout;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
1070
+ * Load external resource of type javascript
1071
+ */_createClass(ExternalSrcLoader,[{key:"loadJSFile",value:function loadJSFile(config){var _this=this;var url=config.url,id=config.id,timeout=config.timeout,async=config.async,callback=config.callback,extraAttributes=config.extraAttributes;var isFireAndForget=!isFunction(callback);jsFileLoader(url,id,timeout||this.timeout,async,extraAttributes).then(function(id){if(!isFireAndForget){callback(id);}}).catch(function(err){_this.onError(err);if(!isFireAndForget){callback();}});}/**
1072
+ * Handle errors
1073
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}]);return ExternalSrcLoader;}();
1074
+
1075
+ function i$2(){throw new Error("Cycle detected");}var t$1=Symbol.for("preact-signals");function r(){if(!(v>1)){var i,t=!1;while(void 0!==f){var r=f;f=void 0;e++;while(void 0!==r){var n=r.o;r.o=void 0;r.f&=-3;if(!(8&r.f)&&l(r))try{r.c();}catch(r){if(!t){i=r;t=!0;}}r=n;}}e=0;v--;if(t)throw i;}else v--;}function n(i){if(v>0)return i();v++;try{return i();}finally{r();}}var o=void 0;var f=void 0,v=0,e=0,u=0;function c(i){if(void 0!==o){var t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t;}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t;}return t;}}}function d$1(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0;}d$1.prototype.brand=t$1;d$1.prototype.h=function(){return !0;};d$1.prototype.S=function(i){if(this.t!==i&&void 0===i.e){i.x=this.t;if(void 0!==this.t)this.t.e=i;this.t=i;}};d$1.prototype.U=function(i){if(void 0!==this.t){var t=i.e,r=i.x;if(void 0!==t){t.x=r;i.e=void 0;}if(void 0!==r){r.e=t;i.x=void 0;}if(i===this.t)this.t=r;}};d$1.prototype.subscribe=function(i){var t=this;return O(function(){var r=t.value,n=32&this.f;this.f&=-33;try{i(r);}finally{this.f|=n;}});};d$1.prototype.valueOf=function(){return this.value;};d$1.prototype.toString=function(){return this.value+"";};d$1.prototype.toJSON=function(){return this.value;};d$1.prototype.peek=function(){return this.v;};Object.defineProperty(d$1.prototype,"value",{get:function get(){var i=c(this);if(void 0!==i)i.i=this.i;return this.v;},set:function set(t){if(o instanceof _)!function(){throw new Error("Computed cannot have side-effects");}();if(t!==this.v){if(e>100)i$2();this.v=t;this.i++;u++;v++;try{for(var n=this.t;void 0!==n;n=n.x)n.t.N();}finally{r();}}}});function a(i){return new d$1(i);}function l(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return !0;return !1;}function y(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break;}}}function w(i){var t=i.s,r=void 0;while(void 0!==t){var n=t.p;if(-1===t.i){t.S.U(t);if(void 0!==n)n.n=t.n;if(void 0!==t.n)t.n.p=n;}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=n;}i.s=r;}function _(i){d$1.call(this,void 0);this.x=i;this.s=void 0;this.g=u-1;this.f=4;}(_.prototype=new d$1()).h=function(){this.f&=-3;if(1&this.f)return !1;if(32==(36&this.f))return !0;this.f&=-5;if(this.g===u)return !0;this.g=u;this.f|=1;if(this.i>0&&!l(this)){this.f&=-2;return !0;}var i=o;try{y(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++;}}catch(i){this.v=i;this.f|=16;this.i++;}o=i;w(this);this.f&=-2;return !0;};_.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t);}d$1.prototype.S.call(this,i);};_.prototype.U=function(i){if(void 0!==this.t){d$1.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t);}}};_.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N();}};_.prototype.peek=function(){if(!this.h())i$2();if(16&this.f)throw this.v;return this.v;};Object.defineProperty(_.prototype,"value",{get:function get(){if(1&this.f)i$2();var t=c(this);this.h();if(void 0!==t)t.i=this.i;if(16&this.f)throw this.v;return this.v;}});function g(i){var t=i.u;i.u=void 0;if("function"==typeof t){v++;var n=o;o=void 0;try{t();}catch(t){i.f&=-2;i.f|=8;b(i);throw t;}finally{o=n;r();}}}function b(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;g(i);}function x$1(i){if(o!==this)throw new Error("Out-of-order effect");w(this);o=i;this.f&=-2;if(8&this.f)b(this);r();}function E(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;}E.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if("function"==typeof t)this.u=t;}finally{i();}};E.prototype.S=function(){if(1&this.f)i$2();this.f|=1;this.f&=-9;g(this);y(this);v++;var t=o;o=this;return x$1.bind(this,t);};E.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=f;f=this;}};E.prototype.d=function(){this.f|=8;if(!(1&this.f))b(this);};function O(i){var t=new E(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
1076
+
1077
+ var LOG_LEVEL_MAP={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5};var DEFAULT_LOG_LEVEL='ERROR';var LOG_MSG_PREFIX='RS SDK';var LOG_MSG_PREFIX_STYLE='font-weight: bold; background: black; color: white;';var LOG_MSG_STYLE='font-weight: normal;';/**
1078
+ * Service to log messages/data to output provider, default is console
1079
+ */var Logger=/*#__PURE__*/function(){function Logger(){var minLogLevel=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_LOG_LEVEL;var scope=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var logProvider=arguments.length>2&&arguments[2]!==undefined?arguments[2]:console;_classCallCheck(this,Logger);this.minLogLevel=LOG_LEVEL_MAP[minLogLevel];this.scope=scope;this.logProvider=logProvider;}_createClass(Logger,[{key:"log",value:function log(){for(var _len=arguments.length,data=new Array(_len),_key=0;_key<_len;_key++){data[_key]=arguments[_key];}this.outputLog('LOG',data);}},{key:"info",value:function info(){for(var _len2=arguments.length,data=new Array(_len2),_key2=0;_key2<_len2;_key2++){data[_key2]=arguments[_key2];}this.outputLog('INFO',data);}},{key:"debug",value:function debug(){for(var _len3=arguments.length,data=new Array(_len3),_key3=0;_key3<_len3;_key3++){data[_key3]=arguments[_key3];}this.outputLog('DEBUG',data);}},{key:"warn",value:function warn(){for(var _len4=arguments.length,data=new Array(_len4),_key4=0;_key4<_len4;_key4++){data[_key4]=arguments[_key4];}this.outputLog('WARN',data);}},{key:"error",value:function error(){for(var _len5=arguments.length,data=new Array(_len5),_key5=0;_key5<_len5;_key5++){data[_key5]=arguments[_key5];}this.outputLog('ERROR',data);}},{key:"outputLog",value:function outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider,_this$logProvider2;(_this$logProvider=(_this$logProvider2=this.logProvider)[logMethod.toLowerCase()])===null||_this$logProvider===void 0||_this$logProvider.call.apply(_this$logProvider,[_this$logProvider2].concat(_toConsumableArray(this.formatLogData(data))));}}},{key:"setScope",value:function setScope(scopeVal){this.scope=scopeVal||this.scope;}// TODO: should we allow to change the level via global variable on run time
1080
+ // to assist on the fly debugging?
1081
+ },{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
1082
+ * Formats the console message using `scope` and styles
1083
+ */},{key:"formatLogData",value:function formatLogData(data){if(Array.isArray(data)&&data.length>0){// prefix SDK identifier
1084
+ var msg="%c ".concat(LOG_MSG_PREFIX);// format the log message using `scope`
1085
+ if(this.scope){msg="".concat(msg," - ").concat(this.scope);}// trim whitespaces for original message
1086
+ var originalMsg=isString(data[0])?data[0].trim():'';// prepare the final message
1087
+ msg="".concat(msg," %c ").concat(originalMsg);var styledLogArgs=[msg,LOG_MSG_PREFIX_STYLE,// add style for the prefix
1088
+ LOG_MSG_STYLE// reset the style for the actual message
1089
+ ];// add first it if it was not a string msg
1090
+ if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
1091
+ styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);return Logger;}();var defaultLogger=new Logger();
1092
+
1093
+ // default is v3
1094
+ var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
1095
+
1096
+ var SOURCE_CONFIG_OPTION_ERROR="\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.";var INTG_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for integrations is not valid.";var PLUGINS_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for plugins is not valid.";var DATA_PLANE_URL_ERROR="Failed to load the SDK as the data plane URL could not be determined. Please check that the data plane URL is set correctly and try again.";var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var EVENT_OBJECT_GENERATION_ERROR="Failed to generate the event object.";var PLUGIN_EXT_POINT_MISSING_ERROR="Failed to invoke plugin because the extension point name is missing.";var PLUGIN_EXT_POINT_INVALID_ERROR="Failed to invoke plugin because the extension point name is invalid.";// ERROR
1097
+ var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "The write key \"".concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl){return "The data plane URL \"".concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};// WARNING
1098
+ var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=function UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(context,selectedResidencyServerRegion,defaultRegion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The residency server region \"").concat(selectedResidencyServerRegion,"\" is not supported. Please choose one of the following supported regions: \"US, EU\". The default region \"").concat(defaultRegion,"\" will be used instead.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var INVALID_CONTEXT_OBJECT_WARNING=function INVALID_CONTEXT_OBJECT_WARNING(logContext){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"Please make sure that the \"context\" property in the event API's \"options\" argument is a valid object literal with key-value pairs.");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var WRITE_KEY_NOT_A_STRING_ERROR=function WRITE_KEY_NOT_A_STRING_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is not a string. Please check that the write key is correct and try again.");};var EMPTY_GROUP_CALL_ERROR=function EMPTY_GROUP_CALL_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The group() method must be called with at least one argument.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided config URL \"").concat(configUrl,"\" is invalid. Using the default value instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var COOKIE_DATA_ENCODING_ERROR="Failed to encode the cookie data.";var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};// DEBUG
1099
+
1100
+ var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';
1101
+
1102
+ var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var DEST_SDK_BASE_URL="".concat(SDK_CDN_BASE_URL,"/beta/3.0.0-beta/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var PLUGINS_BASE_URL="".concat(SDK_CDN_BASE_URL,"/beta/3.0.0-beta/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);// TODO: change the above to production URLs when beta phase is done
1103
+ // const DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;
1104
+ // const PLUGINS_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;
1105
+ var DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
1106
+
1107
+ var _StorageEncryptionVer;var DEFAULT_ERROR_REPORTING_PROVIDER='bugsnag';var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var ConsentManagersToPluginNameMap={oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};var ErrorReportingProvidersToPluginNameMap=_defineProperty({},DEFAULT_ERROR_REPORTING_PROVIDER,'Bugsnag');var StorageEncryptionVersionsToPluginNameMap=(_StorageEncryptionVer={},_defineProperty(_StorageEncryptionVer,DEFAULT_STORAGE_ENCRYPTION_VERSION,'StorageEncryption'),_defineProperty(_StorageEncryptionVer,"legacy",'StorageEncryptionLegacy'),_StorageEncryptionVer);
1108
+
1109
+ var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:false},sendAdblockPageOptions:{}};var loadOptionsState=a(clone$1(defaultLoadOptions));
1110
+
1111
+ var USER_SESSION_STORAGE_KEYS={userId:'rl_user_id',userTraits:'rl_trait',anonymousId:'rl_anonymous_id',groupId:'rl_group_id',groupTraits:'rl_group_trait',initialReferrer:'rl_page_init_referrer',initialReferringDomain:'rl_page_init_referring_domain',sessionInfo:'rl_session',authToken:'rl_auth_token'};var DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};
1112
+
1113
+ var defaultSessionInfo={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS};var sessionState={userId:a(DEFAULT_USER_SESSION_VALUES.userId),userTraits:a(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:a(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:a(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:a(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:a(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:a(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:a(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:a(DEFAULT_USER_SESSION_VALUES.authToken)};
1114
+
1115
+ var capabilitiesState={isOnline:a(true),storage:{isLocalStorageAvailable:a(false),isCookieStorageAvailable:a(false),isSessionStorageAvailable:a(false)},isBeaconAvailable:a(false),isLegacyDOM:a(false),isUaCHAvailable:a(false),isCryptoAvailable:a(false),isIE11:a(false),isAdBlocked:a(false)};
1116
+
1117
+ var reportingState={isErrorReportingEnabled:a(false),isMetricsReportingEnabled:a(false),errorReportingProviderPluginName:a(undefined)};
1118
+
1119
+ var sourceConfigState=a(undefined);
1120
+
1121
+ var lifecycleState={activeDataplaneUrl:a(undefined),integrationsCDNPath:a(DEST_SDK_BASE_URL),pluginsCDNPath:a(PLUGINS_BASE_URL),sourceConfigUrl:a(undefined),status:a(undefined),initialized:a(false),logLevel:a('ERROR'),loaded:a(false),readyCallbacks:a([]),writeKey:a(undefined),dataPlaneUrl:a(undefined)};
1122
+
1123
+ var consentsState={enabled:a(false),initialized:a(false),data:a({}),activeConsentManagerPluginName:a(undefined),preConsent:a({enabled:false}),postConsent:a({}),resolutionStrategy:a('and'),provider:a(undefined),metadata:a(undefined)};
1124
+
1125
+ var metricsState={retries:a(0),dropped:a(0),sent:a(0),queued:a(0),triggered:a(0)};
1126
+
1127
+ var contextState={app:a({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:a(null),library:a({name:APP_NAME,version:APP_VERSION}),userAgent:a(''),device:a(null),network:a(null),os:a({name:'',version:''}),locale:a(null),screen:a({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':a(undefined),timezone:a(undefined)};
1128
+
1129
+ var nativeDestinationsState={configuredDestinations:a([]),activeDestinations:a([]),loadOnlyIntegrations:a({}),failedDestinations:a([]),loadIntegration:a(true),initializedDestinations:a([]),clientDestinationsReady:a(false),integrationsConfig:a({})};
1130
+
1131
+ var eventBufferState={toBeProcessedArray:a([]),readyCallbacksArray:a([])};
1132
+
1133
+ var pluginsState={ready:a(false),loadedPlugins:a([]),failedPlugins:a([]),pluginsToLoadFromConfig:a([]),activePlugins:a([]),totalPluginsToLoad:a(0)};
1134
+
1135
+ var storageState={encryptionPluginName:a(undefined),migrate:a(false),type:a(undefined),cookie:a(undefined),entries:a({}),trulyAnonymousTracking:a(false)};
1136
+
1137
+ var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,context:contextState,eventBuffer:eventBufferState,lifecycle:lifecycleState,loadOptions:loadOptionsState,metrics:metricsState,nativeDestinations:nativeDestinationsState,plugins:pluginsState,reporting:reportingState,session:sessionState,source:sourceConfigState,storage:storageState};var state=_objectSpread2({},clone$1(defaultStateValues));
1138
+
1139
+ // to next or return the value if it is the last one instead of an array per
1140
+ // plugin that is the normal invoke
1141
+ // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1142
+ var PluginEngine=/*#__PURE__*/function(){function PluginEngine(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,PluginEngine);_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}_createClass(PluginEngine,[{key:"register",value:function register(plugin,state){if(!plugin.name){var errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.error(errorMessage,plugin);}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(_errorMessage);}}this.cache={};this.plugins=this.plugins.slice();var pos=this.plugins.length;this.plugins.forEach(function(pluginItem,index){var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==void 0&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}},{key:"unregister",value:function unregister(name){var plugin=this.byName[name];if(!plugin){var errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error(errorMessage);}}var index=this.plugins.indexOf(plugin);if(index===-1){var _errorMessage2=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(_errorMessage2);}else {var _this$logger4;(_this$logger4=this.logger)===null||_this$logger4===void 0||_this$logger4.error(_errorMessage2);}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}},{key:"getPlugin",value:function getPlugin(name){return this.byName[name];}},{key:"getPlugins",value:function getPlugins(extPoint){var _this=this;var lifeCycleName=extPoint!==null&&extPoint!==void 0?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(function(plugin){var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==void 0&&_plugin$deps.some(function(dependency){return !_this.byName[dependency];})){var _this$logger5;// If deps not exist, then not load it.
1143
+ var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===void 0||_this$logger5.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
1144
+ // do some unified pre-process before application starts.
1145
+ },{key:"processRawPlugins",value:function processRawPlugins(callback){callback(this.plugins);this.cache={};}},{key:"invoke",value:function invoke(extPoint){var _this$config$throws,_this2=this;var allowMultiple=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}var extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}var noCall=extensionPointName.startsWith('!');var throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==void 0?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
1146
+ extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}var extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();var pluginMethodPath=extensionPointNameParts.join('.');var pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(function(plugin){var method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
1147
+ if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);return PluginEngine;}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
1148
+
1149
+ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
1150
+
1151
+ /**
1152
+ * Utility method to normalise errors
1153
+ */var processError=function processError(error){var errorMessage;try{if(isString(error)){errorMessage=error;}else if(error instanceof Error){errorMessage=error.message;}else {errorMessage=error.message?error.message:stringifyWithoutCircular(error);}}catch(e){errorMessage="Unknown error: ".concat(e.message);}return errorMessage;};/**
1154
+ * A function to determine whether the error should be promoted to notify or not
1155
+ * @param {Error} error
1156
+ * @returns
1157
+ */var isAllowedToBeNotified=function isAllowedToBeNotified(error){if(error.message){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return error.message.includes(e);});}return true;};
1158
+
1159
+ /**
1160
+ * A service to handle errors
1161
+ */var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
1162
+ function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;}_createClass(ErrorHandler,[{key:"init",value:function init(externalSrcLoader){var _this=this;if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this.errReportingClient=client;}).catch(function(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}},{key:"onError",value:function onError(error){var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var shouldAlwaysThrow=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;// Error handling is already implemented in processError method
1163
+ var errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
1164
+ if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));var normalizedError=error;// Enhance error message
1165
+ if(isTypeOfError(error)){normalizedError.message=errorMessage;}else {normalizedError=new Error(errorMessage);}this.notifyError(normalizedError);if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}/**
1166
+ * Add breadcrumbs to add insight of a user's journey before an error
1167
+ * occurred and send to external error monitoring service via a plugin
1168
+ *
1169
+ * @param {string} breadcrumb breadcrumbs message
1170
+ */},{key:"leaveBreadcrumb",value:function leaveBreadcrumb(breadcrumb){if(this.pluginEngine){try{this.pluginEngine.invokeSingle('errorReporting.breadcrumb',this.pluginEngine,this.errReportingClient,breadcrumb,this.logger);}catch(err){this.onError(err,ERROR_HANDLER,'errorReporting.breadcrumb');}}}/**
1171
+ * Send handled errors to external error monitoring service via a plugin
1172
+ *
1173
+ * @param {Error} error Error instance from handled error
1174
+ */},{key:"notifyError",value:function notifyError(error){if(this.pluginEngine&&isAllowedToBeNotified(error)){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,this.errReportingClient,error,state,this.logger);}catch(err){var _this$logger2;// Not calling onError here as we don't want to go into infinite loop
1175
+ (_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);return ErrorHandler;}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
1176
+
1177
+ /**
1178
+ * A function to filter and return non cloud mode destinations
1179
+ * @param destination
1180
+ *
1181
+ * @returns boolean
1182
+ */var isNonCloudDestination=function isNonCloudDestination(destination){return Boolean(destination.config.connectionMode!=='cloud'||destination.config.useNativeSDKToSend===true||// this is the older flag for hybrid mode destinations
1183
+ destination.config.useNativeSDK===true);};var isHybridModeDestination=function isHybridModeDestination(destination){return Boolean(destination.config.connectionMode==='hybrid'||destination.config.useNativeSDKToSend===true);};/**
1184
+ * A function to filter and return non cloud mode destinations
1185
+ * @param destinations
1186
+ *
1187
+ * @returns destinations
1188
+ */var getNonCloudDestinations=function getNonCloudDestinations(destinations){return destinations.filter(isNonCloudDestination);};
1189
+
1190
+ /**
1191
+ * List of plugin names that are loaded as dynamic imports in modern builds
1192
+ */var pluginNamesList=['BeaconQueue','Bugsnag','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
1193
+
1194
+ var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';
1195
+
1196
+ var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.replace(/\/{2,}/g,'/');};
1197
+
1198
+ function random(len){return crypto.getRandomValues(new Uint8Array(len));}
1199
+
1200
+ var SIZE=4096,HEX$1=[],IDX$1=0,BUFFER$1;for(;IDX$1<256;IDX$1++){HEX$1[IDX$1]=(IDX$1+256).toString(16).substring(1);}function v4$1(){if(!BUFFER$1||IDX$1+16>SIZE){BUFFER$1=random(SIZE);IDX$1=0;}var i=0,tmp,out='';for(;i<16;i++){tmp=BUFFER$1[IDX$1+i];if(i==6)out+=HEX$1[tmp&15|64];else if(i==8)out+=HEX$1[tmp&63|128];else out+=HEX$1[tmp];if(i&1&&i>1&&i<11)out+='-';}IDX$1+=16;return out;}
1201
+
1202
+ var IDX=256,HEX=[],BUFFER;while(IDX--)HEX[IDX]=(IDX+256).toString(16).substring(1);function v4(){var i=0,num,out='';if(!BUFFER||IDX+16>256){BUFFER=Array(i=256);while(i--)BUFFER[i]=256*Math.random()|0;i=IDX=0;}for(;i<16;i++){num=BUFFER[IDX+i];if(i==6)out+=HEX[num&15|64];else if(i==8)out+=HEX[num&63|128];else out+=HEX[num];if(i&1&&i>1&&i<11)out+='-';}IDX++;return out;}
1203
+
1204
+ var hasCrypto$1=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};
1205
+
1206
+ var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
1207
+
1208
+ var isErrRetryable=function isErrRetryable(details){var isRetryableNWFailure=false;if(details!==null&&details!==void 0&&details.error&&details!==null&&details!==void 0&&details.xhr){var xhrStatus=details.xhr.status;// same as in v1.1
1209
+ isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRetryableNWFailure;};
1210
+
1211
+ /**
1212
+ * To get the current timestamp in ISO string format
1213
+ * @returns ISO formatted timestamp string
1214
+ */var getCurrentTimeFormatted=function getCurrentTimeFormatted(){var curDateTime=new Date().toISOString();return curDateTime;};
1215
+
1216
+ var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
1217
+
1218
+ var EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING=function EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(context,payloadSize,sizeLimit){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The size of the event payload (").concat(payloadSize," bytes) exceeds the maximum limit of ").concat(sizeLimit," bytes. Events with large payloads may be dropped in the future. Please review your instrumentation to ensure that event payloads are within the size limit.");};var EVENT_PAYLOAD_SIZE_VALIDATION_WARNING=function EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to validate event payload size. Please make sure that the event payload is within the size limit and is a valid JSON object.");};var QUEUE_UTILITIES='QueueUtilities';/**
1219
+ * Utility to get the stringified event payload
1220
+ * @param event RudderEvent object
1221
+ * @param logger Logger instance
1222
+ * @returns stringified event payload. Empty string if error occurs.
1223
+ */var getDeliveryPayload=function getDeliveryPayload(event,logger){return stringifyWithoutCircular(event,true,undefined,logger);};var getDMTDeliveryPayload=function getDMTDeliveryPayload(dmtRequestPayload,logger){return stringifyWithoutCircular(dmtRequestPayload,true,undefined,logger);};/**
1224
+ * Utility to validate final payload size before sending to server
1225
+ * @param event RudderEvent object
1226
+ * @param logger Logger instance
1227
+ */var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload(event,logger);if(payloadStr){var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}}else {logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));}};/**
1228
+ * Mutates the event and return final event for delivery
1229
+ * Updates certain parameters like sentAt timestamp, integrations config etc.
1230
+ * @param event RudderEvent object
1231
+ * @returns Final event ready to be delivered
1232
+ */var getFinalEventForDeliveryMutator=function getFinalEventForDeliveryMutator(event){var finalEvent=clone$1(event);// Update sentAt timestamp to the latest timestamp
1233
+ finalEvent.sentAt=getCurrentTimeFormatted();return finalEvent;};
1234
+
1235
+ var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
1236
+
1237
+ var encrypt$1=function encrypt(value){return "".concat(ENCRYPTION_PREFIX_V3).concat(toBase64(value));};var decrypt$1=function decrypt(value){if(value.startsWith(ENCRYPTION_PREFIX_V3)){return fromBase64(value.substring(ENCRYPTION_PREFIX_V3.length));}return value;};
1238
+
1239
+ var BEACON_PLUGIN_EVENTS_QUEUE_DEBUG=function BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Sending events to data plane.");};var BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to string.");};var BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to Blob.");};var BEACON_QUEUE_SEND_ERROR=function BEACON_QUEUE_SEND_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to send events batch data to the browser's beacon queue. The events will be dropped.");};var BEACON_QUEUE_DELIVERY_ERROR=function BEACON_QUEUE_DELIVERY_ERROR(url){return "Failed to send events batch data to the browser's beacon queue for URL ".concat(url,".");};
1240
+
1241
+ var DEFAULT_BEACON_QUEUE_MAX_SIZE=10;var DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS=10*60*1000;// 10 minutes
1242
+ // Limit of the Beacon transfer mechanism on the browsers
1243
+ var MAX_BATCH_PAYLOAD_SIZE_BYTES=64*1024;// 64 KB
1244
+ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQueueInterval:DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS};var DATA_PLANE_API_VERSION$1='v1';var QUEUE_NAME$3='rudder_beacon';var BEACON_QUEUE_PLUGIN='BeaconQueuePlugin';
1245
+
1246
+ /**
1247
+ * Utility to get the stringified event payload as Blob
1248
+ * @param events RudderEvent object array
1249
+ * @param logger Logger instance
1250
+ * @returns stringified events payload as Blob, undefined if error occurs.
1251
+ */var getBatchDeliveryPayload$1=function getBatchDeliveryPayload(events,logger){var data={batch:events};try{var blobPayload=stringifyWithoutCircular(data,true);var blobOptions={type:'text/plain'};if(blobPayload){return new Blob([blobPayload],blobOptions);}logger===null||logger===void 0||logger.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));}catch(err){logger===null||logger===void 0||logger.error(BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN),err);}return undefined;};var getNormalizedBeaconQueueOptions=function getNormalizedBeaconQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_BEACON_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl$1=function getDeliveryUrl(dataplaneUrl,writeKey){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/','beacon','/',DATA_PLANE_API_VERSION$1,'/',"batch?writeKey=".concat(writeKey)].join('')),dpUrl).href;};
1252
+
1253
+ var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
1254
+
1255
+ var ScheduleModes=/*#__PURE__*/function(ScheduleModes){ScheduleModes[ScheduleModes["ASAP"]=1]="ASAP";ScheduleModes[ScheduleModes["RESCHEDULE"]=2]="RESCHEDULE";ScheduleModes[ScheduleModes["ABANDON"]=3]="ABANDON";return ScheduleModes;}({});var DEFAULT_CLOCK_LATE_FACTOR=2;var DEFAULT_CLOCK={setTimeout:function setTimeout(fn,ms){return globalThis.setTimeout(fn,ms);},clearTimeout:function clearTimeout(id){return globalThis.clearTimeout(id);},Date:globalThis.Date,clockLateFactor:DEFAULT_CLOCK_LATE_FACTOR};var Schedule=/*#__PURE__*/function(){function Schedule(){_classCallCheck(this,Schedule);this.tasks={};this.nextId=1;this.clock=DEFAULT_CLOCK;}_createClass(Schedule,[{key:"now",value:function now(){return +new this.clock.Date();}},{key:"run",value:function run(task,timeout,mode){var id=(this.nextId+1).toString();this.tasks[id]=this.clock.setTimeout(this.handle(id,task,timeout,mode||ScheduleModes.ASAP),timeout);return id;}},{key:"handle",value:function handle(id,callback,timeout,mode){var _this=this;var start=this.now();return function(){delete _this.tasks[id];var elapsedTimeoutTime=start+timeout*(_this.clock.clockLateFactor||DEFAULT_CLOCK_LATE_FACTOR);var currentTime=_this.now();var notCompletedOrTimedOut=mode>=ScheduleModes.RESCHEDULE&&elapsedTimeoutTime<currentTime;if(notCompletedOrTimedOut){if(mode===ScheduleModes.RESCHEDULE){_this.run(callback,timeout,mode);}return undefined;}return callback();};}},{key:"cancel",value:function cancel(id){if(this.tasks[id]){this.clock.clearTimeout(this.tasks[id]);delete this.tasks[id];}}},{key:"cancelAll",value:function cancelAll(){Object.values(this.tasks).forEach(this.clock.clearTimeout);this.tasks={};}}]);return Schedule;}();
1256
+
1257
+ var RETRY_QUEUE_PROCESS_ERROR=function RETRY_QUEUE_PROCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Process function threw an error.");};var RETRY_QUEUE_ENTRY_REMOVE_ERROR=function RETRY_QUEUE_ENTRY_REMOVE_ERROR(context,entry,attempt){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to remove local storage entry \"").concat(entry,"\" (attempt: ").concat(attempt,".");};
1258
+
1259
+ var DEFAULT_MIN_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_BACKOFF_FACTOR=2;var DEFAULT_BACKOFF_JITTER=0;var DEFAULT_MAX_RETRY_ATTEMPTS=Infinity;var DEFAULT_MAX_ITEMS=Infinity;var DEFAULT_ACK_TIMER_MS=1000;var DEFAULT_RECLAIM_TIMER_MS=3000;var DEFAULT_RECLAIM_TIMEOUT_MS=10000;var DEFAULT_RECLAIM_WAIT_MS=500;var DEFAULT_MAX_BATCH_SIZE_BYTES=512*1024;// 512 KB; this is also the max size of a batch
1260
+ var DEFAULT_MAX_BATCH_ITEMS=100;var DEFAULT_BATCH_FLUSH_INTERVAL_MS=60*1000;// 1 minutes
1261
+
1262
+ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';/**
1263
+ * Constructs a RetryQueue backed by localStorage
1264
+ *
1265
+ * @constructor
1266
+ * @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
1267
+ * @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
1268
+ * @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue
1269
+ */var RetryQueue=/*#__PURE__*/function(){function RetryQueue(name,options,queueProcessCb,storeManager){var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;var queueBatchItemsSizeCalculatorCb=arguments.length>6?arguments[6]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.logger=logger;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.batchSizeCalcCb=queueBatchItemsSizeCalculatorCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=options.maxAttempts||DEFAULT_MAX_RETRY_ATTEMPTS;this.batch={enabled:false};this.configureBatchMode(options);this.backoff={minRetryDelay:options.minRetryDelay||DEFAULT_MIN_RETRY_DELAY_MS,maxRetryDelay:options.maxRetryDelay||DEFAULT_MAX_RETRY_DELAY_MS,factor:options.backoffFactor||DEFAULT_BACKOFF_FACTOR,jitter:options.backoffJitter||DEFAULT_BACKOFF_JITTER};// painstakingly tuned. that's why they're not "easily" configurable
1270
+ this.timeouts={ackTimer:DEFAULT_ACK_TIMER_MS,reclaimTimer:DEFAULT_RECLAIM_TIMER_MS,reclaimTimeout:DEFAULT_RECLAIM_TIMEOUT_MS,reclaimWait:DEFAULT_RECLAIM_WAIT_MS};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
1271
+ this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
1272
+ this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);// Attach visibility change listener to flush the queue
1273
+ this.attachListeners();this.scheduleTimeoutActive=false;}_createClass(RetryQueue,[{key:"setDefaultQueueEntries",value:function setDefaultQueueEntries(){this.setStorageEntry(QueueStatuses.IN_PROGRESS,{});this.setStorageEntry(QueueStatuses.QUEUE,[]);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);}},{key:"configureBatchMode",value:function configureBatchMode(options){this.batchingInProgress=false;if(!isObjectLiteralAndNotNull(options.batch)){return;}var batchOptions=options.batch;this.batch.enabled=batchOptions.enabled===true;if(this.batch.enabled){var _batchOptions$maxSize,_batchOptions$maxItem,_batchOptions$flushIn;// Set upper cap on the batch payload size
1274
+ this.batch.maxSize=Math.min((_batchOptions$maxSize=batchOptions.maxSize)!==null&&_batchOptions$maxSize!==void 0?_batchOptions$maxSize:DEFAULT_MAX_BATCH_SIZE_BYTES,DEFAULT_MAX_BATCH_SIZE_BYTES);this.batch.maxItems=(_batchOptions$maxItem=batchOptions.maxItems)!==null&&_batchOptions$maxItem!==void 0?_batchOptions$maxItem:DEFAULT_MAX_BATCH_ITEMS;this.batch.flushInterval=(_batchOptions$flushIn=batchOptions.flushInterval)!==null&&_batchOptions$flushIn!==void 0?_batchOptions$flushIn:DEFAULT_BATCH_FLUSH_INTERVAL_MS;}}},{key:"attachListeners",value:function attachListeners(){var _this=this;if(this.batch.enabled){globalThis.addEventListener('visibilitychange',function(){if(document.visibilityState==='hidden'){_this.flushBatch();}});}}},{key:"getStorageEntry",value:function getStorageEntry(name){return this.store.get(name!==null&&name!==void 0?name:this.name);}// TODO: fix the type of different queues to be the same if possible
1275
+ },{key:"setStorageEntry",value:function setStorageEntry(name,value){this.store.set(name!==null&&name!==void 0?name:this.name,value!==null&&value!==void 0?value:[]);}/**
1276
+ * Stops processing the queue
1277
+ */},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
1278
+ * Starts processing the queue
1279
+ */},{key:"start",value:function start(){if(this.scheduleTimeoutActive){this.stop();}this.scheduleTimeoutActive=true;this.scheduleFlushBatch();this.ack();this.checkReclaim();this.processHead();}/**
1280
+ * Configures the timeout handler for flushing the batch queue
1281
+ */},{key:"scheduleFlushBatch",value:function scheduleFlushBatch(){var _this$batch;if(this.batch.enabled&&(_this$batch=this.batch)!==null&&_this$batch!==void 0&&_this$batch.flushInterval){if(this.flushBatchTaskId){this.schedule.cancel(this.flushBatchTaskId);}this.flushBatchTaskId=this.schedule.run(this.flushBatch,this.batch.flushInterval,ScheduleModes.ASAP);}}/**
1282
+ * Flushes the batch queue
1283
+ */},{key:"flushBatch",value:function flushBatch(){if(!this.batchingInProgress){var _ref;this.batchingInProgress=true;var batchQueue=(_ref=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref!==void 0?_ref:[];if(batchQueue.length>0){batchQueue=batchQueue.slice(-batchQueue.length);var batchEntry=this.genQueueItem(batchQueue.map(function(queueItem){return queueItem.item;}));this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);this.pushToMainQueue(batchEntry);}this.batchingInProgress=false;// Re-schedule the flush task
1284
+ this.scheduleFlushBatch();}}/**
1285
+ * Decides whether to retry. Overridable.
1286
+ *
1287
+ * @param {Object} item The item being processed
1288
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1289
+ * @return {Boolean} Whether to requeue the message
1290
+ */},{key:"shouldRetry",value:function shouldRetry(item,attemptNumber){return attemptNumber<=this.maxAttempts;}/**
1291
+ * Calculates the delay (in ms) for a retry attempt
1292
+ *
1293
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1294
+ * @return {Number} The delay in milliseconds to wait before attempting a retry
1295
+ */},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.minRetryDelay*Math.pow(this.backoff.factor,attemptNumber);if(this.backoff.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.backoff.jitter*ms);if(Math.floor(rand*10)<5){ms-=deviation;}else {ms+=deviation;}}return Number(Math.min(ms,this.backoff.maxRetryDelay).toPrecision(1));}},{key:"enqueue",value:function enqueue(entry){var curEntry;if(this.batch.enabled){curEntry=this.handleNewItemForBatch(entry);}else {curEntry=entry;}// when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met
1296
+ if(curEntry){this.pushToMainQueue(curEntry);}}/**
1297
+ * Handles a new item added to the retry queue when batching is enabled
1298
+ * @param entry New item added to the retry queue
1299
+ * @returns Undefined or batch entry object
1300
+ */},{key:"handleNewItemForBatch",value:function handleNewItemForBatch(entry){var _ref2;var curEntry;var batchQueue=(_ref2=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref2!==void 0?_ref2:[];if(!this.batchingInProgress){this.batchingInProgress=true;batchQueue=batchQueue.slice(-batchQueue.length);batchQueue.push(entry);var batchDispatchInfo=this.getBatchDispInfo(batchQueue);// if batch criteria is met, queue the batch events to the main queue and clear batch queue
1301
+ if(batchDispatchInfo.criteriaMet||batchDispatchInfo.criteriaExceeded){var batchItems;if(batchDispatchInfo.criteriaExceeded){batchItems=batchQueue.slice(0,batchQueue.length-1).map(function(queueItem){return queueItem.item;});batchQueue=[entry];}else {batchItems=batchQueue.map(function(queueItem){return queueItem.item;});batchQueue=[];}// Don't make any batch request if there are no items
1302
+ if(batchItems.length>0){curEntry=this.genQueueItem(batchItems);}// re-attach the timeout handler
1303
+ this.scheduleFlushBatch();}this.batchingInProgress=false;}else {batchQueue.push(entry);}// update the batch queue
1304
+ this.setStorageEntry(QueueStatuses.BATCH_QUEUE,batchQueue);return curEntry;}},{key:"pushToMainQueue",value:function pushToMainQueue(curEntry){var _ref3;var queue=(_ref3=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref3!==void 0?_ref3:[];queue=queue.slice(-(this.maxItems-1));queue.push(curEntry);queue=queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}/**
1305
+ * Adds an item to the queue
1306
+ *
1307
+ * @param {Object} itemData The item to process
1308
+ */},{key:"addItem",value:function addItem(itemData){this.enqueue(this.genQueueItem(itemData));}/**
1309
+ * Generates a queue item
1310
+ * @param itemData Queue item data
1311
+ * @returns Queue item
1312
+ */},{key:"genQueueItem",value:function genQueueItem(itemData){return {item:itemData,attemptNumber:0,time:this.schedule.now(),id:generateUUID()};}/**
1313
+ * Adds an item to the retry queue
1314
+ *
1315
+ * @param {Object} itemData The item to retry
1316
+ * @param {Number} attemptNumber The attempt number (1 for first retry)
1317
+ * @param {Error} [error] The error from previous attempt, if there was one
1318
+ * @param {String} [id] The id of the queued message used for tracking duplicate entries
1319
+ */},{key:"requeue",value:function requeue(itemData,attemptNumber,error,id){if(this.shouldRetry(itemData,attemptNumber)){this.enqueue({item:itemData,attemptNumber:attemptNumber,time:this.schedule.now()+this.getDelay(attemptNumber),id:id!==null&&id!==void 0?id:generateUUID()});}}/**
1320
+ * Returns the information about whether the batch criteria is met or exceeded
1321
+ * @param batchItems Prospective batch items
1322
+ * @returns Batch dispatch info
1323
+ */},{key:"getBatchDispInfo",value:function getBatchDispInfo(batchItems){var _this$batch2,_this$batch3;var lengthCriteriaMet=false;var lengthCriteriaExceeded=false;var configuredBatchMaxItems=(_this$batch2=this.batch)===null||_this$batch2===void 0?void 0:_this$batch2.maxItems;if(isDefined(configuredBatchMaxItems)){lengthCriteriaMet=batchItems.length===configuredBatchMaxItems;lengthCriteriaExceeded=batchItems.length>configuredBatchMaxItems;}if(lengthCriteriaMet||lengthCriteriaExceeded){return {criteriaMet:lengthCriteriaMet,criteriaExceeded:lengthCriteriaExceeded};}var sizeCriteriaMet=false;var sizeCriteriaExceeded=false;var configuredBatchMaxSize=(_this$batch3=this.batch)===null||_this$batch3===void 0?void 0:_this$batch3.maxSize;if(isDefined(configuredBatchMaxSize)&&isDefined(this.batchSizeCalcCb)){var curBatchSize=this.batchSizeCalcCb(batchItems.map(function(queueItem){return queueItem.item;}));sizeCriteriaMet=curBatchSize===configuredBatchMaxSize;sizeCriteriaExceeded=curBatchSize>configuredBatchMaxSize;}return {criteriaMet:sizeCriteriaMet,criteriaExceeded:sizeCriteriaExceeded};}},{key:"processHead",value:function processHead(){var _ref4,_ref5,_this2=this,_ref7;// cancel the scheduled task if it exists
1324
+ this.schedule.cancel(this.processId);// Pop the head off the queue
1325
+ var queue=(_ref4=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref4!==void 0?_ref4:[];var inProgress=(_ref5=this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==void 0?_ref5:{};var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
1326
+ var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref6;var inProgress=(_ref6=_this2.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref6!==void 0?_ref6:{};delete inProgress[id];_this2.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);if(err){_this2.requeue(el.item,el.attemptNumber+1,err,el.id);}};};var enqueueItem=function enqueueItem(el,id){toRun.push({item:el.item,done:processItemCallback(el,id),attemptNumber:el.attemptNumber});};var inProgressSize=Object.keys(inProgress).length;// eslint-disable-next-line no-plusplus
1327
+ while(queue.length>0&&queue[0].time<=now&&inProgressSize++<this.maxItems){var el=queue.shift();if(el){var id=generateUUID();// Save this to the in progress map
1328
+ inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now()};enqueueItem(el,id);}}this.setStorageEntry(QueueStatuses.QUEUE,queue);this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
1329
+ try{var willBeRetried=_this2.shouldRetry(el.item,el.attemptNumber+1);_this2.processQueueCb(el.item,el.done,el.attemptNumber,_this2.maxAttempts,willBeRetried);}catch(err){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(RETRY_QUEUE_PROCESS_ERROR(RETRY_QUEUE),err);}});// re-read the queue in case the process function finished immediately or added another item
1330
+ queue=(_ref7=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref7!==void 0?_ref7:[];this.schedule.cancel(this.processId);if(queue.length>0){var nextProcessExecutionTime=queue[0].time-now;this.processId=this.schedule.run(this.processHead,nextProcessExecutionTime,ScheduleModes.ASAP);}}// Ack continuously to prevent other tabs from claiming our queue
1331
+ },{key:"ack",value:function ack(){this.setStorageEntry(QueueStatuses.ACK,this.schedule.now());this.setStorageEntry(QueueStatuses.RECLAIM_START,null);this.setStorageEntry(QueueStatuses.RECLAIM_END,null);this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getStorageEntry,_other$get,_other$get2,_other$get3,_this3=this;var other=this.storeManager.setStore({id:id,name:this.name,validKeys:QueueStatuses,type:LOCAL_STORAGE});var our={queue:(_this$getStorageEntry=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_this$getStorageEntry!==void 0?_this$getStorageEntry:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==void 0?_other$get:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==void 0?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==void 0?_other$get3:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var _el$id;var id=(_el$id=el.id)!==null&&_el$id!==void 0?_el$id:generateUUID();if(trackMessageIds.includes(id));else {our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this3.schedule.now(),id:id});trackMessageIds.push(id);}};if(Array.isArray(queue)){queue.forEach(concatIterator);}else if(queue){Object.values(queue).forEach(concatIterator);}};// add their queue to ours, resetting run-time to immediate and copying the attempt#
1332
+ addConcatQueue(their.queue,0);// Process batch queue items
1333
+ if(this.batch.enabled){their.batchQueue.forEach(function(el){var _el$id2;var id=(_el$id2=el.id)!==null&&_el$id2!==void 0?_el$id2:generateUUID();if(trackMessageIds.includes(id));else {_this3.enqueue(el);trackMessageIds.push(id);}});}else {// if batching is not enabled in the current instance, add those items to the main queue directly
1334
+ addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
1335
+ addConcatQueue(their.inProgress,1);our.queue=our.queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,our.queue);// remove all keys one by on next tick to avoid NS_ERROR_STORAGE_BUSY error
1336
+ this.clearQueueEntries(other,1);// process the new items we claimed
1337
+ this.processHead();}// eslint-disable-next-line class-methods-use-this
1338
+ },{key:"clearQueueEntries",value:function clearQueueEntries(other,localStorageBackoff){this.removeStorageEntry(other,0,localStorageBackoff);}},{key:"removeStorageEntry",value:function removeStorageEntry(store,entryIdx,backoff){var _this4=this;var attempt=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var maxAttempts=2;globalThis.setTimeout(function(){var queueEntryKeys=Object.keys(QueueStatuses);var entry=QueueStatuses[queueEntryKeys[entryIdx]];try{store.remove(entry);// clear the next entry
1339
+ if(entryIdx+1<queueEntryKeys.length){_this4.removeStorageEntry(store,entryIdx+1,backoff);}}catch(err){var storageBusyErr='NS_ERROR_STORAGE_BUSY';var isLocalStorageBusy=err.name===storageBusyErr||err.code===storageBusyErr||err.code===0x80630001;if(isLocalStorageBusy&&attempt<maxAttempts){// Try clearing the same entry again with some extra delay
1340
+ _this4.removeStorageEntry(store,entryIdx,backoff+40,attempt+1);}else {var _this4$logger;(_this4$logger=_this4.logger)===null||_this4$logger===void 0||_this4$logger.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE,entry,attempt),err);}// clear the next entry
1341
+ if(attempt===maxAttempts&&entryIdx+1<queueEntryKeys.length){_this4.removeStorageEntry(store,entryIdx+1,backoff);}}},backoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this5=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this5.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this5.id){return;}_this5.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this5.id){return;}store.set(QueueStatuses.RECLAIM_END,_this5.id);_this5.schedule.run(createReclaimStartTask(store),_this5.timeouts.reclaimWait,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this5.id);store.set(QueueStatuses.ACK,_this5.schedule.now());_this5.schedule.run(createReclaimEndTask(store),_this5.timeouts.reclaimWait,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storage=_this5.store.getOriginalEngine();for(var i=0;i<storage.length;i++){var k=storage.key(i);var parts=k?k.split('.'):[];if(parts.length!==3){// eslint-disable-next-line no-continue
1342
+ continue;}if(parts[0]!==name){// eslint-disable-next-line no-continue
1343
+ continue;}if(parts[2]!==QueueStatuses.ACK){// eslint-disable-next-line no-continue
1344
+ continue;}res.push(_this5.storeManager.setStore({id:parts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}return res;};findOtherQueues(this.name).forEach(function(store){if(store.id===_this5.id){return;}if(_this5.schedule.now()-store.get(QueueStatuses.ACK)<_this5.timeouts.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}},{key:"clear",value:function clear(){this.schedule.cancelAll();this.setDefaultQueueEntries();}}]);return RetryQueue;}();
1345
+
1346
+ var pluginName$e='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {name:pluginName$e,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$e]);},dataplaneEventsQueue:{/**
1347
+ * Initialize the queue for delivery
1348
+ * @param state Application state
1349
+ * @param httpClient http client instance
1350
+ * @param storeManager Store Manager instance
1351
+ * @param errorHandler Error handler instance
1352
+ * @param logger Logger instance
1353
+ * @returns BeaconItemsQueue instance
1354
+ */init:function init(state,httpClient,storeManager,errorHandler,logger){var _state$loadOptions$va;var writeKey=state.lifecycle.writeKey.value;var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl$1(dataplaneUrl,writeKey);var finalQOpts=getNormalizedBeaconQueueOptions((_state$loadOptions$va=state.loadOptions.value.beaconQueueOptions)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:{});var queueProcessCallback=function queueProcessCallback(itemData,done){logger===null||logger===void 0||logger.debug(BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(BEACON_QUEUE_PLUGIN));var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event);});var data=getBatchDeliveryPayload$1(finalEvents,logger);if(data){try{var isEnqueuedInBeacon=navigator.sendBeacon(url,data);if(!isEnqueuedInBeacon){logger===null||logger===void 0||logger.error(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN));}done(null,isEnqueuedInBeacon);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,BEACON_QUEUE_PLUGIN,BEACON_QUEUE_DELIVERY_ERROR(url));// Remove the item from queue
1355
+ done(null);}}else {// Mark the item as done so that it can be removed from the queue
1356
+ done(null);}};var eventsQueue=new RetryQueue("".concat(QUEUE_NAME$3,"_").concat(writeKey),{batch:{enabled:true,flushInterval:finalQOpts.flushQueueInterval,maxSize:MAX_BATCH_PAYLOAD_SIZE_BYTES,// set the hard limit
1357
+ maxItems:finalQOpts.maxItems}},queueProcessCallback,storeManager,LOCAL_STORAGE,logger,function(itemData){var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to Blob as we know that the event has already been validated prior to enqueue
1358
+ return getBatchDeliveryPayload$1(events,logger).size;});return eventsQueue;},/**
1359
+ * Add event to the queue for delivery
1360
+ * @param state Application state
1361
+ * @param eventsQueue IQueue instance
1362
+ * @param event RudderEvent object
1363
+ * @param errorHandler Error handler instance
1364
+ * @param logger Logger instance
1365
+ * @returns none
1366
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
1367
+ // It'll be updated to the latest timestamp during actual delivery
1368
+ event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);eventsQueue.addItem({event:event});}}};};
1369
+
1370
+ var BUGSNAG_API_KEY_VALIDATION_ERROR=function BUGSNAG_API_KEY_VALIDATION_ERROR(apiKey){return "The Bugsnag API key (".concat(apiKey,") is invalid or not provided.");};var BUGSNAG_SDK_LOAD_TIMEOUT_ERROR=function BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(timeout){return "A timeout ".concat(timeout," ms occurred while trying to load the Bugsnag SDK.");};var BUGSNAG_SDK_LOAD_ERROR=function BUGSNAG_SDK_LOAD_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the Bugsnag SDK.");};
1371
+
1372
+ var BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME='bugsnag';// For version 6 and below
1373
+ var BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME='Bugsnag';var GLOBAL_LIBRARY_OBJECT_NAMES=[BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME,BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];var BUGSNAG_CDN_URL='https://d2wy8f7a9ursnm.cloudfront.net/v6/bugsnag.min.js';var ERROR_REPORT_PROVIDER_NAME_BUGSNAG='rs-bugsnag';// This API key token is parsed in the CI pipeline
1374
+ var API_KEY='0d96a60df267f4a13f808bbaa54e535c';var BUGSNAG_VALID_MAJOR_VERSION='6';var SDK_LOAD_POLL_INTERVAL_MS=100;// ms
1375
+ var MAX_WAIT_FOR_SDK_LOAD_MS=100*SDK_LOAD_POLL_INTERVAL_MS;// ms
1376
+ // Errors from the below scripts are NOT allowed to reach Bugsnag
1377
+ var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
1378
+ ];};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1379
+ // Potential PII or sensitive data
1380
+ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
1381
+ 'eventBuffer',// pre-load event buffer (may contain PII)
1382
+ 'traits'];var BUGSNAG_PLUGIN='BugsnagPlugin';
1383
+
1384
+ var isValidVersion=function isValidVersion(globalLibInstance){var _globalLibInstance$_c;// For version 7
1385
+ // eslint-disable-next-line no-underscore-dangle
1386
+ var version=globalLibInstance===null||globalLibInstance===void 0||(_globalLibInstance$_c=globalLibInstance._client)===null||_globalLibInstance$_c===void 0||(_globalLibInstance$_c=_globalLibInstance$_c._notifier)===null||_globalLibInstance$_c===void 0?void 0:_globalLibInstance$_c.version;// For versions older than 7
1387
+ if(!version){var _tempInstance$notifie;var tempInstance=globalLibInstance({apiKey:API_KEY,releaseStage:'version-test',// eslint-disable-next-line func-names, object-shorthand
1388
+ beforeSend:function beforeSend(){return false;}});version=(_tempInstance$notifie=tempInstance.notifier)===null||_tempInstance$notifie===void 0?void 0:_tempInstance$notifie.version;}return version&&version.charAt(0)===BUGSNAG_VALID_MAJOR_VERSION;};var isRudderSDKError=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===void 0||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===void 0?void 0:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}// Prefix folder for all the destination SDK scripts
1389
+ var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var enhanceErrorEventMutator=function enhanceErrorEventMutator(event,metadataSource){event.updateMetaData('source',{metadataSource:metadataSource});var errorMessage=event.errorMessage;// eslint-disable-next-line no-param-reassign
1390
+ event.context=errorMessage;// Hack for easily grouping the script load errors
1391
+ // on the dashboard
1392
+ if(errorMessage.includes('error in script loading')){// eslint-disable-next-line no-param-reassign
1393
+ event.context='Script load failures';}// eslint-disable-next-line no-param-reassign
1394
+ event.severity='error';};var onError=function onError(state){var _state$source$value;var metadataSource=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id;return function(event){try{// Discard the event if it's not originated at the SDK
1395
+ if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event,metadataSource);return true;}catch(_unused){// Drop the error event if it couldn't be filtered as
1396
+ // it is most likely a non-SDK error
1397
+ return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'development';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'3.0.0-beta.14',// Set SDK version as the app version from build config
1398
+ metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
1399
+ collectUserIp:false,// collecting user's IP is disabled
1400
+ // enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
1401
+ maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage(),user:{id:state.lifecycle.writeKey.value},logger:logger,networkBreadcrumbsEnabled:false};var client=globalBugsnagLibInstance(clientConfig);return client;};var isApiKeyValid=function isApiKeyValid(apiKey){var isAPIKeyValid=!(apiKey.startsWith('{{')||apiKey.endsWith('}}')||apiKey.length===0);return isAPIKeyValid;};var loadBugsnagSDK=function loadBugsnagSDK(externalSrcLoader,logger){var isNotLoaded=GLOBAL_LIBRARY_OBJECT_NAMES.every(function(globalKeyName){return !globalThis[globalKeyName];});if(!isNotLoaded){return;}externalSrcLoader.loadJSFile({url:BUGSNAG_CDN_URL,id:ERROR_REPORT_PROVIDER_NAME_BUGSNAG,callback:function callback(id){if(!id){logger===null||logger===void 0||logger.error(BUGSNAG_SDK_LOAD_ERROR(BUGSNAG_PLUGIN));}}});};var initBugsnagClient=function initBugsnagClient(state,promiseResolve,promiseReject,logger){var time=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();if(typeof globalBugsnagLibInstance==='function'){if(isValidVersion(globalBugsnagLibInstance)){var client=getNewClient(state,logger);promiseResolve(client);}}else if(time>=MAX_WAIT_FOR_SDK_LOAD_MS){promiseReject(new Error(BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(MAX_WAIT_FOR_SDK_LOAD_MS)));}else {// Try to initialize the client after a delay
1402
+ globalThis.setTimeout(initBugsnagClient,SDK_LOAD_POLL_INTERVAL_MS,state,promiseResolve,promiseReject,logger,time+SDK_LOAD_POLL_INTERVAL_MS);}};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):undefined;};
1403
+
1404
+ var pluginName$d='Bugsnag';var Bugsnag=function Bugsnag(){return {name:pluginName$d,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$d]);},errorReportingProvider:{init:function init(state,externalSrcLoader,logger){return new Promise(function(resolve,reject){// If API key token is not parsed or invalid, don't proceed to initialize the client
1405
+ if(!isApiKeyValid(API_KEY)){reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));return;}loadBugsnagSDK(externalSrcLoader,logger);initBugsnagClient(state,resolve,reject,logger);});},notify:function notify(client,error,state,logger){client===null||client===void 0||client.notify(error,{metaData:{state:getAppStateForMetadata(state)}});},breadcrumb:function breadcrumb(client,message,logger){client===null||client===void 0||client.leaveBreadcrumb(message);}}};};
1406
+
1407
+ var CUSTOM_CONSENT_MANAGER_PLUGIN='CustomConsentManagerPlugin';
1408
+
1409
+ var DESTINATION_CONSENT_STATUS_ERROR$2="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1410
+
1411
+ var pluginName$c='CustomConsentManager';var CustomConsentManager=function CustomConsentManager(){return {name:pluginName$c,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$c]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1412
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// Nothing to update. Already provided by the user
1413
+ },isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var _cmpConfig$resolution;var consentManagement=destConfig.consentManagement;// If the destination does not have consent management config, events should be sent.
1414
+ if(!consentManagement){return true;}// Get the corresponding consents for the destination
1415
+ var cmpConfig=consentManagement.find(function(c){return c.provider===state.consents.provider.value;});// If there are no consents configured for the destination for the current provider, events should be sent.
1416
+ if(!(cmpConfig!==null&&cmpConfig!==void 0&&cmpConfig.consents)){return true;}var configuredConsents=cmpConfig.consents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});var resolutionStrategy=(_cmpConfig$resolution=cmpConfig.resolutionStrategy)!==null&&_cmpConfig$resolution!==void 0?_cmpConfig$resolution:state.consents.resolutionStrategy.value;// match the configured consents with user provided consents as per
1417
+ // the configured resolution strategy
1418
+ var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};switch(resolutionStrategy){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,CUSTOM_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$2);return true;}}}};};
1419
+
1420
+ var _CNameMapping$19;var DIR_NAME$19='AdobeAnalytics';var NAME$19='ADOBE_ANALYTICS';var DISPLAY_NAME$19='Adobe Analytics';_defineProperty({},DISPLAY_NAME$19,DIR_NAME$19);(_CNameMapping$19={'Adobe Analytics':NAME$19,ADOBEANALYTICS:NAME$19,'ADOBE ANALYTICS':NAME$19},_defineProperty(_CNameMapping$19,NAME$19,NAME$19),_defineProperty(_CNameMapping$19,"AdobeAnalytics",NAME$19),_defineProperty(_CNameMapping$19,"adobeanalytics",NAME$19),_defineProperty(_CNameMapping$19,'adobe analytics',NAME$19),_defineProperty(_CNameMapping$19,'Adobe analytics',NAME$19),_defineProperty(_CNameMapping$19,'adobe Analytics',NAME$19),_CNameMapping$19);
1421
+
1422
+ var _CNameMapping$18;var DIR_NAME$18='Amplitude';var NAME$18='AM';var DISPLAY_NAME$18='Amplitude';_defineProperty({},DISPLAY_NAME$18,DIR_NAME$18);(_CNameMapping$18={},_defineProperty(_CNameMapping$18,NAME$18,NAME$18),_defineProperty(_CNameMapping$18,"AMPLITUDE",NAME$18),_defineProperty(_CNameMapping$18,"Amplitude",NAME$18),_defineProperty(_CNameMapping$18,"am",NAME$18),_CNameMapping$18);
1423
+
1424
+ var _CNameMapping$17;var DIR_NAME$17='Appcues';var NAME$17='APPCUES';var DISPLAY_NAME$17='Appcues';_defineProperty({},DISPLAY_NAME$17,DIR_NAME$17);(_CNameMapping$17={},_defineProperty(_CNameMapping$17,NAME$17,NAME$17),_defineProperty(_CNameMapping$17,"Appcues",NAME$17),_defineProperty(_CNameMapping$17,'App Cues',NAME$17),_defineProperty(_CNameMapping$17,"appcues",NAME$17),_CNameMapping$17);
1425
+
1426
+ var _CNameMapping$16;var DIR_NAME$16='BingAds';var NAME$16='BINGADS';var DISPLAY_NAME$16='Bing Ads';_defineProperty({},DISPLAY_NAME$16,DIR_NAME$16);(_CNameMapping$16={},_defineProperty(_CNameMapping$16,NAME$16,NAME$16),_defineProperty(_CNameMapping$16,"BingAds",NAME$16),_defineProperty(_CNameMapping$16,"bingads",NAME$16),_defineProperty(_CNameMapping$16,'Bing Ads',NAME$16),_defineProperty(_CNameMapping$16,'Bing ads',NAME$16),_defineProperty(_CNameMapping$16,'bing Ads',NAME$16),_defineProperty(_CNameMapping$16,'bing ads',NAME$16),_CNameMapping$16);
1427
+
1428
+ var _CNameMapping$15;var DIR_NAME$15='Braze';var NAME$15='BRAZE';var DISPLAY_NAME$15='Braze';_defineProperty({},DISPLAY_NAME$15,DIR_NAME$15);(_CNameMapping$15={},_defineProperty(_CNameMapping$15,NAME$15,NAME$15),_defineProperty(_CNameMapping$15,"Braze",NAME$15),_defineProperty(_CNameMapping$15,"braze",NAME$15),_CNameMapping$15);
1429
+
1430
+ var _CNameMapping$14;var DIR_NAME$14='Bugsnag';var NAME$14='BUGSNAG';var DISPLAY_NAME$14='Bugsnag';_defineProperty({},DISPLAY_NAME$14,DIR_NAME$14);(_CNameMapping$14={},_defineProperty(_CNameMapping$14,NAME$14,NAME$14),_defineProperty(_CNameMapping$14,"bugsnag",NAME$14),_defineProperty(_CNameMapping$14,"Bugsnag",NAME$14),_CNameMapping$14);
1431
+
1432
+ var _CNameMapping$13;var DIR_NAME$13='Chartbeat';var NAME$13='CHARTBEAT';var DISPLAY_NAME$13='Chartbeat';_defineProperty({},DISPLAY_NAME$13,DIR_NAME$13);(_CNameMapping$13={},_defineProperty(_CNameMapping$13,NAME$13,NAME$13),_defineProperty(_CNameMapping$13,"Chartbeat",NAME$13),_defineProperty(_CNameMapping$13,"chartbeat",NAME$13),_defineProperty(_CNameMapping$13,'Chart Beat',NAME$13),_defineProperty(_CNameMapping$13,'chart beat',NAME$13),_CNameMapping$13);
1433
+
1434
+ var _CNameMapping$12;var DIR_NAME$12='Clevertap';var NAME$12='CLEVERTAP';var DISPLAY_NAME$12='CleverTap';_defineProperty({},DISPLAY_NAME$12,DIR_NAME$12);(_CNameMapping$12={},_defineProperty(_CNameMapping$12,NAME$12,NAME$12),_defineProperty(_CNameMapping$12,"Clevertap",NAME$12),_defineProperty(_CNameMapping$12,"clevertap",NAME$12),_CNameMapping$12);
1435
+
1436
+ var _CNameMapping$11;var DIR_NAME$11='Comscore';var NAME$11='COMSCORE';var DISPLAY_NAME$11='Comscore';_defineProperty({},DISPLAY_NAME$11,DIR_NAME$11);(_CNameMapping$11={},_defineProperty(_CNameMapping$11,NAME$11,NAME$11),_defineProperty(_CNameMapping$11,"Comscore",NAME$11),_defineProperty(_CNameMapping$11,'Com Score',NAME$11),_defineProperty(_CNameMapping$11,'com Score',NAME$11),_defineProperty(_CNameMapping$11,'com score',NAME$11),_defineProperty(_CNameMapping$11,'Com score',NAME$11),_CNameMapping$11);
1437
+
1438
+ var _CNameMapping$10;var DIR_NAME$10='Criteo';var NAME$10='CRITEO';var DISPLAY_NAME$10='Criteo';_defineProperty({},DISPLAY_NAME$10,DIR_NAME$10);(_CNameMapping$10={},_defineProperty(_CNameMapping$10,NAME$10,NAME$10),_defineProperty(_CNameMapping$10,"Criteo",NAME$10),_defineProperty(_CNameMapping$10,"criteo",NAME$10),_CNameMapping$10);
1439
+
1440
+ var _CNameMapping$$;var DIR_NAME$$='CustomerIO';var NAME$$='CUSTOMERIO';var DISPLAY_NAME$$='Customer IO';_defineProperty({},DISPLAY_NAME$$,DIR_NAME$$);(_CNameMapping$$={},_defineProperty(_CNameMapping$$,NAME$$,NAME$$),_defineProperty(_CNameMapping$$,"Customerio",NAME$$),_defineProperty(_CNameMapping$$,'Customer.io',NAME$$),_defineProperty(_CNameMapping$$,'CUSTOMER.IO',NAME$$),_defineProperty(_CNameMapping$$,'customer.io',NAME$$),_CNameMapping$$);
1441
+
1442
+ var _CNameMapping$_;var DIR_NAME$_='Drip';var NAME$_='DRIP';var DISPLAY_NAME$_='Drip';_defineProperty({},DISPLAY_NAME$_,DIR_NAME$_);(_CNameMapping$_={},_defineProperty(_CNameMapping$_,NAME$_,NAME$_),_defineProperty(_CNameMapping$_,"Drip",NAME$_),_defineProperty(_CNameMapping$_,"drip",NAME$_),_CNameMapping$_);
1443
+
1444
+ var _CNameMapping$Z;var DIR_NAME$Z='FacebookPixel';var NAME$Z='FACEBOOK_PIXEL';var DISPLAY_NAME$Z='Facebook Pixel';_defineProperty({},DISPLAY_NAME$Z,DIR_NAME$Z);(_CNameMapping$Z={},_defineProperty(_CNameMapping$Z,NAME$Z,NAME$Z),_defineProperty(_CNameMapping$Z,'FB Pixel',NAME$Z),_defineProperty(_CNameMapping$Z,'Facebook Pixel',NAME$Z),_defineProperty(_CNameMapping$Z,'facebook pixel',NAME$Z),_defineProperty(_CNameMapping$Z,"fbpixel",NAME$Z),_defineProperty(_CNameMapping$Z,"FBPIXEL",NAME$Z),_defineProperty(_CNameMapping$Z,"FB_PIXEL",NAME$Z),_CNameMapping$Z);
1445
+
1446
+ var _CNameMapping$Y;var DIR_NAME$Y='Fullstory';var NAME$Y='FULLSTORY';var DISPLAY_NAME$Y='Fullstory';_defineProperty({},DISPLAY_NAME$Y,DIR_NAME$Y);(_CNameMapping$Y={},_defineProperty(_CNameMapping$Y,NAME$Y,NAME$Y),_defineProperty(_CNameMapping$Y,"Fullstory",NAME$Y),_defineProperty(_CNameMapping$Y,"FullStory",NAME$Y),_defineProperty(_CNameMapping$Y,'full Story',NAME$Y),_defineProperty(_CNameMapping$Y,'Full Story',NAME$Y),_defineProperty(_CNameMapping$Y,'Full story',NAME$Y),_defineProperty(_CNameMapping$Y,'full story',NAME$Y),_defineProperty(_CNameMapping$Y,"fullstory",NAME$Y),_CNameMapping$Y);
1447
+
1448
+ var _CNameMapping$X;var DIR_NAME$X='GA';var NAME$X='GA';var DISPLAY_NAME$X='Google Analytics';_defineProperty({},DISPLAY_NAME$X,DIR_NAME$X);(_CNameMapping$X={},_defineProperty(_CNameMapping$X,NAME$X,NAME$X),_defineProperty(_CNameMapping$X,'Google Analytics',NAME$X),_defineProperty(_CNameMapping$X,"GoogleAnalytics",NAME$X),_defineProperty(_CNameMapping$X,'GOOGLE ANALYTICS',NAME$X),_defineProperty(_CNameMapping$X,'google analytics',NAME$X),_CNameMapping$X);
1449
+
1450
+ var _CNameMapping$W;var DIR_NAME$W='GA4';var NAME$W='GA4';var DISPLAY_NAME$W='Google Analytics 4 (GA4)';_defineProperty({},DISPLAY_NAME$W,DIR_NAME$W);(_CNameMapping$W={},_defineProperty(_CNameMapping$W,NAME$W,NAME$W),_defineProperty(_CNameMapping$W,'Google Analytics 4',NAME$W),_defineProperty(_CNameMapping$W,'Google analytics 4',NAME$W),_defineProperty(_CNameMapping$W,'google analytics 4',NAME$W),_defineProperty(_CNameMapping$W,'Google Analytics4',NAME$W),_defineProperty(_CNameMapping$W,'Google analytics4',NAME$W),_defineProperty(_CNameMapping$W,'google analytics4',NAME$W),_defineProperty(_CNameMapping$W,'Google Analytics 4 (GA4)',NAME$W),_defineProperty(_CNameMapping$W,'google analytics 4 (ga4)',NAME$W),_defineProperty(_CNameMapping$W,"GoogleAnalytics4",NAME$W),_CNameMapping$W);
1451
+
1452
+ var _CNameMapping$V;var DIR_NAME$V='GoogleAds';var NAME$V='GOOGLEADS';var DISPLAY_NAME$V='Google Ads';_defineProperty({},DISPLAY_NAME$V,DIR_NAME$V);(_CNameMapping$V={},_defineProperty(_CNameMapping$V,NAME$V,NAME$V),_defineProperty(_CNameMapping$V,'Google Ads',NAME$V),_defineProperty(_CNameMapping$V,"GoogleAds",NAME$V),_defineProperty(_CNameMapping$V,'GOOGLE ADS',NAME$V),_defineProperty(_CNameMapping$V,'google ads',NAME$V),_defineProperty(_CNameMapping$V,"googleads",NAME$V),_CNameMapping$V);
1453
+
1454
+ var _CNameMapping$U;var DIR_NAME$U='GoogleOptimize';var NAME$U='GOOGLE_OPTIMIZE';var DISPLAY_NAME$U='Google Optimize';_defineProperty({},DISPLAY_NAME$U,DIR_NAME$U);(_CNameMapping$U={},_defineProperty(_CNameMapping$U,NAME$U,NAME$U),_defineProperty(_CNameMapping$U,'Google Optimize',NAME$U),_defineProperty(_CNameMapping$U,"GoogleOptimize",NAME$U),_defineProperty(_CNameMapping$U,"Googleoptimize",NAME$U),_defineProperty(_CNameMapping$U,"GOOGLEOPTIMIZE",NAME$U),_defineProperty(_CNameMapping$U,'google optimize',NAME$U),_defineProperty(_CNameMapping$U,'Google optimize',NAME$U),_defineProperty(_CNameMapping$U,'GOOGLE OPTIMIZE',NAME$U),_CNameMapping$U);
1455
+
1456
+ var _CNameMapping$T;var DIR_NAME$T='GoogleTagManager';var NAME$T='GTM';var DISPLAY_NAME$T='Google Tag Manager';_defineProperty({},DISPLAY_NAME$T,DIR_NAME$T);(_CNameMapping$T={},_defineProperty(_CNameMapping$T,NAME$T,NAME$T),_defineProperty(_CNameMapping$T,'Google Tag Manager',NAME$T),_defineProperty(_CNameMapping$T,'google tag manager',NAME$T),_defineProperty(_CNameMapping$T,'googletag manager',NAME$T),_defineProperty(_CNameMapping$T,"googletagmanager",NAME$T),_CNameMapping$T);
1457
+
1458
+ var _CNameMapping$S;var DIR_NAME$S='Heap';var NAME$S='HEAP';var DISPLAY_NAME$S='Heap.io';_defineProperty({},DISPLAY_NAME$S,DIR_NAME$S);(_CNameMapping$S={},_defineProperty(_CNameMapping$S,NAME$S,NAME$S),_defineProperty(_CNameMapping$S,"Heap",NAME$S),_defineProperty(_CNameMapping$S,"heap",NAME$S),_defineProperty(_CNameMapping$S,'Heap.io',NAME$S),_CNameMapping$S);
1459
+
1460
+ var _CNameMapping$R;var DIR_NAME$R='Hotjar';var NAME$R='HOTJAR';var DISPLAY_NAME$R='Hotjar';_defineProperty({},DISPLAY_NAME$R,DIR_NAME$R);(_CNameMapping$R={},_defineProperty(_CNameMapping$R,NAME$R,NAME$R),_defineProperty(_CNameMapping$R,"Hotjar",NAME$R),_defineProperty(_CNameMapping$R,"hotjar",NAME$R),_defineProperty(_CNameMapping$R,'Hot Jar',NAME$R),_defineProperty(_CNameMapping$R,'hot jar',NAME$R),_CNameMapping$R);
1461
+
1462
+ var _CNameMapping$Q;var DIR_NAME$Q='HubSpot';var NAME$Q='HS';var DISPLAY_NAME$Q='HubSpot';_defineProperty({},DISPLAY_NAME$Q,DIR_NAME$Q);(_CNameMapping$Q={},_defineProperty(_CNameMapping$Q,NAME$Q,NAME$Q),_defineProperty(_CNameMapping$Q,"Hubspot",NAME$Q),_defineProperty(_CNameMapping$Q,"HUBSPOT",NAME$Q),_defineProperty(_CNameMapping$Q,'hub spot',NAME$Q),_defineProperty(_CNameMapping$Q,'Hub Spot',NAME$Q),_defineProperty(_CNameMapping$Q,'Hub spot',NAME$Q),_CNameMapping$Q);
1463
+
1464
+ var _CNameMapping$P;var DIR_NAME$P='INTERCOM';var NAME$P='INTERCOM';var DISPLAY_NAME$P='Intercom';_defineProperty({},DISPLAY_NAME$P,DIR_NAME$P);(_CNameMapping$P={},_defineProperty(_CNameMapping$P,NAME$P,NAME$P),_defineProperty(_CNameMapping$P,"Intercom",NAME$P),_defineProperty(_CNameMapping$P,"intercom",NAME$P),_CNameMapping$P);
1465
+
1466
+ var _CNameMapping$O;var DIR_NAME$O='Keen';var NAME$O='KEEN';var DISPLAY_NAME$O='Keen';_defineProperty({},DISPLAY_NAME$O,DIR_NAME$O);(_CNameMapping$O={},_defineProperty(_CNameMapping$O,NAME$O,NAME$O),_defineProperty(_CNameMapping$O,"Keen",NAME$O),_defineProperty(_CNameMapping$O,'Keen.io',NAME$O),_defineProperty(_CNameMapping$O,"keen",NAME$O),_defineProperty(_CNameMapping$O,'keen.io',NAME$O),_CNameMapping$O);
1467
+
1468
+ var _CNameMapping$N;var DIR_NAME$N='Kissmetrics';var NAME$N='KISSMETRICS';var DISPLAY_NAME$N='Kiss Metrics';_defineProperty({},DISPLAY_NAME$N,DIR_NAME$N);(_CNameMapping$N={},_defineProperty(_CNameMapping$N,NAME$N,NAME$N),_defineProperty(_CNameMapping$N,"Kissmetrics",NAME$N),_defineProperty(_CNameMapping$N,"kissmetrics",NAME$N),_CNameMapping$N);
1469
+
1470
+ var _CNameMapping$M;var DIR_NAME$M='Klaviyo';var NAME$M='KLAVIYO';var DISPLAY_NAME$M='Klaviyo';_defineProperty({},DISPLAY_NAME$M,DIR_NAME$M);(_CNameMapping$M={},_defineProperty(_CNameMapping$M,NAME$M,NAME$M),_defineProperty(_CNameMapping$M,"Klaviyo",NAME$M),_defineProperty(_CNameMapping$M,"klaviyo",NAME$M),_CNameMapping$M);
1471
+
1472
+ var _CNameMapping$L;var DIR_NAME$L='LaunchDarkly';var NAME$L='LAUNCHDARKLY';var DISPLAY_NAME$L='LaunchDarkly';_defineProperty({},DISPLAY_NAME$L,DIR_NAME$L);(_CNameMapping$L={},_defineProperty(_CNameMapping$L,NAME$L,NAME$L),_defineProperty(_CNameMapping$L,"LaunchDarkly",NAME$L),_defineProperty(_CNameMapping$L,"Launch_Darkly",NAME$L),_defineProperty(_CNameMapping$L,'Launch Darkly',NAME$L),_defineProperty(_CNameMapping$L,"launchDarkly",NAME$L),_defineProperty(_CNameMapping$L,'launch darkly',NAME$L),_CNameMapping$L);
1473
+
1474
+ var _CNameMapping$K;var DIR_NAME$K='LinkedInInsightTag';var NAME$K='LINKEDIN_INSIGHT_TAG';var DISPLAY_NAME$K='Linkedin Insight Tag';_defineProperty({},DISPLAY_NAME$K,DIR_NAME$K);(_CNameMapping$K={},_defineProperty(_CNameMapping$K,NAME$K,NAME$K),_defineProperty(_CNameMapping$K,'LinkedIn Insight Tag',NAME$K),_defineProperty(_CNameMapping$K,'LinkedIn insight tag',NAME$K),_defineProperty(_CNameMapping$K,'linkedIn insight tag',NAME$K),_defineProperty(_CNameMapping$K,"Linkedin_insight_tag",NAME$K),_defineProperty(_CNameMapping$K,"LinkedinInsighttag",NAME$K),_defineProperty(_CNameMapping$K,"LinkedinInsightTag",NAME$K),_defineProperty(_CNameMapping$K,"LinkedInInsightTag",NAME$K),_defineProperty(_CNameMapping$K,"Linkedininsighttag",NAME$K),_defineProperty(_CNameMapping$K,"LINKEDININSIGHTTAG",NAME$K),_defineProperty(_CNameMapping$K,"linkedininsighttag",NAME$K),_CNameMapping$K);
1475
+
1476
+ var _CNameMapping$J;var DIR_NAME$J='Lotame';var NAME$J='LOTAME';var DISPLAY_NAME$J='Lotame';_defineProperty({},DISPLAY_NAME$J,DIR_NAME$J);(_CNameMapping$J={},_defineProperty(_CNameMapping$J,NAME$J,NAME$J),_defineProperty(_CNameMapping$J,"Lotame",NAME$J),_defineProperty(_CNameMapping$J,"lotame",NAME$J),_CNameMapping$J);
1477
+
1478
+ var _CNameMapping$I;var DIR_NAME$I='Lytics';var NAME$I='LYTICS';var DISPLAY_NAME$I='Lytics';_defineProperty({},DISPLAY_NAME$I,DIR_NAME$I);(_CNameMapping$I={},_defineProperty(_CNameMapping$I,NAME$I,NAME$I),_defineProperty(_CNameMapping$I,"Lytics",NAME$I),_defineProperty(_CNameMapping$I,"lytics",NAME$I),_CNameMapping$I);
1479
+
1480
+ var _CNameMapping$H;var DIR_NAME$H='Mixpanel';var NAME$H='MP';var DISPLAY_NAME$H='Mixpanel';_defineProperty({},DISPLAY_NAME$H,DIR_NAME$H);(_CNameMapping$H={},_defineProperty(_CNameMapping$H,NAME$H,NAME$H),_defineProperty(_CNameMapping$H,"MIXPANEL",NAME$H),_defineProperty(_CNameMapping$H,"Mixpanel",NAME$H),_defineProperty(_CNameMapping$H,'MIX PANEL',NAME$H),_defineProperty(_CNameMapping$H,'Mix panel',NAME$H),_defineProperty(_CNameMapping$H,'Mix Panel',NAME$H),_CNameMapping$H);
1481
+
1482
+ var _CNameMapping$G;var DIR_NAME$G='MoEngage';var NAME$G='MOENGAGE';var DISPLAY_NAME$G='MoEngage';_defineProperty({},DISPLAY_NAME$G,DIR_NAME$G);(_CNameMapping$G={},_defineProperty(_CNameMapping$G,NAME$G,NAME$G),_defineProperty(_CNameMapping$G,"MoEngage",NAME$G),_defineProperty(_CNameMapping$G,"moengage",NAME$G),_defineProperty(_CNameMapping$G,"Moengage",NAME$G),_defineProperty(_CNameMapping$G,'Mo Engage',NAME$G),_defineProperty(_CNameMapping$G,'mo engage',NAME$G),_defineProperty(_CNameMapping$G,'Mo engage',NAME$G),_CNameMapping$G);
1483
+
1484
+ var _CNameMapping$F;var DIR_NAME$F='Optimizely';var NAME$F='OPTIMIZELY';var DISPLAY_NAME$F='Optimizely Web';_defineProperty({},DISPLAY_NAME$F,DIR_NAME$F);(_CNameMapping$F={},_defineProperty(_CNameMapping$F,NAME$F,NAME$F),_defineProperty(_CNameMapping$F,"Optimizely",NAME$F),_defineProperty(_CNameMapping$F,"optimizely",NAME$F),_CNameMapping$F);
1485
+
1486
+ var _CNameMapping$E;var DIR_NAME$E='Pendo';var NAME$E='PENDO';var DISPLAY_NAME$E='Pendo';_defineProperty({},DISPLAY_NAME$E,DIR_NAME$E);(_CNameMapping$E={},_defineProperty(_CNameMapping$E,NAME$E,NAME$E),_defineProperty(_CNameMapping$E,"Pendo",NAME$E),_defineProperty(_CNameMapping$E,"pendo",NAME$E),_CNameMapping$E);
1487
+
1488
+ var _CNameMapping$D;var DIR_NAME$D='PinterestTag';var NAME$D='PINTEREST_TAG';var DISPLAY_NAME$D='Pinterest Tag';_defineProperty({},DISPLAY_NAME$D,DIR_NAME$D);(_CNameMapping$D={},_defineProperty(_CNameMapping$D,NAME$D,NAME$D),_defineProperty(_CNameMapping$D,"PinterestTag",NAME$D),_defineProperty(_CNameMapping$D,"Pinterest_Tag",NAME$D),_defineProperty(_CNameMapping$D,"PINTERESTTAG",NAME$D),_defineProperty(_CNameMapping$D,"pinterest",NAME$D),_defineProperty(_CNameMapping$D,"PinterestAds",NAME$D),_defineProperty(_CNameMapping$D,"Pinterest_Ads",NAME$D),_defineProperty(_CNameMapping$D,"Pinterest",NAME$D),_defineProperty(_CNameMapping$D,'Pinterest Tag',NAME$D),_defineProperty(_CNameMapping$D,'Pinterest tag',NAME$D),_defineProperty(_CNameMapping$D,'PINTEREST TAG',NAME$D),_defineProperty(_CNameMapping$D,'pinterest tag',NAME$D),_defineProperty(_CNameMapping$D,'Pinterest Ads',NAME$D),_defineProperty(_CNameMapping$D,'Pinterest ads',NAME$D),_CNameMapping$D);
1489
+
1490
+ var _CNameMapping$C;var DIR_NAME$C='PostAffiliatePro';var NAME$C='POST_AFFILIATE_PRO';var DISPLAY_NAME$C='Post Affiliate Pro';_defineProperty({},DISPLAY_NAME$C,DIR_NAME$C);(_CNameMapping$C={},_defineProperty(_CNameMapping$C,NAME$C,NAME$C),_defineProperty(_CNameMapping$C,"PostAffiliatePro",NAME$C),_defineProperty(_CNameMapping$C,"Post_affiliate_pro",NAME$C),_defineProperty(_CNameMapping$C,'Post Affiliate Pro',NAME$C),_defineProperty(_CNameMapping$C,'Post affiliate pro',NAME$C),_defineProperty(_CNameMapping$C,'post affiliate pro',NAME$C),_defineProperty(_CNameMapping$C,"postaffiliatepro",NAME$C),_defineProperty(_CNameMapping$C,"POSTAFFILIATEPRO",NAME$C),_CNameMapping$C);
1491
+
1492
+ var _CNameMapping$B;var DIR_NAME$B='Posthog';var NAME$B='POSTHOG';var DISPLAY_NAME$B='PostHog';_defineProperty({},DISPLAY_NAME$B,DIR_NAME$B);(_CNameMapping$B={},_defineProperty(_CNameMapping$B,NAME$B,NAME$B),_defineProperty(_CNameMapping$B,"PostHog",NAME$B),_defineProperty(_CNameMapping$B,"Posthog",NAME$B),_defineProperty(_CNameMapping$B,"posthog",NAME$B),_defineProperty(_CNameMapping$B,'Post Hog',NAME$B),_defineProperty(_CNameMapping$B,'Post hog',NAME$B),_defineProperty(_CNameMapping$B,'post hog',NAME$B),_CNameMapping$B);
1493
+
1494
+ var _CNameMapping$A;var DIR_NAME$A='ProfitWell';var NAME$A='PROFITWELL';var DISPLAY_NAME$A='ProfitWell';_defineProperty({},DISPLAY_NAME$A,DIR_NAME$A);(_CNameMapping$A={},_defineProperty(_CNameMapping$A,NAME$A,NAME$A),_defineProperty(_CNameMapping$A,"ProfitWell",NAME$A),_defineProperty(_CNameMapping$A,"profitwell",NAME$A),_defineProperty(_CNameMapping$A,"Profitwell",NAME$A),_defineProperty(_CNameMapping$A,'Profit Well',NAME$A),_defineProperty(_CNameMapping$A,'profit well',NAME$A),_defineProperty(_CNameMapping$A,'Profit well',NAME$A),_CNameMapping$A);
1495
+
1496
+ var _CNameMapping$z;var DIR_NAME$z='Qualtrics';var NAME$z='QUALTRICS';var DISPLAY_NAME$z='Qualtrics';_defineProperty({},DISPLAY_NAME$z,DIR_NAME$z);(_CNameMapping$z={},_defineProperty(_CNameMapping$z,NAME$z,NAME$z),_defineProperty(_CNameMapping$z,"Qualtrics",NAME$z),_defineProperty(_CNameMapping$z,"qualtrics",NAME$z),_CNameMapping$z);
1497
+
1498
+ var _CNameMapping$y;var DIR_NAME$y='QuantumMetric';var NAME$y='QUANTUMMETRIC';var DISPLAY_NAME$y='Quantum Metric';_defineProperty({},DISPLAY_NAME$y,DIR_NAME$y);(_CNameMapping$y={},_defineProperty(_CNameMapping$y,NAME$y,NAME$y),_defineProperty(_CNameMapping$y,'Quantum Metric',NAME$y),_defineProperty(_CNameMapping$y,'quantum Metric',NAME$y),_defineProperty(_CNameMapping$y,'quantum metric',NAME$y),_defineProperty(_CNameMapping$y,"QuantumMetric",NAME$y),_defineProperty(_CNameMapping$y,"quantumMetric",NAME$y),_defineProperty(_CNameMapping$y,"quantummetric",NAME$y),_defineProperty(_CNameMapping$y,"Quantum_Metric",NAME$y),_CNameMapping$y);
1499
+
1500
+ var _CNameMapping$x;var DIR_NAME$x='RedditPixel';var NAME$x='REDDIT_PIXEL';var DISPLAY_NAME$x='Reddit Pixel';_defineProperty({},DISPLAY_NAME$x,DIR_NAME$x);(_CNameMapping$x={},_defineProperty(_CNameMapping$x,NAME$x,NAME$x),_defineProperty(_CNameMapping$x,"Reddit_Pixel",NAME$x),_defineProperty(_CNameMapping$x,"RedditPixel",NAME$x),_defineProperty(_CNameMapping$x,"REDDITPIXEL",NAME$x),_defineProperty(_CNameMapping$x,"redditpixel",NAME$x),_defineProperty(_CNameMapping$x,'Reddit Pixel',NAME$x),_defineProperty(_CNameMapping$x,'REDDIT PIXEL',NAME$x),_defineProperty(_CNameMapping$x,'reddit pixel',NAME$x),_CNameMapping$x);
1501
+
1502
+ var _CNameMapping$w;var DIR_NAME$w='Sentry';var NAME$w='SENTRY';var DISPLAY_NAME$w='Sentry';_defineProperty({},DISPLAY_NAME$w,DIR_NAME$w);(_CNameMapping$w={},_defineProperty(_CNameMapping$w,NAME$w,NAME$w),_defineProperty(_CNameMapping$w,"sentry",NAME$w),_defineProperty(_CNameMapping$w,"Sentry",NAME$w),_CNameMapping$w);
1503
+
1504
+ var _CNameMapping$v;var DIR_NAME$v='SnapPixel';var NAME$v='SNAP_PIXEL';var DISPLAY_NAME$v='Snap Pixel';_defineProperty({},DISPLAY_NAME$v,DIR_NAME$v);(_CNameMapping$v={},_defineProperty(_CNameMapping$v,NAME$v,NAME$v),_defineProperty(_CNameMapping$v,"Snap_Pixel",NAME$v),_defineProperty(_CNameMapping$v,"SnapPixel",NAME$v),_defineProperty(_CNameMapping$v,"SNAPPIXEL",NAME$v),_defineProperty(_CNameMapping$v,"snappixel",NAME$v),_defineProperty(_CNameMapping$v,'Snap Pixel',NAME$v),_defineProperty(_CNameMapping$v,'SNAP PIXEL',NAME$v),_defineProperty(_CNameMapping$v,'snap pixel',NAME$v),_CNameMapping$v);
1505
+
1506
+ var _CNameMapping$u;var DIR_NAME$u='TVSquared';var NAME$u='TVSQUARED';var DISPLAY_NAME$u='TVSquared';_defineProperty({},DISPLAY_NAME$u,DIR_NAME$u);(_CNameMapping$u={},_defineProperty(_CNameMapping$u,NAME$u,NAME$u),_defineProperty(_CNameMapping$u,"TVSquared",NAME$u),_defineProperty(_CNameMapping$u,"tvsquared",NAME$u),_defineProperty(_CNameMapping$u,"tvSquared",NAME$u),_defineProperty(_CNameMapping$u,"TvSquared",NAME$u),_defineProperty(_CNameMapping$u,"Tvsquared",NAME$u),_defineProperty(_CNameMapping$u,'TV Squared',NAME$u),_defineProperty(_CNameMapping$u,'tv squared',NAME$u),_defineProperty(_CNameMapping$u,'tv Squared',NAME$u),_CNameMapping$u);
1507
+
1508
+ var _CNameMapping$t;var DIR_NAME$t='VWO';var NAME$t='VWO';var DISPLAY_NAME$t='VWO';_defineProperty({},DISPLAY_NAME$t,DIR_NAME$t);(_CNameMapping$t={},_defineProperty(_CNameMapping$t,NAME$t,NAME$t),_defineProperty(_CNameMapping$t,"VisualWebsiteOptimizer",NAME$t),_defineProperty(_CNameMapping$t,"Visualwebsiteoptimizer",NAME$t),_defineProperty(_CNameMapping$t,"visualwebsiteoptimizer",NAME$t),_defineProperty(_CNameMapping$t,"vwo",NAME$t),_defineProperty(_CNameMapping$t,'Visual Website Optimizer',NAME$t),_defineProperty(_CNameMapping$t,'Visual website optimizer',NAME$t),_defineProperty(_CNameMapping$t,'visual website optimizer',NAME$t),_CNameMapping$t);
1509
+
1510
+ var _CNameMapping$s;var DIR_NAME$s='GA360';var NAME$s='GA360';var DISPLAY_NAME$s='Google Analytics 360';_defineProperty({},DISPLAY_NAME$s,DIR_NAME$s);(_CNameMapping$s={},_defineProperty(_CNameMapping$s,NAME$s,NAME$s),_defineProperty(_CNameMapping$s,'Google Analytics 360',NAME$s),_defineProperty(_CNameMapping$s,'Google analytics 360',NAME$s),_defineProperty(_CNameMapping$s,'google analytics 360',NAME$s),_defineProperty(_CNameMapping$s,'Google Analytics360',NAME$s),_defineProperty(_CNameMapping$s,'Google analytics360',NAME$s),_defineProperty(_CNameMapping$s,'google analytics360',NAME$s),_defineProperty(_CNameMapping$s,"GoogleAnalytics360",NAME$s),_defineProperty(_CNameMapping$s,'GA 360',NAME$s),_CNameMapping$s);
1511
+
1512
+ var _CNameMapping$r;var DIR_NAME$r='Adroll';var NAME$r='ADROLL';var DISPLAY_NAME$r='Adroll';_defineProperty({},DISPLAY_NAME$r,DIR_NAME$r);(_CNameMapping$r={},_defineProperty(_CNameMapping$r,NAME$r,NAME$r),_defineProperty(_CNameMapping$r,"Adroll",NAME$r),_defineProperty(_CNameMapping$r,'Ad roll',NAME$r),_defineProperty(_CNameMapping$r,'ad roll',NAME$r),_defineProperty(_CNameMapping$r,"adroll",NAME$r),_CNameMapping$r);
1513
+
1514
+ var _CNameMapping$q;var DIR_NAME$q='DCMFloodlight';var NAME$q='DCM_FLOODLIGHT';var DISPLAY_NAME$q='DCM Floodlight';_defineProperty({},DISPLAY_NAME$q,DIR_NAME$q);(_CNameMapping$q={},_defineProperty(_CNameMapping$q,NAME$q,NAME$q),_defineProperty(_CNameMapping$q,'DCM Floodlight',NAME$q),_defineProperty(_CNameMapping$q,'dcm floodlight',NAME$q),_defineProperty(_CNameMapping$q,'Dcm Floodlight',NAME$q),_defineProperty(_CNameMapping$q,"DCMFloodlight",NAME$q),_defineProperty(_CNameMapping$q,"dcmfloodlight",NAME$q),_defineProperty(_CNameMapping$q,"DcmFloodlight",NAME$q),_defineProperty(_CNameMapping$q,"dcm_floodlight",NAME$q),_defineProperty(_CNameMapping$q,"DCM_Floodlight",NAME$q),_CNameMapping$q);
1515
+
1516
+ var _CNameMapping$p;var DIR_NAME$p='Matomo';var NAME$p='MATOMO';var DISPLAY_NAME$p='Matomo';_defineProperty({},DISPLAY_NAME$p,DIR_NAME$p);(_CNameMapping$p={},_defineProperty(_CNameMapping$p,NAME$p,NAME$p),_defineProperty(_CNameMapping$p,"Matomo",NAME$p),_defineProperty(_CNameMapping$p,"matomo",NAME$p),_CNameMapping$p);
1517
+
1518
+ var _CNameMapping$o;var DIR_NAME$o='Vero';var NAME$o='VERO';var DISPLAY_NAME$o='Vero';_defineProperty({},DISPLAY_NAME$o,DIR_NAME$o);(_CNameMapping$o={},_defineProperty(_CNameMapping$o,NAME$o,NAME$o),_defineProperty(_CNameMapping$o,"Vero",NAME$o),_defineProperty(_CNameMapping$o,"vero",NAME$o),_CNameMapping$o);
1519
+
1520
+ var _CNameMapping$n;var DIR_NAME$n='Mouseflow';var NAME$n='MOUSEFLOW';var DISPLAY_NAME$n='Mouseflow';_defineProperty({},DISPLAY_NAME$n,DIR_NAME$n);(_CNameMapping$n={},_defineProperty(_CNameMapping$n,NAME$n,NAME$n),_defineProperty(_CNameMapping$n,"Mouseflow",NAME$n),_defineProperty(_CNameMapping$n,"mouseflow",NAME$n),_defineProperty(_CNameMapping$n,"mouseFlow",NAME$n),_defineProperty(_CNameMapping$n,"MouseFlow",NAME$n),_defineProperty(_CNameMapping$n,'Mouse flow',NAME$n),_defineProperty(_CNameMapping$n,'mouse flow',NAME$n),_defineProperty(_CNameMapping$n,'mouse Flow',NAME$n),_defineProperty(_CNameMapping$n,'Mouse Flow',NAME$n),_CNameMapping$n);
1521
+
1522
+ var _CNameMapping$m;var DIR_NAME$m='Rockerbox';var NAME$m='ROCKERBOX';var DISPLAY_NAME$m='Rockerbox';_defineProperty({},DISPLAY_NAME$m,DIR_NAME$m);(_CNameMapping$m={},_defineProperty(_CNameMapping$m,NAME$m,NAME$m),_defineProperty(_CNameMapping$m,"Rockerbox",NAME$m),_defineProperty(_CNameMapping$m,"rockerbox",NAME$m),_defineProperty(_CNameMapping$m,"RockerBox",NAME$m),_defineProperty(_CNameMapping$m,'Rocker box',NAME$m),_defineProperty(_CNameMapping$m,'rocker box',NAME$m),_defineProperty(_CNameMapping$m,'Rocker Box',NAME$m),_CNameMapping$m);
1523
+
1524
+ var _CNameMapping$l;var DIR_NAME$l='ConvertFlow';var NAME$l='CONVERTFLOW';var DISPLAY_NAME$l='ConvertFlow';_defineProperty({},DISPLAY_NAME$l,DIR_NAME$l);(_CNameMapping$l={},_defineProperty(_CNameMapping$l,NAME$l,NAME$l),_defineProperty(_CNameMapping$l,"Convertflow",NAME$l),_defineProperty(_CNameMapping$l,"convertflow",NAME$l),_defineProperty(_CNameMapping$l,"convertFlow",NAME$l),_defineProperty(_CNameMapping$l,"ConvertFlow",NAME$l),_defineProperty(_CNameMapping$l,'Convert flow',NAME$l),_defineProperty(_CNameMapping$l,'convert flow',NAME$l),_defineProperty(_CNameMapping$l,'convert Flow',NAME$l),_defineProperty(_CNameMapping$l,'Convert Flow',NAME$l),_defineProperty(_CNameMapping$l,'CONVERT FLOW',NAME$l),_CNameMapping$l);
1525
+
1526
+ var _CNameMapping$k;var DIR_NAME$k='SnapEngage';var NAME$k='SNAPENGAGE';var DISPLAY_NAME$k='SnapEngage';_defineProperty({},DISPLAY_NAME$k,DIR_NAME$k);(_CNameMapping$k={},_defineProperty(_CNameMapping$k,NAME$k,NAME$k),_defineProperty(_CNameMapping$k,"SnapEngage",NAME$k),_defineProperty(_CNameMapping$k,"Snap_Engage",NAME$k),_defineProperty(_CNameMapping$k,"snapengage",NAME$k),_defineProperty(_CNameMapping$k,'SNAP ENGAGE',NAME$k),_defineProperty(_CNameMapping$k,'Snap Engage',NAME$k),_defineProperty(_CNameMapping$k,'snap engage',NAME$k),_CNameMapping$k);
1527
+
1528
+ var _CNameMapping$j;var DIR_NAME$j='LiveChat';var NAME$j='LIVECHAT';var DISPLAY_NAME$j='LiveChat';_defineProperty({},DISPLAY_NAME$j,DIR_NAME$j);(_CNameMapping$j={},_defineProperty(_CNameMapping$j,NAME$j,NAME$j),_defineProperty(_CNameMapping$j,"LiveChat",NAME$j),_defineProperty(_CNameMapping$j,"Live_Chat",NAME$j),_defineProperty(_CNameMapping$j,"livechat",NAME$j),_defineProperty(_CNameMapping$j,'LIVE CHAT',NAME$j),_defineProperty(_CNameMapping$j,'Live Chat',NAME$j),_defineProperty(_CNameMapping$j,'live chat',NAME$j),_CNameMapping$j);
1529
+
1530
+ var _CNameMapping$i;var DIR_NAME$i='Shynet';var NAME$i='SHYNET';var DISPLAY_NAME$i='Shynet';_defineProperty({},DISPLAY_NAME$i,DIR_NAME$i);(_CNameMapping$i={},_defineProperty(_CNameMapping$i,NAME$i,NAME$i),_defineProperty(_CNameMapping$i,"shynet",NAME$i),_defineProperty(_CNameMapping$i,"ShyNet",NAME$i),_defineProperty(_CNameMapping$i,"shyNet",NAME$i),_defineProperty(_CNameMapping$i,"Shynet",NAME$i),_defineProperty(_CNameMapping$i,'shy net',NAME$i),_defineProperty(_CNameMapping$i,'Shy Net',NAME$i),_defineProperty(_CNameMapping$i,'shy Net',NAME$i),_defineProperty(_CNameMapping$i,'Shy net',NAME$i),_CNameMapping$i);
1531
+
1532
+ var _CNameMapping$h;var DIR_NAME$h='Woopra';var NAME$h='WOOPRA';var DISPLAY_NAME$h='Woopra';_defineProperty({},DISPLAY_NAME$h,DIR_NAME$h);(_CNameMapping$h={},_defineProperty(_CNameMapping$h,NAME$h,NAME$h),_defineProperty(_CNameMapping$h,"Woopra",NAME$h),_defineProperty(_CNameMapping$h,"woopra",NAME$h),_CNameMapping$h);
1533
+
1534
+ var _CNameMapping$g;var DIR_NAME$g='RollBar';var NAME$g='ROLLBAR';var DISPLAY_NAME$g='RollBar';_defineProperty({},DISPLAY_NAME$g,DIR_NAME$g);(_CNameMapping$g={},_defineProperty(_CNameMapping$g,NAME$g,NAME$g),_defineProperty(_CNameMapping$g,"RollBar",NAME$g),_defineProperty(_CNameMapping$g,"Roll_Bar",NAME$g),_defineProperty(_CNameMapping$g,"rollbar",NAME$g),_defineProperty(_CNameMapping$g,"Rollbar",NAME$g),_defineProperty(_CNameMapping$g,'ROLL BAR',NAME$g),_defineProperty(_CNameMapping$g,'Roll Bar',NAME$g),_defineProperty(_CNameMapping$g,'roll bar',NAME$g),_CNameMapping$g);
1535
+
1536
+ var _CNameMapping$f;var DIR_NAME$f='QuoraPixel';var NAME$f='QUORA_PIXEL';var DISPLAY_NAME$f='Quora Pixel';_defineProperty({},DISPLAY_NAME$f,DIR_NAME$f);(_CNameMapping$f={},_defineProperty(_CNameMapping$f,NAME$f,NAME$f),_defineProperty(_CNameMapping$f,'Quora Pixel',NAME$f),_defineProperty(_CNameMapping$f,'Quora pixel',NAME$f),_defineProperty(_CNameMapping$f,'QUORA PIXEL',NAME$f),_defineProperty(_CNameMapping$f,"QuoraPixel",NAME$f),_defineProperty(_CNameMapping$f,"Quorapixel",NAME$f),_defineProperty(_CNameMapping$f,"QUORAPIXEL",NAME$f),_defineProperty(_CNameMapping$f,"Quora_Pixel",NAME$f),_defineProperty(_CNameMapping$f,"quora_pixel",NAME$f),_defineProperty(_CNameMapping$f,"Quora",NAME$f),_CNameMapping$f);
1537
+
1538
+ var _CNameMapping$e;var DIR_NAME$e='June';var NAME$e='JUNE';var DISPLAY_NAME$e='June';_defineProperty({},DISPLAY_NAME$e,DIR_NAME$e);(_CNameMapping$e={},_defineProperty(_CNameMapping$e,NAME$e,NAME$e),_defineProperty(_CNameMapping$e,"June",NAME$e),_defineProperty(_CNameMapping$e,"june",NAME$e),_CNameMapping$e);
1539
+
1540
+ var _CNameMapping$d;var DIR_NAME$d='Engage';var NAME$d='ENGAGE';var DISPLAY_NAME$d='Engage';_defineProperty({},DISPLAY_NAME$d,DIR_NAME$d);(_CNameMapping$d={},_defineProperty(_CNameMapping$d,NAME$d,NAME$d),_defineProperty(_CNameMapping$d,"Engage",NAME$d),_defineProperty(_CNameMapping$d,"engage",NAME$d),_CNameMapping$d);
1541
+
1542
+ var _CNameMapping$c;var DIR_NAME$c='Iterable';var NAME$c='ITERABLE';var DISPLAY_NAME$c='Iterable';_defineProperty({},DISPLAY_NAME$c,DIR_NAME$c);(_CNameMapping$c={},_defineProperty(_CNameMapping$c,NAME$c,NAME$c),_defineProperty(_CNameMapping$c,"Iterable",NAME$c),_defineProperty(_CNameMapping$c,"iterable",NAME$c),_CNameMapping$c);
1543
+
1544
+ var _CNameMapping$b;var DIR_NAME$b='YandexMetrica';var NAME$b='YANDEX_METRICA';var DISPLAY_NAME$b='Yandex.Metrica';_defineProperty({},DISPLAY_NAME$b,DIR_NAME$b);(_CNameMapping$b={},_defineProperty(_CNameMapping$b,NAME$b,NAME$b),_defineProperty(_CNameMapping$b,"Yandexmetrica",NAME$b),_defineProperty(_CNameMapping$b,"yandexmetrica",NAME$b),_defineProperty(_CNameMapping$b,"yandexMetrica",NAME$b),_defineProperty(_CNameMapping$b,"YandexMetrica",NAME$b),_CNameMapping$b);
1545
+
1546
+ var _CNameMapping$a;var DIR_NAME$a='Refiner';var NAME$a='REFINER';var DISPLAY_NAME$a='Refiner';_defineProperty({},DISPLAY_NAME$a,DIR_NAME$a);(_CNameMapping$a={},_defineProperty(_CNameMapping$a,NAME$a,NAME$a),_defineProperty(_CNameMapping$a,"Refiner",NAME$a),_defineProperty(_CNameMapping$a,"refiner",NAME$a),_CNameMapping$a);
1547
+
1548
+ var _CNameMapping$9;var DIR_NAME$9='Qualaroo';var NAME$9='QUALAROO';var DISPLAY_NAME$9='Qualaroo';_defineProperty({},DISPLAY_NAME$9,DIR_NAME$9);(_CNameMapping$9={},_defineProperty(_CNameMapping$9,NAME$9,NAME$9),_defineProperty(_CNameMapping$9,"Qualaroo",NAME$9),_defineProperty(_CNameMapping$9,"qualaroo",NAME$9),_CNameMapping$9);
1549
+
1550
+ var _CNameMapping$8;var DIR_NAME$8='Podsights';var NAME$8='PODSIGHTS';var DISPLAY_NAME$8='Podsights';_defineProperty({},DISPLAY_NAME$8,DIR_NAME$8);(_CNameMapping$8={},_defineProperty(_CNameMapping$8,NAME$8,NAME$8),_defineProperty(_CNameMapping$8,"Podsights",NAME$8),_defineProperty(_CNameMapping$8,"PodSights",NAME$8),_defineProperty(_CNameMapping$8,'pod Sights',NAME$8),_defineProperty(_CNameMapping$8,'Pod Sights',NAME$8),_defineProperty(_CNameMapping$8,'pod sights',NAME$8),_defineProperty(_CNameMapping$8,'POD SIGHTS',NAME$8),_defineProperty(_CNameMapping$8,'Pod sights',NAME$8),_CNameMapping$8);// default mapping for the events
1551
+
1552
+ var _CNameMapping$7;var DIR_NAME$7='Axeptio';var NAME$7='AXEPTIO';var DISPLAY_NAME$7='Axeptio';_defineProperty({},DISPLAY_NAME$7,DIR_NAME$7);(_CNameMapping$7={},_defineProperty(_CNameMapping$7,NAME$7,NAME$7),_defineProperty(_CNameMapping$7,"Axeptio",NAME$7),_defineProperty(_CNameMapping$7,"axeptio",NAME$7),_CNameMapping$7);
1553
+
1554
+ var _CNameMapping$6;var DIR_NAME$6='Satismeter';var NAME$6='SATISMETER';var DISPLAY_NAME$6='Satismeter';_defineProperty({},DISPLAY_NAME$6,DIR_NAME$6);(_CNameMapping$6={},_defineProperty(_CNameMapping$6,NAME$6,NAME$6),_defineProperty(_CNameMapping$6,"Satismeter",NAME$6),_defineProperty(_CNameMapping$6,"SatisMeter",NAME$6),_CNameMapping$6);
1555
+
1556
+ var _CNameMapping$5;var DIR_NAME$5='MicrosoftClarity';var NAME$5='MICROSOFT_CLARITY';var DISPLAY_NAME$5='Microsoft Clarity';_defineProperty({},DISPLAY_NAME$5,DIR_NAME$5);(_CNameMapping$5={},_defineProperty(_CNameMapping$5,NAME$5,NAME$5),_defineProperty(_CNameMapping$5,'Microsoft Clarity',NAME$5),_defineProperty(_CNameMapping$5,'Microsoft clarity',NAME$5),_defineProperty(_CNameMapping$5,'microsoft clarity',NAME$5),_defineProperty(_CNameMapping$5,"Microsoft_clarity",NAME$5),_defineProperty(_CNameMapping$5,"MicrosoftClarity",NAME$5),_defineProperty(_CNameMapping$5,"MICROSOFTCLARITY",NAME$5),_defineProperty(_CNameMapping$5,"microsoftclarity",NAME$5),_defineProperty(_CNameMapping$5,"microsoftClarity",NAME$5),_CNameMapping$5);
1557
+
1558
+ var _CNameMapping$4;var DIR_NAME$4='Sendinblue';var NAME$4='SENDINBLUE';var DISPLAY_NAME$4='Sendinblue';_defineProperty({},DISPLAY_NAME$4,DIR_NAME$4);(_CNameMapping$4={},_defineProperty(_CNameMapping$4,NAME$4,NAME$4),_defineProperty(_CNameMapping$4,"Sendinblue",NAME$4),_defineProperty(_CNameMapping$4,"sendinblue",NAME$4),_defineProperty(_CNameMapping$4,"SendinBlue",NAME$4),_CNameMapping$4);
1559
+
1560
+ var _CNameMapping$3;var DIR_NAME$3='Olark';var NAME$3='OLARK';var DISPLAY_NAME$3='Olark';_defineProperty({},DISPLAY_NAME$3,DIR_NAME$3);(_CNameMapping$3={},_defineProperty(_CNameMapping$3,NAME$3,NAME$3),_defineProperty(_CNameMapping$3,"Olark",NAME$3),_defineProperty(_CNameMapping$3,"olark",NAME$3),_CNameMapping$3);
1561
+
1562
+ var _CNameMapping$2;var DIR_NAME$2='Lemnisk';var NAME$2='LEMNISK';var DISPLAY_NAME$2='Lemnisk';_defineProperty({},DISPLAY_NAME$2,DIR_NAME$2);(_CNameMapping$2={},_defineProperty(_CNameMapping$2,NAME$2,NAME$2),_defineProperty(_CNameMapping$2,"LEMNISK_MARKETING_AUTOMATION",NAME$2),_defineProperty(_CNameMapping$2,'Lemnisk Marketing Automation',NAME$2),_defineProperty(_CNameMapping$2,"LemniskMarketingAutomation",NAME$2),_defineProperty(_CNameMapping$2,"lemniskmarketingautomation",NAME$2),_defineProperty(_CNameMapping$2,"lemniskMarketingAutomation",NAME$2),_defineProperty(_CNameMapping$2,"lemnisk",NAME$2),_defineProperty(_CNameMapping$2,"Lemnisk",NAME$2),_CNameMapping$2);
1563
+
1564
+ var _CNameMapping$1;var DIR_NAME$1='TiktokAds';var NAME$1='TIKTOK_ADS';var DISPLAY_NAME$1='TikTok Ads';_defineProperty({},DISPLAY_NAME$1,DIR_NAME$1);(_CNameMapping$1={},_defineProperty(_CNameMapping$1,NAME$1,NAME$1),_defineProperty(_CNameMapping$1,"TiktokAds",NAME$1),_defineProperty(_CNameMapping$1,'Tiktok ads',NAME$1),_defineProperty(_CNameMapping$1,'Tiktok Ads',NAME$1),_defineProperty(_CNameMapping$1,'Tik Tok Ads',NAME$1),_defineProperty(_CNameMapping$1,'tik tok ads',NAME$1),_defineProperty(_CNameMapping$1,"tiktokads",NAME$1),_CNameMapping$1);
1565
+
1566
+ var _CNameMapping;var DIR_NAME='ActiveCampaign';var NAME='ACTIVE_CAMPAIGN';var DISPLAY_NAME='Active Campaign';_defineProperty({},DISPLAY_NAME,DIR_NAME);(_CNameMapping={ActiveCampaign:NAME,'Active Campaign':NAME,'ACTIVE CAMPAIGN':NAME},_defineProperty(_CNameMapping,NAME,NAME),_defineProperty(_CNameMapping,"activecampaign",NAME),_defineProperty(_CNameMapping,'active campaign',NAME),_defineProperty(_CNameMapping,'Active campaign',NAME),_defineProperty(_CNameMapping,'active Campaign',NAME),_defineProperty(_CNameMapping,"active_campaign",NAME),_CNameMapping);
1567
+
1568
+ var _destDisplayNamesToFi;// map of the destination display names to the destination directory names
1569
+ var destDisplayNamesToFileNamesMap=(_destDisplayNamesToFi={},_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$Q,DIR_NAME$Q),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$X,DIR_NAME$X),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$R,DIR_NAME$R),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$V,DIR_NAME$V),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$t,DIR_NAME$t),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$T,DIR_NAME$T),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$15,DIR_NAME$15),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$P,DIR_NAME$P),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$O,DIR_NAME$O),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$N,DIR_NAME$N),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$$,DIR_NAME$$),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$13,DIR_NAME$13),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$11,DIR_NAME$11),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$Z,DIR_NAME$Z),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$J,DIR_NAME$J),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$F,DIR_NAME$F),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$14,DIR_NAME$14),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$Y,DIR_NAME$Y),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$u,DIR_NAME$u),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$W,DIR_NAME$W),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$G,DIR_NAME$G),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$18,DIR_NAME$18),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$E,DIR_NAME$E),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$I,DIR_NAME$I),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$17,DIR_NAME$17),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$B,DIR_NAME$B),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$M,DIR_NAME$M),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$12,DIR_NAME$12),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$16,DIR_NAME$16),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$D,DIR_NAME$D),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$19,DIR_NAME$19),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$K,DIR_NAME$K),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$x,DIR_NAME$x),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$_,DIR_NAME$_),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$S,DIR_NAME$S),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$10,DIR_NAME$10),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$H,DIR_NAME$H),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$z,DIR_NAME$z),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$A,DIR_NAME$A),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$w,DIR_NAME$w),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$y,DIR_NAME$y),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$v,DIR_NAME$v),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$C,DIR_NAME$C),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$U,DIR_NAME$U),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$L,DIR_NAME$L),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$s,DIR_NAME$s),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$r,DIR_NAME$r),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$q,DIR_NAME$q),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$p,DIR_NAME$p),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$o,DIR_NAME$o),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$n,DIR_NAME$n),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$m,DIR_NAME$m),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$l,DIR_NAME$l),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$k,DIR_NAME$k),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$j,DIR_NAME$j),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$i,DIR_NAME$i),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$h,DIR_NAME$h),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$g,DIR_NAME$g),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$f,DIR_NAME$f),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$e,DIR_NAME$e),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$d,DIR_NAME$d),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$c,DIR_NAME$c),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$b,DIR_NAME$b),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$a,DIR_NAME$a),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$9,DIR_NAME$9),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$8,DIR_NAME$8),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$7,DIR_NAME$7),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$6,DIR_NAME$6),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$5,DIR_NAME$5),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$4,DIR_NAME$4),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$3,DIR_NAME$3),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$2,DIR_NAME$2),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$1,DIR_NAME$1),_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME,DIR_NAME),_destDisplayNamesToFi);
1570
+
1571
+ var DEFAULT_INTEGRATIONS_CONFIG={All:true};
1572
+
1573
+ var isDestIntgConfigTruthy=function isDestIntgConfigTruthy(destIntgConfig){return !isUndefined(destIntgConfig)&&Boolean(destIntgConfig)===true;};var isDestIntgConfigFalsy=function isDestIntgConfigFalsy(destIntgConfig){return !isUndefined(destIntgConfig)&&Boolean(destIntgConfig)===false;};/**
1574
+ * Filters the destinations that should not be loaded or forwarded events to based on the integration options (load or events API)
1575
+ * @param intgOpts Integration options object
1576
+ * @param destinations Destinations array
1577
+ * @returns Destinations array filtered based on the integration options
1578
+ */var filterDestinations=function filterDestinations(intgOpts,destinations){var allOptVal=intgOpts.All;return destinations.filter(function(dest){var destDisplayName=dest.displayName;var isDestEnabled;if(allOptVal){isDestEnabled=true;if(isDestIntgConfigFalsy(intgOpts[destDisplayName])){isDestEnabled=false;}}else {isDestEnabled=false;if(isDestIntgConfigTruthy(intgOpts[destDisplayName])){isDestEnabled=true;}}return isDestEnabled;});};
1579
+
1580
+ var READY_CHECK_TIMEOUT_MS=11*1000;// 11 seconds
1581
+ var SCRIPT_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
1582
+ var DEVICE_MODE_DESTINATIONS_PLUGIN='DeviceModeDestinationsPlugin';
1583
+
1584
+ var DESTINATION_NOT_SUPPORTED_ERROR=function DESTINATION_NOT_SUPPORTED_ERROR(destUserFriendlyId){return "Destination ".concat(destUserFriendlyId," is not supported.");};var DESTINATION_SDK_LOAD_ERROR=function DESTINATION_SDK_LOAD_ERROR(context,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load script for destination ").concat(destUserFriendlyId,".");};var DESTINATION_INIT_ERROR=function DESTINATION_INIT_ERROR(destUserFriendlyId){return "Failed to initialize destination ".concat(destUserFriendlyId,".");};var DESTINATION_INTEGRATIONS_DATA_ERROR=function DESTINATION_INTEGRATIONS_DATA_ERROR(destUserFriendlyId){return "Failed to get integrations data for destination ".concat(destUserFriendlyId,".");};var DESTINATION_READY_TIMEOUT_ERROR=function DESTINATION_READY_TIMEOUT_ERROR(timeout,destUserFriendlyId){return "A timeout of ".concat(timeout," ms occurred while trying to check the ready status for \"").concat(destUserFriendlyId,"\" destination.");};
1585
+
1586
+ /**
1587
+ * Determines if the destination SDK code is evaluated
1588
+ * @param destSDKIdentifier The name of the global globalThis object that contains the destination SDK
1589
+ * @param sdkTypeName The name of the destination SDK type
1590
+ * @param logger Logger instance
1591
+ * @returns true if the destination SDK code is evaluated, false otherwise
1592
+ */var isDestinationSDKMounted=function isDestinationSDKMounted(destSDKIdentifier,sdkTypeName,logger){return Boolean(globalThis[destSDKIdentifier]&&globalThis[destSDKIdentifier][sdkTypeName]&&globalThis[destSDKIdentifier][sdkTypeName].prototype&&typeof globalThis[destSDKIdentifier][sdkTypeName].prototype.constructor!=='undefined');};var createDestinationInstance=function createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state){var rAnalytics=globalThis.rudderanalytics;var analytics=rAnalytics.getAnalyticsInstance(state.lifecycle.writeKey.value);return new globalThis[destSDKIdentifier][sdkTypeName](clone$1(dest.config),{loadIntegration:state.nativeDestinations.loadIntegration.value,logLevel:state.lifecycle.logLevel.value,loadOnlyIntegrations:state.nativeDestinations.loadOnlyIntegrations.value,page:function page(category,name,properties,options,callback){return analytics.page(pageArgumentsToCallOptions(category,name,properties,options,callback));},track:function track(event,properties,options,callback){return analytics.track(trackArgumentsToCallOptions(event,properties,options,callback));},identify:function identify(userId,traits,options,callback){return analytics.identify(identifyArgumentsToCallOptions(userId,traits,options,callback));},alias:function alias(to,from,options,callback){return analytics.alias(aliasArgumentsToCallOptions(to,from,options,callback));},group:function group(groupId,traits,options,callback){return analytics.group(groupArgumentsToCallOptions(groupId,traits,options,callback));},getAnonymousId:function getAnonymousId(){return analytics.getAnonymousId();},getUserId:function getUserId(){return analytics.getUserId();},getUserTraits:function getUserTraits(){return analytics.getUserTraits();},getGroupId:function getGroupId(){return analytics.getGroupId();},getGroupTraits:function getGroupTraits(){return analytics.getGroupTraits();},getSessionId:function getSessionId(){return analytics.getSessionId();}},{shouldApplyDeviceModeTransformation:dest.shouldApplyDeviceModeTransformation,propagateEventsUntransformedOnError:dest.propagateEventsUntransformedOnError,destinationId:dest.id});};var isDestinationReady=function isDestinationReady(dest){return new Promise(function(resolve,reject){var instance=dest.instance;var handleNumber;var checkReady=function checkReady(){if(instance.isLoaded()&&(!instance.isReady||instance.isReady())){resolve(true);}else {handleNumber=globalThis.requestAnimationFrame(checkReady);}};checkReady();setTimeout(function(){globalThis.cancelAnimationFrame(handleNumber);reject(new Error(DESTINATION_READY_TIMEOUT_ERROR(READY_CHECK_TIMEOUT_MS,dest.userFriendlyId)));},READY_CHECK_TIMEOUT_MS);});};/**
1593
+ * Extracts the integration config, if any, from the given destination
1594
+ * and merges it with the current integrations config
1595
+ * @param dest Destination object
1596
+ * @param curDestIntgConfig Current destinations integration config
1597
+ * @param logger Logger object
1598
+ * @returns Combined destinations integrations config
1599
+ */var getCumulativeIntegrationsConfig=function getCumulativeIntegrationsConfig(dest,curDestIntgConfig,errorHandler){var _dest$instance;var integrationsConfig=curDestIntgConfig;if(isFunction((_dest$instance=dest.instance)===null||_dest$instance===void 0?void 0:_dest$instance.getDataForIntegrationsObject)){try{var _dest$instance2;integrationsConfig=mergeDeepRight(curDestIntgConfig,(_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject());}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INTEGRATIONS_DATA_ERROR(dest.userFriendlyId));}}return integrationsConfig;};var initializeDestination=function initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger){try{var initializedDestination=clone$1(dest);var destInstance=createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state);initializedDestination.instance=destInstance;destInstance.init();isDestinationReady(initializedDestination).then(function(){// Collect the integrations data for the hybrid mode destinations
1600
+ if(isHybridModeDestination(initializedDestination)){state.nativeDestinations.integrationsConfig.value=getCumulativeIntegrationsConfig(initializedDestination,state.nativeDestinations.integrationsConfig.value,errorHandler);}state.nativeDestinations.initializedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.initializedDestinations.value),[initializedDestination]);}).catch(function(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);// The error message is already formatted in the isDestinationReady function
1601
+ logger===null||logger===void 0||logger.error(err);});}catch(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INIT_ERROR(dest.userFriendlyId));}};
1602
+
1603
+ var pluginName$b='DeviceModeDestinations';var DeviceModeDestinations=function DeviceModeDestinations(){return {name:pluginName$b,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$b]);},nativeDestinations:{setActiveDestinations:function setActiveDestinations(state,pluginsManager,errorHandler,logger){var _clone,_state$consents$postC,_state$consents$postC2;// Normalize the integration options from the load API call
1604
+ state.nativeDestinations.loadOnlyIntegrations.value=(_clone=clone$1(state.loadOptions.value.integrations))!==null&&_clone!==void 0?_clone:DEFAULT_INTEGRATIONS_CONFIG;state.nativeDestinations.loadIntegration.value=state.loadOptions.value.loadIntegration;// Filter destination that doesn't have mapping config-->Integration names
1605
+ var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===void 0||errorHandler.onError(new Error(DESTINATION_NOT_SUPPORTED_ERROR(configDest.userFriendlyId)),DEVICE_MODE_DESTINATIONS_PLUGIN);return false;});// Filter destinations that are disabled through load and consent API options
1606
+ var destinationsToLoad=filterDestinations(mergeDeepRight(state.nativeDestinations.loadOnlyIntegrations.value,(_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===void 0?void 0:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:{}),configSupportedDestinations);var consentedDestinations=destinationsToLoad.filter(function(dest){var _pluginsManager$invok;return(// if consent manager is not configured, then default to load the destination
1607
+ (_pluginsManager$invok=pluginsManager.invokeSingle("consentManager.isDestinationConsented",state,dest.config,errorHandler,logger))!==null&&_pluginsManager$invok!==void 0?_pluginsManager$invok:true);});state.nativeDestinations.activeDestinations.value=consentedDestinations;},load:function load(state,externalSrcLoader,errorHandler,logger,externalScriptOnLoad){var integrationsCDNPath=state.lifecycle.integrationsCDNPath.value;var activeDestinations=state.nativeDestinations.activeDestinations.value;activeDestinations.forEach(function(dest){var sdkName=destDisplayNamesToFileNamesMap[dest.displayName];var destSDKIdentifier="".concat(sdkName,"_RS");// this is the name of the object loaded on the window
1608
+ var sdkTypeName=sdkName;if(sdkTypeName&&!isDestinationSDKMounted(destSDKIdentifier,sdkTypeName)){var destSdkURL="".concat(integrationsCDNPath,"/").concat(sdkName,".min.js");externalSrcLoader.loadJSFile({url:destSdkURL,id:dest.userFriendlyId,callback:externalScriptOnLoad!==null&&externalScriptOnLoad!==void 0?externalScriptOnLoad:function(id){if(!id){logger===null||logger===void 0||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId));state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);}else {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}},timeout:SCRIPT_LOAD_TIMEOUT_MS});}else if(sdkTypeName){initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}else {logger===null||logger===void 0||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.displayName));}});}}};};
1609
+
1610
+ var DEFAULT_TRANSFORMATION_QUEUE_OPTIONS={minRetryDelay:500,backoffFactor:2,maxAttempts:3};var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
1611
+ var QUEUE_NAME$2='rudder';var DMT_PLUGIN='DeviceModeTransformationPlugin';
1612
+
1613
+ var DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR=function DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(context,displayName,reason,action){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Event transformation unsuccessful for destination \"").concat(displayName,"\". Reason: ").concat(reason,". ").concat(action,".");};var DMT_REQUEST_FAILED_ERROR=function DMT_REQUEST_FAILED_ERROR(context,displayName,status,action){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"[Destination: ").concat(displayName,"].Transformation request failed with status: ").concat(status,". Retries exhausted. ").concat(action,".");};var DMT_EXCEPTION=function DMT_EXCEPTION(displayName){return "[Destination:".concat(displayName,"].");};var DMT_SERVER_ACCESS_DENIED_WARNING=function DMT_SERVER_ACCESS_DENIED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Transformation server access is denied. The configuration data seems to be out of sync. Sending untransformed event to the destination.");};
1614
+
1615
+ /**
1616
+ * A helper function that will take rudderEvent and generate
1617
+ * a batch payload that will be sent to transformation server
1618
+ *
1619
+ */var createPayload=function createPayload(event,destinationIds,token){var orderNo=Date.now();var payload={metadata:{'Custom-Authorization':token},batch:[{orderNo:orderNo,destinationIds:destinationIds,event:event}]};return payload;};var sendTransformedEventToDestinations=function sendTransformedEventToDestinations(state,pluginsManager,destinationIds,result,status,event,errorHandler,logger){var NATIVE_DEST_EXT_POINT='destinationsEventsQueue.enqueueEventToDestination';var ACTION_TO_SEND_UNTRANSFORMED_EVENT='Sending untransformed event';var ACTION_TO_DROP_EVENT='Dropping the event';var destinations=state.nativeDestinations.initializedDestinations.value.filter(function(d){return d&&destinationIds.includes(d.id);});destinations.forEach(function(dest){try{var eventsToSend=[];switch(status){case 200:{var response=JSON.parse(result);var destTransformedResult=response.transformedBatch.find(function(e){return e.id===dest.id;});destTransformedResult===null||destTransformedResult===void 0||destTransformedResult.payload.forEach(function(tEvent){if(tEvent.status==='200'){eventsToSend.push(tEvent.event);}else {var reason='Unknown';if(tEvent.status==='410'){reason='Transformation is not available';}var action=ACTION_TO_DROP_EVENT;if(dest.propagateEventsUntransformedOnError===true){action=ACTION_TO_SEND_UNTRANSFORMED_EVENT;eventsToSend.push(event);logger===null||logger===void 0||logger.warn(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}else {logger===null||logger===void 0||logger.error(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}}});break;}// Transformation server access denied
1620
+ case 404:{logger===null||logger===void 0||logger.warn(DMT_SERVER_ACCESS_DENIED_WARNING(DMT_PLUGIN));eventsToSend.push(event);break;}default:{if(dest.propagateEventsUntransformedOnError===true){logger===null||logger===void 0||logger.warn(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_SEND_UNTRANSFORMED_EVENT));eventsToSend.push(event);}else {logger===null||logger===void 0||logger.error(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_DROP_EVENT));}break;}}eventsToSend===null||eventsToSend===void 0||eventsToSend.forEach(function(tEvent){if(isNonEmptyObject(tEvent)){pluginsManager.invokeSingle(NATIVE_DEST_EXT_POINT,state,tEvent,dest,errorHandler,logger);}});}catch(e){errorHandler===null||errorHandler===void 0||errorHandler.onError(e,DMT_PLUGIN,DMT_EXCEPTION(dest.displayName));}});};
1621
+
1622
+ var pluginName$a='DeviceModeTransformation';var DeviceModeTransformation=function DeviceModeTransformation(){return {name:pluginName$a,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);},transformEvent:{init:function init(state,pluginsManager,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1623
+ "".concat(QUEUE_NAME$2,"_").concat(writeKey),DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,function(item,done,attemptNumber,maxRetryAttempts){var payload=createPayload(item.event,item.destinationIds,item.token);httpClient.getAsyncData({url:"".concat(state.lifecycle.dataPlaneUrl.value,"/transform"),options:{method:'POST',data:getDMTDeliveryPayload(payload),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// null means item will not be requeued
1624
+ var queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemptNumber===maxRetryAttempts){var _details$xhr;sendTransformedEventToDestinations(state,pluginsManager,item.destinationIds,result,details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status,item.event,errorHandler,logger);}done(queueErrResp,result);}});},storeManager,MEMORY_STORAGE);return eventsQueue;},enqueue:function enqueue(state,eventsQueue,event,destinations){var destinationIds=destinations.map(function(d){return d.id;});eventsQueue.addItem({event:event,destinationIds:destinationIds,token:state.session.authToken.value});}}};};
1625
+
1626
+ var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";
1627
+
1628
+ var pluginName$9='ErrorReporting';var ErrorReporting=function ErrorReporting(){return {name:pluginName$9,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$9]);},errorReporting:{init:function init(state,pluginEngine,externalSrcLoader,logger){var _state$source$value,_state$source$value2;if(!((_state$source$value=state.source.value)!==null&&_state$source$value!==void 0&&_state$source$value.config)||!((_state$source$value2=state.source.value)!==null&&_state$source$value2!==void 0&&_state$source$value2.id)){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:function notify(pluginEngine,client,error,state,logger){pluginEngine.invokeSingle('errorReportingProvider.notify',client,error,state,logger);},breadcrumb:function breadcrumb(pluginEngine,client,message,logger){pluginEngine.invokeSingle('errorReportingProvider.breadcrumb',client,message,logger);}}};};
1629
+
1630
+ var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
1631
+
1632
+ var getSegmentAnonymousId=function getSegmentAnonymousId(getStorageEngine){var anonymousId;/**
1633
+ * First check the local storage for anonymousId
1634
+ * Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify
1635
+ */var lsEngine=getStorageEngine(LOCAL_STORAGE);if(lsEngine!==null&&lsEngine!==void 0&&lsEngine.isEnabled){anonymousId=lsEngine.getItem(externallyLoadedSessionStorageKeys.segment);}// If anonymousId is not present in local storage and find it in cookies
1636
+ var csEngine=getStorageEngine(COOKIE_STORAGE);if(!anonymousId&&csEngine!==null&&csEngine!==void 0&&csEngine.isEnabled){anonymousId=csEngine.getItem(externallyLoadedSessionStorageKeys.segment);}return anonymousId;};
1637
+
1638
+ var pluginName$8='ExternalAnonymousId';var ExternalAnonymousId=function ExternalAnonymousId(){return {name:pluginName$8,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$8]);},storage:{getAnonymousId:function getAnonymousId(getStorageEngine,options){var _options$autoCapture;var anonymousId;if(options!==null&&options!==void 0&&(_options$autoCapture=options.autoCapture)!==null&&_options$autoCapture!==void 0&&_options$autoCapture.enabled&&options.autoCapture.source){var source=options.autoCapture.source.toLowerCase();if(!Object.keys(externallyLoadedSessionStorageKeys).includes(source)){return anonymousId;}// eslint-disable-next-line sonarjs/no-small-switch
1639
+ switch(source){case'segment':anonymousId=getSegmentAnonymousId(getStorageEngine);break;}}return anonymousId;}}};};
1640
+
1641
+ var AMP_LINKER_ANONYMOUS_ID_KEY='rs_amp_id';
1642
+
1643
+ /* eslint-disable no-bitwise */ /**
1644
+ * generate crc table
1645
+ *
1646
+ * @params none
1647
+ * @returns array of CRC table
1648
+ */var makeCRCTable=function makeCRCTable(){var crcTable=[];var c;for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?0xedb88320^c>>>1:c>>>1;}crcTable[n]=c;}return crcTable;};/**
1649
+ * This is utility function for crc32 algorithm
1650
+ *
1651
+ * @param {string} str
1652
+ * @returns {number} crc32
1653
+ */var crc32=function crc32(str){var crcTable=makeCRCTable();var crc=0^-1;for(var i=0;i<str.length;i++){// eslint-disable-next-line @typescript-eslint/ban-ts-comment
1654
+ // @ts-ignore
1655
+ crc=crc>>>8^crcTable[(crc^str.charCodeAt(i))&0xff];}return (crc^-1)>>>0;};
1656
+
1657
+ /**
1658
+ * An interface to fetch user device details.
1659
+ */var USER_INTERFACE={/**
1660
+ * @returns {string} user language
1661
+ */getUserLanguage:function getUserLanguage(){var _navigator;return (_navigator=navigator)===null||_navigator===void 0?void 0:_navigator.language;},/**
1662
+ * @returns {string} userAgent
1663
+ */getUserAgent:function getUserAgent(){var _navigator2;return (_navigator2=navigator)===null||_navigator2===void 0?void 0:_navigator2.userAgent;}};
1664
+
1665
+ /**
1666
+ * This is utility function for decoding from base 64 to utf8
1667
+ *
1668
+ * @param {string} str base64
1669
+ *
1670
+ * @returns {string} utf8
1671
+ */var b64DecodeUnicode=function b64DecodeUnicode(str){return(// Going backwards: from bytestream, to percent-encoding, to original string.
1672
+ decodeURIComponent(globalThis.atob(str).split('').map(function(c){var percentEncodingChar="00".concat(c.charCodeAt(0).toString(16));return "%".concat(percentEncodingChar.slice(-2));}).join('')));};/**
1673
+ * This is utility function for decoding from base 64 to utf8
1674
+ *
1675
+ * @param {string} data
1676
+ *
1677
+ * @return {string}
1678
+ */var decode$1=function decode(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var decodedData=data.endsWith('..')?data.substring(0,data.length-2):data;return b64DecodeUnicode(decodedData);};
1679
+
1680
+ var KEY_VALIDATOR=/^[\w.-]+$/;var CHECKSUM_OFFSET_MAX_MIN=1;var VALID_VERSION=1;var DELIMITER='*';/**
1681
+ * Parse the linker param value to version checksum and serializedParams
1682
+ *
1683
+ * @param {string} value
1684
+ *
1685
+ * @return {?Object}
1686
+ */var parseLinkerParamValue=function parseLinkerParamValue(value){var parts=value.split(DELIMITER);var isEven=parts.length%2===0;if(parts.length<4||!isEven){// Format <version>*<checksum>*<key1>*<value1>
1687
+ // Note: linker makes sure there's at least one pair of non empty key value
1688
+ // Make sure there is at least three delimiters.
1689
+ return null;}var version=Number(parts.shift());if(version!==VALID_VERSION){return null;}var checksum=parts.shift();var serializedIds=parts.join(DELIMITER);return {checksum:checksum!==null&&checksum!==void 0?checksum:'',serializedIds:serializedIds};};/**
1690
+ * Deserialize the serializedIds and return keyValue pairs.
1691
+ *
1692
+ * @param {string} serializedIds
1693
+ *
1694
+ * @return {!Object<string, string>}
1695
+ */var deserialize=function deserialize(serializedIds){if(!serializedIds){return {};}var keyValuePairs={};var params=serializedIds.split(DELIMITER);for(var i=0;i<params.length;i+=2){var key=params[i];var valid=KEY_VALIDATOR.test(key);if(valid){keyValuePairs[key]=decode$1(params[i+1]);}}return keyValuePairs;};/**
1696
+ * Generates a semi-unique value for page visitor.
1697
+ *
1698
+ * @return {string}
1699
+ */var getFingerprint=function getFingerprint(userAgent,language){var date=new Date();var timezone=date.getTimezoneOffset();return [userAgent,timezone,language].join(DELIMITER);};/**
1700
+ * Rounded time used to check if t2 - t1 is within our time tolerance.
1701
+ * Timestamp in minutes, floored.
1702
+ *
1703
+ * @return {number}
1704
+ */var getMinSinceEpoch=function getMinSinceEpoch(){return Math.floor(Date.now()/60000);};/**
1705
+ * Create a unique checksum hashing the fingerprint and a few other values.
1706
+ *
1707
+ * @param {string} serializedIds
1708
+ * @param {number=} optOffsetMin
1709
+ * @param {string} userAgent
1710
+ * @param {string} language
1711
+ *
1712
+ * @return {string}
1713
+ */var getCheckSum=function getCheckSum(serializedIds,optOffsetMin,userAgent,language){var fingerprint=getFingerprint(userAgent,language);var offset=optOffsetMin||0;var timestamp=getMinSinceEpoch()-offset;var crc=crc32([fingerprint,timestamp,serializedIds].join(DELIMITER));// Encoded to base36 for fewer bytes.
1714
+ return crc.toString(36);};/**
1715
+ * Check if the checksum is valid with time offset tolerance.
1716
+ *
1717
+ * @param {string} serializedIds
1718
+ * @param {string} checksum
1719
+ *
1720
+ * @return {boolean}
1721
+ */var isCheckSumValid=function isCheckSumValid(serializedIds,checksum){var userAgent=USER_INTERFACE.getUserAgent();var language=USER_INTERFACE.getUserLanguage();for(var i=0;i<=CHECKSUM_OFFSET_MAX_MIN;i+=1){var calculateCheckSum=getCheckSum(serializedIds,i,userAgent,language);if(calculateCheckSum===checksum){return true;}}return false;};/**
1722
+ * AMP Linker Parser (works for Rudder, GA or any other linker created by following Google's linker standard.)
1723
+ *
1724
+ * @param {string} value
1725
+ *
1726
+ * @return {?Object<string, string>}
1727
+ */var parseLinker=function parseLinker(value){var linkerObj=parseLinkerParamValue(value);if(!linkerObj){return null;}var checksum=linkerObj.checksum,serializedIds=linkerObj.serializedIds;if(!serializedIds||!checksum||!isCheckSumValid(serializedIds,checksum)){return null;}return deserialize(serializedIds);};
1728
+
1729
+ var pluginName$7='GoogleLinker';var GoogleLinker=function GoogleLinker(){return {name:pluginName$7,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$7]);},userSession:{anonymousIdGoogleLinker:function anonymousIdGoogleLinker(rudderAmpLinkerParam){if(!rudderAmpLinkerParam){return null;}var parsedAnonymousIdObj=rudderAmpLinkerParam?parseLinker(rudderAmpLinkerParam):null;return parsedAnonymousIdObj?parsedAnonymousIdObj[AMP_LINKER_ANONYMOUS_ID_KEY]:null;}}};};
1730
+
1731
+ var KETCH_CONSENT_COOKIE_READ_ERROR=function KETCH_CONSENT_COOKIE_READ_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to read the consent cookie.");};var KETCH_CONSENT_COOKIE_PARSE_ERROR=function KETCH_CONSENT_COOKIE_PARSE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to parse the consent cookie.");};var DESTINATION_CONSENT_STATUS_ERROR$1="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1732
+
1733
+ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
1734
+
1735
+ /**
1736
+ * Gets the consent data from the Ketch's consent cookie
1737
+ * @param storeManager Store manager instance
1738
+ * @param logger Logger instance
1739
+ * @returns Consent data from the consent cookie
1740
+ */var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
1741
+ var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1742
+ var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1743
+ var consentPurposes={};Object.entries(consentCookieData).forEach(function(pEntry){var purposeCode=pEntry[0];var purposeValue=pEntry[1];consentPurposes[purposeCode]=(purposeValue===null||purposeValue===void 0?void 0:purposeValue.status)==='granted';});return consentPurposes;};/**
1744
+ * Gets the consent data in the format expected by the application state
1745
+ * @param ketchConsentData Consent data derived from the consent cookie
1746
+ * @returns Consent data
1747
+ */var getConsentData=function getConsentData(ketchConsentData){var allowedConsentIds=[];var deniedConsentIds=[];if(ketchConsentData){Object.entries(ketchConsentData).forEach(function(e){var purposeCode=e[0];var isConsented=e[1];if(isConsented){allowedConsentIds.push(purposeCode);}else {deniedConsentIds.push(purposeCode);}});}return {allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};};var updateConsentStateFromData=function updateConsentStateFromData(state,ketchConsentData){var consentData=getConsentData(ketchConsentData);state.consents.initialized.value=isDefined(ketchConsentData);state.consents.data.value=consentData;};
1748
+
1749
+ var pluginName$6='KetchConsentManager';var KetchConsentManager=function KetchConsentManager(){return {name:pluginName$6,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$6]);},consentManager:{init:function init(state,logger){// getKetchUserConsentedPurposes returns current ketch opted-in purposes
1750
+ // This will be helpful for debugging
1751
+ globalThis.getKetchUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===void 0?void 0:_state$consents$data$.slice();};// getKetchUserDeniedPurposes returns current ketch opted-out purposes
1752
+ // This will be helpful for debugging
1753
+ globalThis.getKetchUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===void 0?void 0:_state$consents$data$2.slice();};// updateKetchConsent callback function to update current consent purpose state
1754
+ // this will be called from ketch rudderstack plugin
1755
+ globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1756
+ var ketchConsentData;if(!isUndefined(globalThis.ketchConsent)){ketchConsentData=globalThis.ketchConsent;}else {ketchConsentData=getKetchConsentData(storeManager,logger);}updateConsentStateFromData(state,ketchConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var ketchConsentPurposes=destConfig.ketchConsentPurposes,consentManagement=destConfig.consentManagement;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};// Generic consent management
1757
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1758
+ var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
1759
+ if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
1760
+ // the configured resolution strategy
1761
+ switch(state.consents.resolutionStrategy.value){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1762
+ // TODO: To be removed once the source config API is updated to support generic consent management
1763
+ }else if(ketchConsentPurposes){var _configuredConsents=ketchConsentPurposes.map(function(p){return p.purpose.trim();}).filter(function(n){return n;});// Check if any of the destination's mapped ketch purposes are consented by the user in the browser.
1764
+ return _configuredConsents.some(matchPredicate)||_configuredConsents.length===0;}// If there are no consents configured for the destination for the current provider, events should be sent.
1765
+ return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,KETCH_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$1);return true;}}}};};
1766
+
1767
+ var DEFAULT_QUEUE_OPTIONS={maxItems:100};var QUEUE_NAME$1='rudder_destinations_events';var NATIVE_DESTINATION_QUEUE_PLUGIN='NativeDestinationQueuePlugin';
1768
+
1769
+ var DESTINATION_EVENT_FILTERING_WARNING=function DESTINATION_EVENT_FILTERING_WARNING(context,eventName,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(eventName,"\" track event has been filtered for the \"").concat(destUserFriendlyId,"\" destination.");};var DESTINATION_EVENT_FORWARDING_ERROR=function DESTINATION_EVENT_FORWARDING_ERROR(destUserFriendlyId){return "Failed to forward event to destination \"".concat(destUserFriendlyId,"\".");};
1770
+
1771
+ var getNormalizedQueueOptions$1=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_QUEUE_OPTIONS,queueOpts);};var isValidEventName=function isValidEventName(eventName){return eventName&&typeof eventName==='string';};var isEventDenyListed=function isEventDenyListed(eventType,eventName,dest){if(eventType!=='track'){return false;}var _dest$config=dest.config,blacklistedEvents=_dest$config.blacklistedEvents,whitelistedEvents=_dest$config.whitelistedEvents,eventFilteringOption=_dest$config.eventFilteringOption;switch(eventFilteringOption){// Blacklist is chosen for filtering events
1772
+ case'blacklistedEvents':{if(!isValidEventName(eventName)){return false;}var trimmedEventName=eventName.trim();if(Array.isArray(blacklistedEvents)){return blacklistedEvents.some(function(eventObj){return eventObj.eventName.trim()===trimmedEventName;});}return false;}// Whitelist is chosen for filtering events
1773
+ case'whitelistedEvents':{if(!isValidEventName(eventName)){return true;}var _trimmedEventName=eventName.trim();if(Array.isArray(whitelistedEvents)){return !whitelistedEvents.some(function(eventObj){return eventObj.eventName.trim()===_trimmedEventName;});}return true;}case'disable':default:return false;}};var sendEventToDestination=function sendEventToDestination(item,dest,errorHandler,logger){var methodName=item.type.toString();try{var _dest$instance,_dest$instance$method;// Destinations expect the event to be wrapped under the `message` key
1774
+ // This will remain until we update the destinations to accept the event directly
1775
+ (_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0||_dest$instance$method.call(_dest$instance,{message:item});}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,NATIVE_DESTINATION_QUEUE_PLUGIN,DESTINATION_EVENT_FORWARDING_ERROR(dest.userFriendlyId));}};
1776
+
1777
+ var pluginName$5='NativeDestinationQueue';var NativeDestinationQueue=function NativeDestinationQueue(){return {name:pluginName$5,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$5]);},destinationsEventsQueue:{/**
1778
+ * Initialize the queue for delivery to destinations
1779
+ * @param state Application state
1780
+ * @param pluginsManager PluginsManager instance
1781
+ * @param storeManager StoreManager instance
1782
+ * @param errorHandler Error handler instance
1783
+ * @param logger Logger instance
1784
+ * @returns IQueue instance
1785
+ */init:function init(state,pluginsManager,storeManager,dmtQueue,errorHandler,logger){var finalQOpts=getNormalizedQueueOptions$1(state.loadOptions.value.destinationsQueueOptions);var writeKey=state.lifecycle.writeKey.value;var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1786
+ "".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(rudderEvent,done){var destinationsToSend=filterDestinations(rudderEvent.integrations,state.nativeDestinations.initializedDestinations.value);// list of destinations which are enable for DMT
1787
+ var destWithTransformationEnabled=[];var clonedRudderEvent=clone$1(rudderEvent);destinationsToSend.forEach(function(dest){var sendEvent=!isEventDenyListed(clonedRudderEvent.type,clonedRudderEvent.event,dest);if(!sendEvent){logger===null||logger===void 0||logger.warn(DESTINATION_EVENT_FILTERING_WARNING(NATIVE_DESTINATION_QUEUE_PLUGIN,clonedRudderEvent.event,dest.userFriendlyId));return;}if(dest.shouldApplyDeviceModeTransformation){destWithTransformationEnabled.push(dest);}else {sendEventToDestination(clonedRudderEvent,dest,errorHandler);}});if(destWithTransformationEnabled.length>0){pluginsManager.invokeSingle('transformEvent.enqueue',state,dmtQueue,clonedRudderEvent,destWithTransformationEnabled,errorHandler,logger);}// Mark success always
1788
+ done(null);},storeManager,MEMORY_STORAGE);// TODO: This seems to not work as expected. Need to investigate
1789
+ // effect(() => {
1790
+ // if (state.nativeDestinations.clientDestinationsReady.value === true) {
1791
+ // eventsQueue.start();
1792
+ // }
1793
+ // });
1794
+ return eventsQueue;},/**
1795
+ * Add event to the queue for delivery to destinations
1796
+ * @param state Application state
1797
+ * @param eventsQueue IQueue instance
1798
+ * @param event RudderEvent object
1799
+ * @param errorHandler Error handler instance
1800
+ * @param logger Logger instance
1801
+ * @returns none
1802
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){eventsQueue.addItem(event);},/**
1803
+ * This extension point is used to directly send the transformed event to the destination
1804
+ * @param state Application state
1805
+ * @param event RudderEvent Object
1806
+ * @param destination Destination Object
1807
+ * @param errorHandler Error handler instance
1808
+ * @param logger Logger instance
1809
+ */enqueueEventToDestination:function enqueueEventToDestination(state,event,destination,errorHandler,logger){sendEventToDestination(event,destination,errorHandler);}}};};
1810
+
1811
+ var ONETRUST_ACCESS_ERROR=function ONETRUST_ACCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to access OneTrust SDK resources. Please ensure that the OneTrust SDK is loaded successfully before RudderStack SDK.");};var DESTINATION_CONSENT_STATUS_ERROR="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1812
+
1813
+ var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
1814
+
1815
+ var pluginName$4='OneTrustConsentManager';var OneTrustConsentManager=function OneTrustConsentManager(){return {name:pluginName$4,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$4]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1816
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===void 0||logger.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));state.consents.initialized.value=false;return;}// OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with
1817
+ // the cookie categories Ids that the user has consented to.
1818
+ // Eg: ',C0001,C0003,'
1819
+ // We split it and save it as an array.
1820
+ var allowedConsentIds=globalThis.OnetrustActiveGroups.split(',').filter(function(n){return n;});var allowedConsents={};var deniedConsentIds=[];// Get the groups (cookie categorization), user has created in OneTrust account.
1821
+ var oneTrustAllGroupsInfo=globalThis.OneTrust.GetDomainData().Groups;oneTrustAllGroupsInfo.forEach(function(group){var CustomGroupId=group.CustomGroupId,GroupName=group.GroupName;if(allowedConsentIds.includes(CustomGroupId)){allowedConsents[CustomGroupId]=GroupName;}else {deniedConsentIds.push(CustomGroupId);}});state.consents.initialized.value=true;// In case of OneTrust, as we still support both category names and IDs, the allowed consents
1822
+ // are stored as an object with key as the category ID and value as the category name.
1823
+ state.consents.data.value={allowedConsentIds:allowedConsents,deniedConsentIds:deniedConsentIds};},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsents=state.consents.data.value.allowedConsentIds;try{// mapping of the destination with the consent group name
1824
+ var oneTrustCookieCategories=destConfig.oneTrustCookieCategories,consentManagement=destConfig.consentManagement;var allowedConsentIds=Object.keys(allowedConsents);var allowedConsentNames=Object.values(allowedConsents);// Match the consent in both IDs and names
1825
+ var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent)||allowedConsentNames.includes(consent);};// Generic consent management
1826
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1827
+ var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
1828
+ if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
1829
+ // the configured resolution strategy
1830
+ switch(state.consents.resolutionStrategy.value){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1831
+ // TODO: To be removed once the source config API is updated to support generic consent management
1832
+ }else if(oneTrustCookieCategories){// Change the structure of oneTrustConsentGroup as an array and filter values if empty string
1833
+ // Eg:
1834
+ // ["Performance Cookies", "Functional Cookies"]
1835
+ var _configuredConsents=oneTrustCookieCategories.map(function(c){return c.oneTrustCookieCategory.trim();}).filter(function(n){return n;});// Check if all the destination's mapped cookie categories are consented by the user in the browser.
1836
+ return _configuredConsents.every(matchPredicate);}// If there are no consents configured for the destination for the current provider, events should be sent.
1837
+ return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,ONETRUST_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
1838
+
1839
+ var pluginName$3='StorageEncryption';var StorageEncryption=function StorageEncryption(){return {name:pluginName$3,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$3]);},storage:{encrypt:function encrypt(value){return encrypt$1(value);},decrypt:function decrypt(value){return decrypt$1(value);}}};};
1840
+
1841
+ var _ref,_ref2,_ref3,_ref4,_ref5;/* eslint-disable no-use-before-define */var crypto$1=((_ref=typeof globalThis!='undefined'?globalThis:void 0)===null||_ref===void 0?void 0:_ref.crypto)||((_ref2=typeof global!='undefined'?global:void 0)===null||_ref2===void 0?void 0:_ref2.crypto)||((_ref3=typeof window!='undefined'?window:void 0)===null||_ref3===void 0?void 0:_ref3.crypto)||((_ref4=typeof self!='undefined'?self:void 0)===null||_ref4===void 0?void 0:_ref4.crypto)||((_ref5=typeof frames!='undefined'?frames:void 0)===null||_ref5===void 0||(_ref5=_ref5[0])===null||_ref5===void 0?void 0:_ref5.crypto);var randomWordArray;if(crypto$1){randomWordArray=function randomWordArray(nBytes){var words=[];for(var i=0,rcache;i<nBytes;i+=4){words.push(crypto$1.getRandomValues(new Uint32Array(1))[0]);}return new WordArray(words,nBytes);};}else {// Because there is no global crypto property in this context, cryptographically unsafe Math.random() is used.
1842
+ randomWordArray=function randomWordArray(nBytes){var words=[];var r=function r(m_w){var _m_w=m_w;var _m_z=0x3ade68b1;var mask=0xffffffff;return function(){_m_z=0x9069*(_m_z&0xFFFF)+(_m_z>>0x10)&mask;_m_w=0x4650*(_m_w&0xFFFF)+(_m_w>>0x10)&mask;var result=(_m_z<<0x10)+_m_w&mask;result/=0x100000000;result+=0.5;return result*(Math.random()>0.5?1:-1);};};for(var i=0,rcache;i<nBytes;i+=4){var _r=r((rcache||Math.random())*0x100000000);rcache=_r()*0x3ade67b7;words.push(_r()*0x100000000|0);}return new WordArray(words,nBytes);};}/**
1843
+ * Base class for inheritance.
1844
+ */var Base=/*#__PURE__*/function(){function Base(){_classCallCheck(this,Base);}_createClass(Base,[{key:"mixIn",value:/**
1845
+ * Copies properties into this object.
1846
+ *
1847
+ * @param {Object} properties The properties to mix in.
1848
+ *
1849
+ * @example
1850
+ *
1851
+ * MyType.mixIn({
1852
+ * field: 'value'
1853
+ * });
1854
+ */function mixIn(properties){return Object.assign(this,properties);}/**
1855
+ * Creates a copy of this object.
1856
+ *
1857
+ * @return {Object} The clone.
1858
+ *
1859
+ * @example
1860
+ *
1861
+ * var clone = instance.clone();
1862
+ */},{key:"clone",value:function clone(){var clone=new this.constructor();Object.assign(clone,this);return clone;}}],[{key:"create",value:/**
1863
+ * Extends this object and runs the init method.
1864
+ * Arguments to create() will be passed to init().
1865
+ *
1866
+ * @return {Object} The new object.
1867
+ *
1868
+ * @static
1869
+ *
1870
+ * @example
1871
+ *
1872
+ * var instance = MyType.create();
1873
+ */function create(){for(var _len=arguments.length,args=new Array(_len),_key2=0;_key2<_len;_key2++){args[_key2]=arguments[_key2];}return _construct(this,args);}}]);return Base;}();/**
1874
+ * An array of 32-bit words.
1875
+ *
1876
+ * @property {Array} words The array of 32-bit words.
1877
+ * @property {number} sigBytes The number of significant bytes in this word array.
1878
+ */var WordArray=/*#__PURE__*/function(_Base){_inherits(WordArray,_Base);var _super=_createSuper(WordArray);/**
1879
+ * Initializes a newly created word array.
1880
+ *
1881
+ * @param {Array} words (Optional) An array of 32-bit words.
1882
+ * @param {number} sigBytes (Optional) The number of significant bytes in the words.
1883
+ *
1884
+ * @example
1885
+ *
1886
+ * var wordArray = CryptoJS.lib.WordArray.create();
1887
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
1888
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
1889
+ */function WordArray(){var _this;var words=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var sigBytes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:words.length*4;_classCallCheck(this,WordArray);_this=_super.call(this);var typedArray=words;// Convert buffers to uint8
1890
+ if(typedArray instanceof ArrayBuffer){typedArray=new Uint8Array(typedArray);}// Convert other array views to uint8
1891
+ if(typedArray instanceof Int8Array||typedArray instanceof Uint8ClampedArray||typedArray instanceof Int16Array||typedArray instanceof Uint16Array||typedArray instanceof Int32Array||typedArray instanceof Uint32Array||typedArray instanceof Float32Array||typedArray instanceof Float64Array){typedArray=new Uint8Array(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength);}// Handle Uint8Array
1892
+ if(typedArray instanceof Uint8Array){// Shortcut
1893
+ var typedArrayByteLength=typedArray.byteLength;// Extract bytes
1894
+ var _words=[];for(var i=0;i<typedArrayByteLength;i+=1){_words[i>>>2]|=typedArray[i]<<24-i%4*8;}// Initialize this word array
1895
+ _this.words=_words;_this.sigBytes=typedArrayByteLength;}else {// Else call normal init
1896
+ _this.words=words;_this.sigBytes=sigBytes;}return _this;}/**
1897
+ * Creates a word array filled with random bytes.
1898
+ *
1899
+ * @param {number} nBytes The number of random bytes to generate.
1900
+ *
1901
+ * @return {WordArray} The random word array.
1902
+ *
1903
+ * @static
1904
+ *
1905
+ * @example
1906
+ *
1907
+ * var wordArray = CryptoJS.lib.WordArray.random(16);
1908
+ */_createClass(WordArray,[{key:"toString",value:/**
1909
+ * Converts this word array to a string.
1910
+ *
1911
+ * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
1912
+ *
1913
+ * @return {string} The stringified word array.
1914
+ *
1915
+ * @example
1916
+ *
1917
+ * var string = wordArray + '';
1918
+ * var string = wordArray.toString();
1919
+ * var string = wordArray.toString(CryptoJS.enc.Utf8);
1920
+ */function toString(){var encoder=arguments.length>0&&arguments[0]!==undefined?arguments[0]:Hex;return encoder.stringify(this);}/**
1921
+ * Concatenates a word array to this word array.
1922
+ *
1923
+ * @param {WordArray} wordArray The word array to append.
1924
+ *
1925
+ * @return {WordArray} This word array.
1926
+ *
1927
+ * @example
1928
+ *
1929
+ * wordArray1.concat(wordArray2);
1930
+ */},{key:"concat",value:function concat(wordArray){// Shortcuts
1931
+ var thisWords=this.words;var thatWords=wordArray.words;var thisSigBytes=this.sigBytes;var thatSigBytes=wordArray.sigBytes;// Clamp excess bits
1932
+ this.clamp();// Concat
1933
+ if(thisSigBytes%4){// Copy one byte at a time
1934
+ for(var i=0;i<thatSigBytes;i+=1){var thatByte=thatWords[i>>>2]>>>24-i%4*8&0xff;thisWords[thisSigBytes+i>>>2]|=thatByte<<24-(thisSigBytes+i)%4*8;}}else {// Copy one word at a time
1935
+ for(var _i=0;_i<thatSigBytes;_i+=4){thisWords[thisSigBytes+_i>>>2]=thatWords[_i>>>2];}}this.sigBytes+=thatSigBytes;// Chainable
1936
+ return this;}/**
1937
+ * Removes insignificant bits.
1938
+ *
1939
+ * @example
1940
+ *
1941
+ * wordArray.clamp();
1942
+ */},{key:"clamp",value:function clamp(){// Shortcuts
1943
+ var words=this.words,sigBytes=this.sigBytes;// Clamp
1944
+ words[sigBytes>>>2]&=0xffffffff<<32-sigBytes%4*8;words.length=Math.ceil(sigBytes/4);}/**
1945
+ * Creates a copy of this word array.
1946
+ *
1947
+ * @return {WordArray} The clone.
1948
+ *
1949
+ * @example
1950
+ *
1951
+ * var clone = wordArray.clone();
1952
+ */},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(WordArray.prototype),"clone",this).call(this);clone.words=this.words.slice(0);return clone;}}]);return WordArray;}(Base);/**
1953
+ * Hex encoding strategy.
1954
+ */_defineProperty(WordArray,"random",randomWordArray);var Hex={/**
1955
+ * Converts a word array to a hex string.
1956
+ *
1957
+ * @param {WordArray} wordArray The word array.
1958
+ *
1959
+ * @return {string} The hex string.
1960
+ *
1961
+ * @static
1962
+ *
1963
+ * @example
1964
+ *
1965
+ * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
1966
+ */stringify:function stringify(wordArray){// Shortcuts
1967
+ var words=wordArray.words,sigBytes=wordArray.sigBytes;// Convert
1968
+ var hexChars=[];for(var i=0;i<sigBytes;i+=1){var bite=words[i>>>2]>>>24-i%4*8&0xff;hexChars.push((bite>>>4).toString(16));hexChars.push((bite&0x0f).toString(16));}return hexChars.join('');},/**
1969
+ * Converts a hex string to a word array.
1970
+ *
1971
+ * @param {string} hexStr The hex string.
1972
+ *
1973
+ * @return {WordArray} The word array.
1974
+ *
1975
+ * @static
1976
+ *
1977
+ * @example
1978
+ *
1979
+ * var wordArray = CryptoJS.enc.Hex.parse(hexString);
1980
+ */parse:function parse(hexStr){// Shortcut
1981
+ var hexStrLength=hexStr.length;// Convert
1982
+ var words=[];for(var i=0;i<hexStrLength;i+=2){words[i>>>3]|=parseInt(hexStr.substr(i,2),16)<<24-i%8*4;}return new WordArray(words,hexStrLength/2);}};/**
1983
+ * Latin1 encoding strategy.
1984
+ */var Latin1={/**
1985
+ * Converts a word array to a Latin1 string.
1986
+ *
1987
+ * @param {WordArray} wordArray The word array.
1988
+ *
1989
+ * @return {string} The Latin1 string.
1990
+ *
1991
+ * @static
1992
+ *
1993
+ * @example
1994
+ *
1995
+ * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
1996
+ */stringify:function stringify(wordArray){// Shortcuts
1997
+ var words=wordArray.words,sigBytes=wordArray.sigBytes;// Convert
1998
+ var latin1Chars=[];for(var i=0;i<sigBytes;i+=1){var bite=words[i>>>2]>>>24-i%4*8&0xff;latin1Chars.push(String.fromCharCode(bite));}return latin1Chars.join('');},/**
1999
+ * Converts a Latin1 string to a word array.
2000
+ *
2001
+ * @param {string} latin1Str The Latin1 string.
2002
+ *
2003
+ * @return {WordArray} The word array.
2004
+ *
2005
+ * @static
2006
+ *
2007
+ * @example
2008
+ *
2009
+ * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
2010
+ */parse:function parse(latin1Str){// Shortcut
2011
+ var latin1StrLength=latin1Str.length;// Convert
2012
+ var words=[];for(var i=0;i<latin1StrLength;i+=1){words[i>>>2]|=(latin1Str.charCodeAt(i)&0xff)<<24-i%4*8;}return new WordArray(words,latin1StrLength);}};/**
2013
+ * UTF-8 encoding strategy.
2014
+ */var Utf8={/**
2015
+ * Converts a word array to a UTF-8 string.
2016
+ *
2017
+ * @param {WordArray} wordArray The word array.
2018
+ *
2019
+ * @return {string} The UTF-8 string.
2020
+ *
2021
+ * @static
2022
+ *
2023
+ * @example
2024
+ *
2025
+ * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
2026
+ */stringify:function stringify(wordArray){try{return decodeURIComponent(escape(Latin1.stringify(wordArray)));}catch(e){throw new Error('Malformed UTF-8 data');}},/**
2027
+ * Converts a UTF-8 string to a word array.
2028
+ *
2029
+ * @param {string} utf8Str The UTF-8 string.
2030
+ *
2031
+ * @return {WordArray} The word array.
2032
+ *
2033
+ * @static
2034
+ *
2035
+ * @example
2036
+ *
2037
+ * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
2038
+ */parse:function parse(utf8Str){return Latin1.parse(unescape(encodeURIComponent(utf8Str)));}};/**
2039
+ * Abstract buffered block algorithm template.
2040
+ *
2041
+ * The property blockSize must be implemented in a concrete subtype.
2042
+ *
2043
+ * @property {number} _minBufferSize
2044
+ *
2045
+ * The number of blocks that should be kept unprocessed in the buffer. Default: 0
2046
+ */var BufferedBlockAlgorithm=/*#__PURE__*/function(_Base2){_inherits(BufferedBlockAlgorithm,_Base2);var _super2=_createSuper(BufferedBlockAlgorithm);function BufferedBlockAlgorithm(){var _this2;_classCallCheck(this,BufferedBlockAlgorithm);_this2=_super2.call(this);_this2._minBufferSize=0;return _this2;}/**
2047
+ * Resets this block algorithm's data buffer to its initial state.
2048
+ *
2049
+ * @example
2050
+ *
2051
+ * bufferedBlockAlgorithm.reset();
2052
+ */_createClass(BufferedBlockAlgorithm,[{key:"reset",value:function reset(){// Initial values
2053
+ this._data=new WordArray();this._nDataBytes=0;}/**
2054
+ * Adds new data to this block algorithm's buffer.
2055
+ *
2056
+ * @param {WordArray|string} data
2057
+ *
2058
+ * The data to append. Strings are converted to a WordArray using UTF-8.
2059
+ *
2060
+ * @example
2061
+ *
2062
+ * bufferedBlockAlgorithm._append('data');
2063
+ * bufferedBlockAlgorithm._append(wordArray);
2064
+ */},{key:"_append",value:function _append(data){var m_data=data;// Convert string to WordArray, else assume WordArray already
2065
+ if(typeof m_data==='string'){m_data=Utf8.parse(m_data);}// Append
2066
+ this._data.concat(m_data);this._nDataBytes+=m_data.sigBytes;}/**
2067
+ * Processes available data blocks.
2068
+ *
2069
+ * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
2070
+ *
2071
+ * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
2072
+ *
2073
+ * @return {WordArray} The processed data.
2074
+ *
2075
+ * @example
2076
+ *
2077
+ * var processedData = bufferedBlockAlgorithm._process();
2078
+ * var processedData = bufferedBlockAlgorithm._process(!!'flush');
2079
+ */},{key:"_process",value:function _process(doFlush){var processedWords;// Shortcuts
2080
+ var data=this._data,blockSize=this.blockSize;var dataWords=data.words;var dataSigBytes=data.sigBytes;var blockSizeBytes=blockSize*4;// Count blocks ready
2081
+ var nBlocksReady=dataSigBytes/blockSizeBytes;if(doFlush){// Round up to include partial blocks
2082
+ nBlocksReady=Math.ceil(nBlocksReady);}else {// Round down to include only full blocks,
2083
+ // less the number of blocks that must remain in the buffer
2084
+ nBlocksReady=Math.max((nBlocksReady|0)-this._minBufferSize,0);}// Count words ready
2085
+ var nWordsReady=nBlocksReady*blockSize;// Count bytes ready
2086
+ var nBytesReady=Math.min(nWordsReady*4,dataSigBytes);// Process blocks
2087
+ if(nWordsReady){for(var offset=0;offset<nWordsReady;offset+=blockSize){// Perform concrete-algorithm logic
2088
+ this._doProcessBlock(dataWords,offset);}// Remove processed words
2089
+ processedWords=dataWords.splice(0,nWordsReady);data.sigBytes-=nBytesReady;}// Return processed words
2090
+ return new WordArray(processedWords,nBytesReady);}/**
2091
+ * Creates a copy of this object.
2092
+ *
2093
+ * @return {Object} The clone.
2094
+ *
2095
+ * @example
2096
+ *
2097
+ * var clone = bufferedBlockAlgorithm.clone();
2098
+ */},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(BufferedBlockAlgorithm.prototype),"clone",this).call(this);clone._data=this._data.clone();return clone;}}]);return BufferedBlockAlgorithm;}(Base);/**
2099
+ * Abstract hasher template.
2100
+ *
2101
+ * @property {number} blockSize
2102
+ *
2103
+ * The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
2104
+ */var Hasher=/*#__PURE__*/function(_BufferedBlockAlgorit){_inherits(Hasher,_BufferedBlockAlgorit);var _super3=_createSuper(Hasher);function Hasher(cfg){var _this3;_classCallCheck(this,Hasher);_this3=_super3.call(this);_this3.blockSize=512/32;/**
2105
+ * Configuration options.
2106
+ */_this3.cfg=Object.assign(new Base(),cfg);// Set initial values
2107
+ _this3.reset();return _this3;}/**
2108
+ * Creates a shortcut function to a hasher's object interface.
2109
+ *
2110
+ * @param {Hasher} SubHasher The hasher to create a helper for.
2111
+ *
2112
+ * @return {Function} The shortcut function.
2113
+ *
2114
+ * @static
2115
+ *
2116
+ * @example
2117
+ *
2118
+ * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
2119
+ */_createClass(Hasher,[{key:"reset",value:/**
2120
+ * Resets this hasher to its initial state.
2121
+ *
2122
+ * @example
2123
+ *
2124
+ * hasher.reset();
2125
+ */function reset(){// Reset data buffer
2126
+ _get(_getPrototypeOf(Hasher.prototype),"reset",this).call(this);// Perform concrete-hasher logic
2127
+ this._doReset();}/**
2128
+ * Updates this hasher with a message.
2129
+ *
2130
+ * @param {WordArray|string} messageUpdate The message to append.
2131
+ *
2132
+ * @return {Hasher} This hasher.
2133
+ *
2134
+ * @example
2135
+ *
2136
+ * hasher.update('message');
2137
+ * hasher.update(wordArray);
2138
+ */},{key:"update",value:function update(messageUpdate){// Append
2139
+ this._append(messageUpdate);// Update the hash
2140
+ this._process();// Chainable
2141
+ return this;}/**
2142
+ * Finalizes the hash computation.
2143
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2144
+ *
2145
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
2146
+ *
2147
+ * @return {WordArray} The hash.
2148
+ *
2149
+ * @example
2150
+ *
2151
+ * var hash = hasher.finalize();
2152
+ * var hash = hasher.finalize('message');
2153
+ * var hash = hasher.finalize(wordArray);
2154
+ */},{key:"finalize",value:function finalize(messageUpdate){// Final message update
2155
+ if(messageUpdate){this._append(messageUpdate);}// Perform concrete-hasher logic
2156
+ var hash=this._doFinalize();return hash;}}],[{key:"_createHelper",value:function _createHelper(SubHasher){return function(message,cfg){return new SubHasher(cfg).finalize(message);};}/**
2157
+ * Creates a shortcut function to the HMAC's object interface.
2158
+ *
2159
+ * @param {Hasher} SubHasher The hasher to use in this HMAC helper.
2160
+ *
2161
+ * @return {Function} The shortcut function.
2162
+ *
2163
+ * @static
2164
+ *
2165
+ * @example
2166
+ *
2167
+ * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
2168
+ */},{key:"_createHmacHelper",value:function _createHmacHelper(SubHasher){return function(message,key){return new HMAC(SubHasher,key).finalize(message);};}}]);return Hasher;}(BufferedBlockAlgorithm);/**
2169
+ * HMAC algorithm.
2170
+ */var HMAC=/*#__PURE__*/function(_Base3){_inherits(HMAC,_Base3);var _super4=_createSuper(HMAC);/**
2171
+ * Initializes a newly created HMAC.
2172
+ *
2173
+ * @param {Hasher} SubHasher The hash algorithm to use.
2174
+ * @param {WordArray|string} key The secret key.
2175
+ *
2176
+ * @example
2177
+ *
2178
+ * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
2179
+ */function HMAC(SubHasher,key){var _this4;_classCallCheck(this,HMAC);_this4=_super4.call(this);var hasher=new SubHasher();_this4._hasher=hasher;// Convert string to WordArray, else assume WordArray already
2180
+ var _key=key;if(typeof _key==='string'){_key=Utf8.parse(_key);}// Shortcuts
2181
+ var hasherBlockSize=hasher.blockSize;var hasherBlockSizeBytes=hasherBlockSize*4;// Allow arbitrary length keys
2182
+ if(_key.sigBytes>hasherBlockSizeBytes){_key=hasher.finalize(key);}// Clamp excess bits
2183
+ _key.clamp();// Clone key for inner and outer pads
2184
+ var oKey=_key.clone();_this4._oKey=oKey;var iKey=_key.clone();_this4._iKey=iKey;// Shortcuts
2185
+ var oKeyWords=oKey.words;var iKeyWords=iKey.words;// XOR keys with pad constants
2186
+ for(var i=0;i<hasherBlockSize;i+=1){oKeyWords[i]^=0x5c5c5c5c;iKeyWords[i]^=0x36363636;}oKey.sigBytes=hasherBlockSizeBytes;iKey.sigBytes=hasherBlockSizeBytes;// Set initial values
2187
+ _this4.reset();return _this4;}/**
2188
+ * Resets this HMAC to its initial state.
2189
+ *
2190
+ * @example
2191
+ *
2192
+ * hmacHasher.reset();
2193
+ */_createClass(HMAC,[{key:"reset",value:function reset(){// Shortcut
2194
+ var hasher=this._hasher;// Reset
2195
+ hasher.reset();hasher.update(this._iKey);}/**
2196
+ * Updates this HMAC with a message.
2197
+ *
2198
+ * @param {WordArray|string} messageUpdate The message to append.
2199
+ *
2200
+ * @return {HMAC} This HMAC instance.
2201
+ *
2202
+ * @example
2203
+ *
2204
+ * hmacHasher.update('message');
2205
+ * hmacHasher.update(wordArray);
2206
+ */},{key:"update",value:function update(messageUpdate){this._hasher.update(messageUpdate);// Chainable
2207
+ return this;}/**
2208
+ * Finalizes the HMAC computation.
2209
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2210
+ *
2211
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
2212
+ *
2213
+ * @return {WordArray} The HMAC.
2214
+ *
2215
+ * @example
2216
+ *
2217
+ * var hmac = hmacHasher.finalize();
2218
+ * var hmac = hmacHasher.finalize('message');
2219
+ * var hmac = hmacHasher.finalize(wordArray);
2220
+ */},{key:"finalize",value:function finalize(messageUpdate){// Shortcut
2221
+ var hasher=this._hasher;// Compute HMAC
2222
+ var innerHash=hasher.finalize(messageUpdate);hasher.reset();var hmac=hasher.finalize(this._oKey.clone().concat(innerHash));return hmac;}}]);return HMAC;}(Base);
2223
+
2224
+ var parseLoop=function parseLoop(base64Str,base64StrLength,reverseMap){var words=[];var nBytes=0;for(var i=0;i<base64StrLength;i+=1){if(i%4){var bits1=reverseMap[base64Str.charCodeAt(i-1)]<<i%4*2;var bits2=reverseMap[base64Str.charCodeAt(i)]>>>6-i%4*2;var bitsCombined=bits1|bits2;words[nBytes>>>2]|=bitsCombined<<24-nBytes%4*8;nBytes+=1;}}return WordArray.create(words,nBytes);};/**
2225
+ * Base64 encoding strategy.
2226
+ */var Base64={/**
2227
+ * Converts a word array to a Base64 string.
2228
+ *
2229
+ * @param {WordArray} wordArray The word array.
2230
+ *
2231
+ * @return {string} The Base64 string.
2232
+ *
2233
+ * @static
2234
+ *
2235
+ * @example
2236
+ *
2237
+ * const base64String = CryptoJS.enc.Base64.stringify(wordArray);
2238
+ */stringify:function stringify(wordArray){// Shortcuts
2239
+ var words=wordArray.words,sigBytes=wordArray.sigBytes;var map=this._map;// Clamp excess bits
2240
+ wordArray.clamp();// Convert
2241
+ var base64Chars=[];for(var i=0;i<sigBytes;i+=3){var byte1=words[i>>>2]>>>24-i%4*8&0xff;var byte2=words[i+1>>>2]>>>24-(i+1)%4*8&0xff;var byte3=words[i+2>>>2]>>>24-(i+2)%4*8&0xff;var triplet=byte1<<16|byte2<<8|byte3;for(var j=0;j<4&&i+j*0.75<sigBytes;j+=1){base64Chars.push(map.charAt(triplet>>>6*(3-j)&0x3f));}}// Add padding
2242
+ var paddingChar=map.charAt(64);if(paddingChar){while(base64Chars.length%4){base64Chars.push(paddingChar);}}return base64Chars.join('');},/**
2243
+ * Converts a Base64 string to a word array.
2244
+ *
2245
+ * @param {string} base64Str The Base64 string.
2246
+ *
2247
+ * @return {WordArray} The word array.
2248
+ *
2249
+ * @static
2250
+ *
2251
+ * @example
2252
+ *
2253
+ * const wordArray = CryptoJS.enc.Base64.parse(base64String);
2254
+ */parse:function parse(base64Str){// Shortcuts
2255
+ var base64StrLength=base64Str.length;var map=this._map;var reverseMap=this._reverseMap;if(!reverseMap){this._reverseMap=[];reverseMap=this._reverseMap;for(var j=0;j<map.length;j+=1){reverseMap[map.charCodeAt(j)]=j;}}// Ignore padding
2256
+ var paddingChar=map.charAt(64);if(paddingChar){var paddingIndex=base64Str.indexOf(paddingChar);if(paddingIndex!==-1){base64StrLength=paddingIndex;}}// Convert
2257
+ return parseLoop(base64Str,base64StrLength,reverseMap);},_map:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='};
2258
+
2259
+ var T=[];// Compute constants
2260
+ for(var i$1=0;i$1<64;i$1+=1){T[i$1]=Math.abs(Math.sin(i$1+1))*0x100000000|0;}var FF=function FF(a,b,c,d,x,s,t){var n=a+(b&c|~b&d)+x+t;return (n<<s|n>>>32-s)+b;};var GG=function GG(a,b,c,d,x,s,t){var n=a+(b&d|c&~d)+x+t;return (n<<s|n>>>32-s)+b;};var HH=function HH(a,b,c,d,x,s,t){var n=a+(b^c^d)+x+t;return (n<<s|n>>>32-s)+b;};var II=function II(a,b,c,d,x,s,t){var n=a+(c^(b|~d))+x+t;return (n<<s|n>>>32-s)+b;};/**
2261
+ * MD5 hash algorithm.
2262
+ */var MD5Algo=/*#__PURE__*/function(_Hasher){_inherits(MD5Algo,_Hasher);var _super=_createSuper(MD5Algo);function MD5Algo(){_classCallCheck(this,MD5Algo);return _super.apply(this,arguments);}_createClass(MD5Algo,[{key:"_doReset",value:function _doReset(){this._hash=new WordArray([0x67452301,0xefcdab89,0x98badcfe,0x10325476]);}},{key:"_doProcessBlock",value:function _doProcessBlock(M,offset){var _M=M;// Swap endian
2263
+ for(var _i=0;_i<16;_i+=1){// Shortcuts
2264
+ var offset_i=offset+_i;var M_offset_i=M[offset_i];_M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&0x00ff00ff|(M_offset_i<<24|M_offset_i>>>8)&0xff00ff00;}// Shortcuts
2265
+ var H=this._hash.words;var M_offset_0=_M[offset+0];var M_offset_1=_M[offset+1];var M_offset_2=_M[offset+2];var M_offset_3=_M[offset+3];var M_offset_4=_M[offset+4];var M_offset_5=_M[offset+5];var M_offset_6=_M[offset+6];var M_offset_7=_M[offset+7];var M_offset_8=_M[offset+8];var M_offset_9=_M[offset+9];var M_offset_10=_M[offset+10];var M_offset_11=_M[offset+11];var M_offset_12=_M[offset+12];var M_offset_13=_M[offset+13];var M_offset_14=_M[offset+14];var M_offset_15=_M[offset+15];// Working varialbes
2266
+ var a=H[0];var b=H[1];var c=H[2];var d=H[3];// Computation
2267
+ a=FF(a,b,c,d,M_offset_0,7,T[0]);d=FF(d,a,b,c,M_offset_1,12,T[1]);c=FF(c,d,a,b,M_offset_2,17,T[2]);b=FF(b,c,d,a,M_offset_3,22,T[3]);a=FF(a,b,c,d,M_offset_4,7,T[4]);d=FF(d,a,b,c,M_offset_5,12,T[5]);c=FF(c,d,a,b,M_offset_6,17,T[6]);b=FF(b,c,d,a,M_offset_7,22,T[7]);a=FF(a,b,c,d,M_offset_8,7,T[8]);d=FF(d,a,b,c,M_offset_9,12,T[9]);c=FF(c,d,a,b,M_offset_10,17,T[10]);b=FF(b,c,d,a,M_offset_11,22,T[11]);a=FF(a,b,c,d,M_offset_12,7,T[12]);d=FF(d,a,b,c,M_offset_13,12,T[13]);c=FF(c,d,a,b,M_offset_14,17,T[14]);b=FF(b,c,d,a,M_offset_15,22,T[15]);a=GG(a,b,c,d,M_offset_1,5,T[16]);d=GG(d,a,b,c,M_offset_6,9,T[17]);c=GG(c,d,a,b,M_offset_11,14,T[18]);b=GG(b,c,d,a,M_offset_0,20,T[19]);a=GG(a,b,c,d,M_offset_5,5,T[20]);d=GG(d,a,b,c,M_offset_10,9,T[21]);c=GG(c,d,a,b,M_offset_15,14,T[22]);b=GG(b,c,d,a,M_offset_4,20,T[23]);a=GG(a,b,c,d,M_offset_9,5,T[24]);d=GG(d,a,b,c,M_offset_14,9,T[25]);c=GG(c,d,a,b,M_offset_3,14,T[26]);b=GG(b,c,d,a,M_offset_8,20,T[27]);a=GG(a,b,c,d,M_offset_13,5,T[28]);d=GG(d,a,b,c,M_offset_2,9,T[29]);c=GG(c,d,a,b,M_offset_7,14,T[30]);b=GG(b,c,d,a,M_offset_12,20,T[31]);a=HH(a,b,c,d,M_offset_5,4,T[32]);d=HH(d,a,b,c,M_offset_8,11,T[33]);c=HH(c,d,a,b,M_offset_11,16,T[34]);b=HH(b,c,d,a,M_offset_14,23,T[35]);a=HH(a,b,c,d,M_offset_1,4,T[36]);d=HH(d,a,b,c,M_offset_4,11,T[37]);c=HH(c,d,a,b,M_offset_7,16,T[38]);b=HH(b,c,d,a,M_offset_10,23,T[39]);a=HH(a,b,c,d,M_offset_13,4,T[40]);d=HH(d,a,b,c,M_offset_0,11,T[41]);c=HH(c,d,a,b,M_offset_3,16,T[42]);b=HH(b,c,d,a,M_offset_6,23,T[43]);a=HH(a,b,c,d,M_offset_9,4,T[44]);d=HH(d,a,b,c,M_offset_12,11,T[45]);c=HH(c,d,a,b,M_offset_15,16,T[46]);b=HH(b,c,d,a,M_offset_2,23,T[47]);a=II(a,b,c,d,M_offset_0,6,T[48]);d=II(d,a,b,c,M_offset_7,10,T[49]);c=II(c,d,a,b,M_offset_14,15,T[50]);b=II(b,c,d,a,M_offset_5,21,T[51]);a=II(a,b,c,d,M_offset_12,6,T[52]);d=II(d,a,b,c,M_offset_3,10,T[53]);c=II(c,d,a,b,M_offset_10,15,T[54]);b=II(b,c,d,a,M_offset_1,21,T[55]);a=II(a,b,c,d,M_offset_8,6,T[56]);d=II(d,a,b,c,M_offset_15,10,T[57]);c=II(c,d,a,b,M_offset_6,15,T[58]);b=II(b,c,d,a,M_offset_13,21,T[59]);a=II(a,b,c,d,M_offset_4,6,T[60]);d=II(d,a,b,c,M_offset_11,10,T[61]);c=II(c,d,a,b,M_offset_2,15,T[62]);b=II(b,c,d,a,M_offset_9,21,T[63]);// Intermediate hash value
2268
+ H[0]=H[0]+a|0;H[1]=H[1]+b|0;H[2]=H[2]+c|0;H[3]=H[3]+d|0;}/* eslint-ensable no-param-reassign */},{key:"_doFinalize",value:function _doFinalize(){// Shortcuts
2269
+ var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;// Add padding
2270
+ dataWords[nBitsLeft>>>5]|=0x80<<24-nBitsLeft%32;var nBitsTotalH=Math.floor(nBitsTotal/0x100000000);var nBitsTotalL=nBitsTotal;dataWords[(nBitsLeft+64>>>9<<4)+15]=(nBitsTotalH<<8|nBitsTotalH>>>24)&0x00ff00ff|(nBitsTotalH<<24|nBitsTotalH>>>8)&0xff00ff00;dataWords[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotalL<<8|nBitsTotalL>>>24)&0x00ff00ff|(nBitsTotalL<<24|nBitsTotalL>>>8)&0xff00ff00;data.sigBytes=(dataWords.length+1)*4;// Hash final blocks
2271
+ this._process();// Shortcuts
2272
+ var hash=this._hash;var H=hash.words;// Swap endian
2273
+ for(var _i2=0;_i2<4;_i2+=1){// Shortcut
2274
+ var H_i=H[_i2];H[_i2]=(H_i<<8|H_i>>>24)&0x00ff00ff|(H_i<<24|H_i>>>8)&0xff00ff00;}// Return final computed hash
2275
+ return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(MD5Algo.prototype),"clone",this).call(this);clone._hash=this._hash.clone();return clone;}}]);return MD5Algo;}(Hasher);/**
2276
+ * Shortcut function to the hasher's object interface.
2277
+ *
2278
+ * @param {WordArray|string} message The message to hash.
2279
+ *
2280
+ * @return {WordArray} The hash.
2281
+ *
2282
+ * @static
2283
+ *
2284
+ * @example
2285
+ *
2286
+ * var hash = CryptoJS.MD5('message');
2287
+ * var hash = CryptoJS.MD5(wordArray);
2288
+ */Hasher._createHelper(MD5Algo);/**
2289
+ * Shortcut function to the HMAC's object interface.
2290
+ *
2291
+ * @param {WordArray|string} message The message to hash.
2292
+ * @param {WordArray|string} key The secret key.
2293
+ *
2294
+ * @return {WordArray} The HMAC.
2295
+ *
2296
+ * @static
2297
+ *
2298
+ * @example
2299
+ *
2300
+ * var hmac = CryptoJS.HmacMD5(message, key);
2301
+ */Hasher._createHmacHelper(MD5Algo);
2302
+
2303
+ /**
2304
+ * This key derivation function is meant to conform with EVP_BytesToKey.
2305
+ * www.openssl.org/docs/crypto/EVP_BytesToKey.html
2306
+ */var EvpKDFAlgo=/*#__PURE__*/function(_Base){_inherits(EvpKDFAlgo,_Base);var _super=_createSuper(EvpKDFAlgo);/**
2307
+ * Initializes a newly created key derivation function.
2308
+ *
2309
+ * @param {Object} cfg (Optional) The configuration options to use for the derivation.
2310
+ *
2311
+ * @example
2312
+ *
2313
+ * const kdf = CryptoJS.algo.EvpKDF.create();
2314
+ * const kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
2315
+ * const kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
2316
+ */function EvpKDFAlgo(cfg){var _this;_classCallCheck(this,EvpKDFAlgo);_this=_super.call(this);/**
2317
+ * Configuration options.
2318
+ *
2319
+ * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
2320
+ * @property {Hasher} hasher The hash algorithm to use. Default: MD5
2321
+ * @property {number} iterations The number of iterations to perform. Default: 1
2322
+ */_this.cfg=Object.assign(new Base(),{keySize:128/32,hasher:MD5Algo,iterations:1},cfg);return _this;}/**
2323
+ * Derives a key from a password.
2324
+ *
2325
+ * @param {WordArray|string} password The password.
2326
+ * @param {WordArray|string} salt A salt.
2327
+ *
2328
+ * @return {WordArray} The derived key.
2329
+ *
2330
+ * @example
2331
+ *
2332
+ * const key = kdf.compute(password, salt);
2333
+ */_createClass(EvpKDFAlgo,[{key:"compute",value:function compute(password,salt){var block;// Shortcut
2334
+ var cfg=this.cfg;// Init hasher
2335
+ var hasher=cfg.hasher.create();// Initial values
2336
+ var derivedKey=WordArray.create();// Shortcuts
2337
+ var derivedKeyWords=derivedKey.words;var keySize=cfg.keySize,iterations=cfg.iterations;// Generate key
2338
+ while(derivedKeyWords.length<keySize){if(block){hasher.update(block);}block=hasher.update(password).finalize(salt);hasher.reset();// Iterations
2339
+ for(var i=1;i<iterations;i+=1){block=hasher.finalize(block);hasher.reset();}derivedKey.concat(block);}derivedKey.sigBytes=keySize*4;return derivedKey;}}]);return EvpKDFAlgo;}(Base);
2340
+
2341
+ var ObjectAssign=typeof Object.assign!=="function"?function(target){if(target==null){throw new TypeError('Cannot convert undefined or null to object');}target=Object(target);for(var index=1;index<arguments.length;index++){var source=arguments[index];if(source!=null){for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}}return target;}:Object.assign;/**
2342
+ * Abstract base cipher template.
2343
+ *
2344
+ * @property {number} keySize This cipher's key size. Default: 4 (128 bits)
2345
+ * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
2346
+ * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
2347
+ * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
2348
+ */var Cipher=/*#__PURE__*/function(_BufferedBlockAlgorit){_inherits(Cipher,_BufferedBlockAlgorit);var _super=_createSuper(Cipher);/**
2349
+ * Initializes a newly created cipher.
2350
+ *
2351
+ * @param {number} xformMode Either the encryption or decryption transormation mode constant.
2352
+ * @param {WordArray} key The key.
2353
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2354
+ *
2355
+ * @example
2356
+ *
2357
+ * const cipher = CryptoJS.algo.AES.create(
2358
+ * CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }
2359
+ * );
2360
+ */function Cipher(xformMode,key,cfg){var _this;_classCallCheck(this,Cipher);_this=_super.call(this);/**
2361
+ * Configuration options.
2362
+ *
2363
+ * @property {WordArray} iv The IV to use for this operation.
2364
+ */_this.cfg=ObjectAssign(new Base(),cfg);// Store transform mode and key
2365
+ _this._xformMode=xformMode;_this._key=key;// Set initial values
2366
+ _this.reset();return _this;}/**
2367
+ * Creates this cipher in encryption mode.
2368
+ *
2369
+ * @param {WordArray} key The key.
2370
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2371
+ *
2372
+ * @return {Cipher} A cipher instance.
2373
+ *
2374
+ * @static
2375
+ *
2376
+ * @example
2377
+ *
2378
+ * const cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
2379
+ */_createClass(Cipher,[{key:"reset",value:/**
2380
+ * Resets this cipher to its initial state.
2381
+ *
2382
+ * @example
2383
+ *
2384
+ * cipher.reset();
2385
+ */function reset(){// Reset data buffer
2386
+ _get(_getPrototypeOf(Cipher.prototype),"reset",this).call(this);// Perform concrete-cipher logic
2387
+ this._doReset();}/**
2388
+ * Adds data to be encrypted or decrypted.
2389
+ *
2390
+ * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
2391
+ *
2392
+ * @return {WordArray} The data after processing.
2393
+ *
2394
+ * @example
2395
+ *
2396
+ * const encrypted = cipher.process('data');
2397
+ * const encrypted = cipher.process(wordArray);
2398
+ */},{key:"process",value:function process(dataUpdate){// Append
2399
+ this._append(dataUpdate);// Process available blocks
2400
+ return this._process();}/**
2401
+ * Finalizes the encryption or decryption process.
2402
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2403
+ *
2404
+ * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
2405
+ *
2406
+ * @return {WordArray} The data after final processing.
2407
+ *
2408
+ * @example
2409
+ *
2410
+ * const encrypted = cipher.finalize();
2411
+ * const encrypted = cipher.finalize('data');
2412
+ * const encrypted = cipher.finalize(wordArray);
2413
+ */},{key:"finalize",value:function finalize(dataUpdate){// Final data update
2414
+ if(dataUpdate){this._append(dataUpdate);}// Perform concrete-cipher logic
2415
+ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"createEncryptor",value:function createEncryptor(key,cfg){return this.create(this._ENC_XFORM_MODE,key,cfg);}/**
2416
+ * Creates this cipher in decryption mode.
2417
+ *
2418
+ * @param {WordArray} key The key.
2419
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2420
+ *
2421
+ * @return {Cipher} A cipher instance.
2422
+ *
2423
+ * @static
2424
+ *
2425
+ * @example
2426
+ *
2427
+ * const cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
2428
+ */},{key:"createDecryptor",value:function createDecryptor(key,cfg){return this.create(this._DEC_XFORM_MODE,key,cfg);}/**
2429
+ * Creates shortcut functions to a cipher's object interface.
2430
+ *
2431
+ * @param {Cipher} cipher The cipher to create a helper for.
2432
+ *
2433
+ * @return {Object} An object with encrypt and decrypt shortcut functions.
2434
+ *
2435
+ * @static
2436
+ *
2437
+ * @example
2438
+ *
2439
+ * const AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
2440
+ */},{key:"_createHelper",value:function _createHelper(SubCipher){var selectCipherStrategy=function selectCipherStrategy(key){if(typeof key==='string'){return PasswordBasedCipher;}return SerializableCipher;};return {encrypt:function encrypt(message,key,cfg){return selectCipherStrategy(key).encrypt(SubCipher,message,key,cfg);},decrypt:function decrypt(ciphertext,key,cfg){return selectCipherStrategy(key).decrypt(SubCipher,ciphertext,key,cfg);}};}}]);return Cipher;}(BufferedBlockAlgorithm);Cipher._ENC_XFORM_MODE=1;Cipher._DEC_XFORM_MODE=2;Cipher.keySize=128/32;Cipher.ivSize=128/32;/**
2441
+ * Abstract base block cipher mode template.
2442
+ */var BlockCipherMode=/*#__PURE__*/function(_Base){_inherits(BlockCipherMode,_Base);var _super3=_createSuper(BlockCipherMode);/**
2443
+ * Initializes a newly created mode.
2444
+ *
2445
+ * @param {Cipher} cipher A block cipher instance.
2446
+ * @param {Array} iv The IV words.
2447
+ *
2448
+ * @example
2449
+ *
2450
+ * const mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
2451
+ */function BlockCipherMode(cipher,iv){var _this3;_classCallCheck(this,BlockCipherMode);_this3=_super3.call(this);_this3._cipher=cipher;_this3._iv=iv;return _this3;}/**
2452
+ * Creates this mode for encryption.
2453
+ *
2454
+ * @param {Cipher} cipher A block cipher instance.
2455
+ * @param {Array} iv The IV words.
2456
+ *
2457
+ * @static
2458
+ *
2459
+ * @example
2460
+ *
2461
+ * const mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
2462
+ */_createClass(BlockCipherMode,null,[{key:"createEncryptor",value:function createEncryptor(cipher,iv){return this.Encryptor.create(cipher,iv);}/**
2463
+ * Creates this mode for decryption.
2464
+ *
2465
+ * @param {Cipher} cipher A block cipher instance.
2466
+ * @param {Array} iv The IV words.
2467
+ *
2468
+ * @static
2469
+ *
2470
+ * @example
2471
+ *
2472
+ * const mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
2473
+ */},{key:"createDecryptor",value:function createDecryptor(cipher,iv){return this.Decryptor.create(cipher,iv);}}]);return BlockCipherMode;}(Base);function xorBlock(words,offset,blockSize){var _words=words;var block;// Shortcut
2474
+ var iv=this._iv;// Choose mixing block
2475
+ if(iv){block=iv;// Remove IV for subsequent blocks
2476
+ this._iv=undefined;}else {block=this._prevBlock;}// XOR blocks
2477
+ for(var i=0;i<blockSize;i+=1){_words[offset+i]^=block[i];}}/**
2478
+ * Cipher Block Chaining mode.
2479
+ */ /**
2480
+ * Abstract base CBC mode.
2481
+ */var CBC=/*#__PURE__*/function(_BlockCipherMode){_inherits(CBC,_BlockCipherMode);var _super4=_createSuper(CBC);function CBC(){_classCallCheck(this,CBC);return _super4.apply(this,arguments);}return _createClass(CBC);}(BlockCipherMode);/**
2482
+ * CBC encryptor.
2483
+ */CBC.Encryptor=/*#__PURE__*/function(_CBC){_inherits(_class,_CBC);var _super5=_createSuper(_class);function _class(){_classCallCheck(this,_class);return _super5.apply(this,arguments);}_createClass(_class,[{key:"processBlock",value:/**
2484
+ * Processes the data block at offset.
2485
+ *
2486
+ * @param {Array} words The data words to operate on.
2487
+ * @param {number} offset The offset where the block starts.
2488
+ *
2489
+ * @example
2490
+ *
2491
+ * mode.processBlock(data.words, offset);
2492
+ */function processBlock(words,offset){// Shortcuts
2493
+ var cipher=this._cipher;var blockSize=cipher.blockSize;// XOR and encrypt
2494
+ xorBlock.call(this,words,offset,blockSize);cipher.encryptBlock(words,offset);// Remember this block to use with next block
2495
+ this._prevBlock=words.slice(offset,offset+blockSize);}}]);return _class;}(CBC);/**
2496
+ * CBC decryptor.
2497
+ */CBC.Decryptor=/*#__PURE__*/function(_CBC2){_inherits(_class2,_CBC2);var _super6=_createSuper(_class2);function _class2(){_classCallCheck(this,_class2);return _super6.apply(this,arguments);}_createClass(_class2,[{key:"processBlock",value:/**
2498
+ * Processes the data block at offset.
2499
+ *
2500
+ * @param {Array} words The data words to operate on.
2501
+ * @param {number} offset The offset where the block starts.
2502
+ *
2503
+ * @example
2504
+ *
2505
+ * mode.processBlock(data.words, offset);
2506
+ */function processBlock(words,offset){// Shortcuts
2507
+ var cipher=this._cipher;var blockSize=cipher.blockSize;// Remember this block to use with next block
2508
+ var thisBlock=words.slice(offset,offset+blockSize);// Decrypt and XOR
2509
+ cipher.decryptBlock(words,offset);xorBlock.call(this,words,offset,blockSize);// This block becomes the previous block
2510
+ this._prevBlock=thisBlock;}}]);return _class2;}(CBC);/**
2511
+ * PKCS #5/7 padding strategy.
2512
+ */var Pkcs7={/**
2513
+ * Pads data using the algorithm defined in PKCS #5/7.
2514
+ *
2515
+ * @param {WordArray} data The data to pad.
2516
+ * @param {number} blockSize The multiple that the data should be padded to.
2517
+ *
2518
+ * @static
2519
+ *
2520
+ * @example
2521
+ *
2522
+ * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
2523
+ */pad:function pad(data,blockSize){// Shortcut
2524
+ var blockSizeBytes=blockSize*4;// Count padding bytes
2525
+ var nPaddingBytes=blockSizeBytes-data.sigBytes%blockSizeBytes;// Create padding word
2526
+ var paddingWord=nPaddingBytes<<24|nPaddingBytes<<16|nPaddingBytes<<8|nPaddingBytes;// Create padding
2527
+ var paddingWords=[];for(var i=0;i<nPaddingBytes;i+=4){paddingWords.push(paddingWord);}var padding=WordArray.create(paddingWords,nPaddingBytes);// Add padding
2528
+ data.concat(padding);},/**
2529
+ * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
2530
+ *
2531
+ * @param {WordArray} data The data to unpad.
2532
+ *
2533
+ * @static
2534
+ *
2535
+ * @example
2536
+ *
2537
+ * CryptoJS.pad.Pkcs7.unpad(wordArray);
2538
+ */unpad:function unpad(data){var _data=data;// Get number of padding bytes from last byte
2539
+ var nPaddingBytes=_data.words[_data.sigBytes-1>>>2]&0xff;// Remove padding
2540
+ _data.sigBytes-=nPaddingBytes;}};/**
2541
+ * Abstract base block cipher template.
2542
+ *
2543
+ * @property {number} blockSize
2544
+ *
2545
+ * The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
2546
+ */var BlockCipher=/*#__PURE__*/function(_Cipher2){_inherits(BlockCipher,_Cipher2);var _super7=_createSuper(BlockCipher);function BlockCipher(xformMode,key,cfg){var _this4;_classCallCheck(this,BlockCipher);/**
2547
+ * Configuration options.
2548
+ *
2549
+ * @property {Mode} mode The block mode to use. Default: CBC
2550
+ * @property {Padding} padding The padding strategy to use. Default: Pkcs7
2551
+ */_this4=_super7.call(this,xformMode,key,ObjectAssign({mode:CBC,padding:Pkcs7},cfg));_this4.blockSize=128/32;return _this4;}_createClass(BlockCipher,[{key:"reset",value:function reset(){var modeCreator;// Reset cipher
2552
+ _get(_getPrototypeOf(BlockCipher.prototype),"reset",this).call(this);// Shortcuts
2553
+ var cfg=this.cfg;var iv=cfg.iv,mode=cfg.mode;// Reset block mode
2554
+ if(this._xformMode===this.constructor._ENC_XFORM_MODE){modeCreator=mode.createEncryptor;}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{modeCreator=mode.createDecryptor;// Keep at least one block in the buffer for unpadding
2555
+ this._minBufferSize=1;}this._mode=modeCreator.call(mode,this,iv&&iv.words);this._mode.__creator=modeCreator;}},{key:"_doProcessBlock",value:function _doProcessBlock(words,offset){this._mode.processBlock(words,offset);}},{key:"_doFinalize",value:function _doFinalize(){var finalProcessedBlocks;// Shortcut
2556
+ var padding=this.cfg.padding;// Finalize
2557
+ if(this._xformMode===this.constructor._ENC_XFORM_MODE){// Pad data
2558
+ padding.pad(this._data,this.blockSize);// Process final blocks
2559
+ finalProcessedBlocks=this._process(!!'flush');}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{// Process final blocks
2560
+ finalProcessedBlocks=this._process(!!'flush');// Unpad data
2561
+ padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);return BlockCipher;}(Cipher);/**
2562
+ * A collection of cipher parameters.
2563
+ *
2564
+ * @property {WordArray} ciphertext The raw ciphertext.
2565
+ * @property {WordArray} key The key to this ciphertext.
2566
+ * @property {WordArray} iv The IV used in the ciphering operation.
2567
+ * @property {WordArray} salt The salt used with a key derivation function.
2568
+ * @property {Cipher} algorithm The cipher algorithm.
2569
+ * @property {Mode} mode The block mode used in the ciphering operation.
2570
+ * @property {Padding} padding The padding scheme used in the ciphering operation.
2571
+ * @property {number} blockSize The block size of the cipher.
2572
+ * @property {Format} formatter
2573
+ * The default formatting strategy to convert this cipher params object to a string.
2574
+ */var CipherParams=/*#__PURE__*/function(_Base2){_inherits(CipherParams,_Base2);var _super8=_createSuper(CipherParams);/**
2575
+ * Initializes a newly created cipher params object.
2576
+ *
2577
+ * @param {Object} cipherParams An object with any of the possible cipher parameters.
2578
+ *
2579
+ * @example
2580
+ *
2581
+ * var cipherParams = CryptoJS.lib.CipherParams.create({
2582
+ * ciphertext: ciphertextWordArray,
2583
+ * key: keyWordArray,
2584
+ * iv: ivWordArray,
2585
+ * salt: saltWordArray,
2586
+ * algorithm: CryptoJS.algo.AES,
2587
+ * mode: CryptoJS.mode.CBC,
2588
+ * padding: CryptoJS.pad.PKCS7,
2589
+ * blockSize: 4,
2590
+ * formatter: CryptoJS.format.OpenSSL
2591
+ * });
2592
+ */function CipherParams(cipherParams){var _this5;_classCallCheck(this,CipherParams);_this5=_super8.call(this);_this5.mixIn(cipherParams);return _this5;}/**
2593
+ * Converts this cipher params object to a string.
2594
+ *
2595
+ * @param {Format} formatter (Optional) The formatting strategy to use.
2596
+ *
2597
+ * @return {string} The stringified cipher params.
2598
+ *
2599
+ * @throws Error If neither the formatter nor the default formatter is set.
2600
+ *
2601
+ * @example
2602
+ *
2603
+ * var string = cipherParams + '';
2604
+ * var string = cipherParams.toString();
2605
+ * var string = cipherParams.toString(CryptoJS.format.OpenSSL);
2606
+ */_createClass(CipherParams,[{key:"toString",value:function toString(formatter){return (formatter||this.formatter).stringify(this);}}]);return CipherParams;}(Base);/**
2607
+ * OpenSSL formatting strategy.
2608
+ */var OpenSSLFormatter={/**
2609
+ * Converts a cipher params object to an OpenSSL-compatible string.
2610
+ *
2611
+ * @param {CipherParams} cipherParams The cipher params object.
2612
+ *
2613
+ * @return {string} The OpenSSL-compatible string.
2614
+ *
2615
+ * @static
2616
+ *
2617
+ * @example
2618
+ *
2619
+ * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
2620
+ */stringify:function stringify(cipherParams){var wordArray;// Shortcuts
2621
+ var ciphertext=cipherParams.ciphertext,salt=cipherParams.salt;// Format
2622
+ if(salt){wordArray=WordArray.create([0x53616c74,0x65645f5f]).concat(salt).concat(ciphertext);}else {wordArray=ciphertext;}return wordArray.toString(Base64);},/**
2623
+ * Converts an OpenSSL-compatible string to a cipher params object.
2624
+ *
2625
+ * @param {string} openSSLStr The OpenSSL-compatible string.
2626
+ *
2627
+ * @return {CipherParams} The cipher params object.
2628
+ *
2629
+ * @static
2630
+ *
2631
+ * @example
2632
+ *
2633
+ * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
2634
+ */parse:function parse(openSSLStr){var salt;// Parse base64
2635
+ var ciphertext=Base64.parse(openSSLStr);// Shortcut
2636
+ var ciphertextWords=ciphertext.words;// Test for salt
2637
+ if(ciphertextWords[0]===0x53616c74&&ciphertextWords[1]===0x65645f5f){// Extract salt
2638
+ salt=WordArray.create(ciphertextWords.slice(2,4));// Remove salt from ciphertext
2639
+ ciphertextWords.splice(0,4);ciphertext.sigBytes-=16;}return CipherParams.create({ciphertext:ciphertext,salt:salt});}};/**
2640
+ * A cipher wrapper that returns ciphertext as a serializable cipher params object.
2641
+ */var SerializableCipher=/*#__PURE__*/function(_Base3){_inherits(SerializableCipher,_Base3);var _super9=_createSuper(SerializableCipher);function SerializableCipher(){_classCallCheck(this,SerializableCipher);return _super9.apply(this,arguments);}_createClass(SerializableCipher,null,[{key:"encrypt",value:/**
2642
+ * Encrypts a message.
2643
+ *
2644
+ * @param {Cipher} cipher The cipher algorithm to use.
2645
+ * @param {WordArray|string} message The message to encrypt.
2646
+ * @param {WordArray} key The key.
2647
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2648
+ *
2649
+ * @return {CipherParams} A cipher params object.
2650
+ *
2651
+ * @static
2652
+ *
2653
+ * @example
2654
+ *
2655
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2656
+ * .encrypt(CryptoJS.algo.AES, message, key);
2657
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2658
+ * .encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
2659
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2660
+ * .encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
2661
+ */function encrypt(cipher,message,key,cfg){// Apply config defaults
2662
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Encrypt
2663
+ var encryptor=cipher.createEncryptor(key,_cfg);var ciphertext=encryptor.finalize(message);// Shortcut
2664
+ var cipherCfg=encryptor.cfg;// Create and return serializable cipher params
2665
+ return CipherParams.create({ciphertext:ciphertext,key:key,iv:cipherCfg.iv,algorithm:cipher,mode:cipherCfg.mode,padding:cipherCfg.padding,blockSize:encryptor.blockSize,formatter:_cfg.format});}/**
2666
+ * Decrypts serialized ciphertext.
2667
+ *
2668
+ * @param {Cipher} cipher The cipher algorithm to use.
2669
+ * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
2670
+ * @param {WordArray} key The key.
2671
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2672
+ *
2673
+ * @return {WordArray} The plaintext.
2674
+ *
2675
+ * @static
2676
+ *
2677
+ * @example
2678
+ *
2679
+ * var plaintext = CryptoJS.lib.SerializableCipher
2680
+ * .decrypt(CryptoJS.algo.AES, formattedCiphertext, key,
2681
+ * { iv: iv, format: CryptoJS.format.OpenSSL });
2682
+ * var plaintext = CryptoJS.lib.SerializableCipher
2683
+ * .decrypt(CryptoJS.algo.AES, ciphertextParams, key,
2684
+ * { iv: iv, format: CryptoJS.format.OpenSSL });
2685
+ */},{key:"decrypt",value:function decrypt(cipher,ciphertext,key,cfg){var _ciphertext=ciphertext;// Apply config defaults
2686
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Convert string to CipherParams
2687
+ _ciphertext=this._parse(_ciphertext,_cfg.format);// Decrypt
2688
+ var plaintext=cipher.createDecryptor(key,_cfg).finalize(_ciphertext.ciphertext);return plaintext;}/**
2689
+ * Converts serialized ciphertext to CipherParams,
2690
+ * else assumed CipherParams already and returns ciphertext unchanged.
2691
+ *
2692
+ * @param {CipherParams|string} ciphertext The ciphertext.
2693
+ * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
2694
+ *
2695
+ * @return {CipherParams} The unserialized ciphertext.
2696
+ *
2697
+ * @static
2698
+ *
2699
+ * @example
2700
+ *
2701
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2702
+ * ._parse(ciphertextStringOrParams, format);
2703
+ */},{key:"_parse",value:function _parse(ciphertext,format){if(typeof ciphertext==='string'){return format.parse(ciphertext,this);}return ciphertext;}}]);return SerializableCipher;}(Base);/**
2704
+ * Configuration options.
2705
+ *
2706
+ * @property {Formatter} format
2707
+ *
2708
+ * The formatting strategy to convert cipher param objects to and from a string.
2709
+ * Default: OpenSSL
2710
+ */SerializableCipher.cfg=ObjectAssign(new Base(),{format:OpenSSLFormatter});/**
2711
+ * OpenSSL key derivation function.
2712
+ */var OpenSSLKdf={/**
2713
+ * Derives a key and IV from a password.
2714
+ *
2715
+ * @param {string} password The password to derive from.
2716
+ * @param {number} keySize The size in words of the key to generate.
2717
+ * @param {number} ivSize The size in words of the IV to generate.
2718
+ * @param {WordArray|string} salt
2719
+ * (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
2720
+ *
2721
+ * @return {CipherParams} A cipher params object with the key, IV, and salt.
2722
+ *
2723
+ * @static
2724
+ *
2725
+ * @example
2726
+ *
2727
+ * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
2728
+ * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
2729
+ */execute:function execute(password,keySize,ivSize,salt,hasher){var _salt=salt;// Generate random salt
2730
+ if(!_salt){_salt=WordArray.random(64/8);}// Derive key and IV
2731
+ var key;if(!hasher){key=EvpKDFAlgo.create({keySize:keySize+ivSize}).compute(password,_salt);}else {key=EvpKDFAlgo.create({keySize:keySize+ivSize,hasher:hasher}).compute(password,_salt);}// Separate key and IV
2732
+ var iv=WordArray.create(key.words.slice(keySize),ivSize*4);key.sigBytes=keySize*4;// Return params
2733
+ return CipherParams.create({key:key,iv:iv,salt:_salt});}};/**
2734
+ * A serializable cipher wrapper that derives the key from a password,
2735
+ * and returns ciphertext as a serializable cipher params object.
2736
+ */var PasswordBasedCipher=/*#__PURE__*/function(_SerializableCipher){_inherits(PasswordBasedCipher,_SerializableCipher);var _super10=_createSuper(PasswordBasedCipher);function PasswordBasedCipher(){_classCallCheck(this,PasswordBasedCipher);return _super10.apply(this,arguments);}_createClass(PasswordBasedCipher,null,[{key:"encrypt",value:/**
2737
+ * Encrypts a message using a password.
2738
+ *
2739
+ * @param {Cipher} cipher The cipher algorithm to use.
2740
+ * @param {WordArray|string} message The message to encrypt.
2741
+ * @param {string} password The password.
2742
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2743
+ *
2744
+ * @return {CipherParams} A cipher params object.
2745
+ *
2746
+ * @static
2747
+ *
2748
+ * @example
2749
+ *
2750
+ * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher
2751
+ * .encrypt(CryptoJS.algo.AES, message, 'password');
2752
+ * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher
2753
+ * .encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
2754
+ */function encrypt(cipher,message,password,cfg){// Apply config defaults
2755
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Derive key and other params
2756
+ var derivedParams=_cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,_cfg.salt,_cfg.hasher);// Add IV to config
2757
+ _cfg.iv=derivedParams.iv;// Encrypt
2758
+ var ciphertext=SerializableCipher.encrypt.call(this,cipher,message,derivedParams.key,_cfg);// Mix in derived params
2759
+ ciphertext.mixIn(derivedParams);return ciphertext;}/**
2760
+ * Decrypts serialized ciphertext using a password.
2761
+ *
2762
+ * @param {Cipher} cipher The cipher algorithm to use.
2763
+ * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
2764
+ * @param {string} password The password.
2765
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2766
+ *
2767
+ * @return {WordArray} The plaintext.
2768
+ *
2769
+ * @static
2770
+ *
2771
+ * @example
2772
+ *
2773
+ * var plaintext = CryptoJS.lib.PasswordBasedCipher
2774
+ * .decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password',
2775
+ * { format: CryptoJS.format.OpenSSL });
2776
+ * var plaintext = CryptoJS.lib.PasswordBasedCipher
2777
+ * .decrypt(CryptoJS.algo.AES, ciphertextParams, 'password',
2778
+ * { format: CryptoJS.format.OpenSSL });
2779
+ */},{key:"decrypt",value:function decrypt(cipher,ciphertext,password,cfg){var _ciphertext=ciphertext;// Apply config defaults
2780
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Convert string to CipherParams
2781
+ _ciphertext=this._parse(_ciphertext,_cfg.format);// Derive key and other params
2782
+ var derivedParams=_cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,_ciphertext.salt,_cfg.hasher);// Add IV to config
2783
+ _cfg.iv=derivedParams.iv;// Decrypt
2784
+ var plaintext=SerializableCipher.decrypt.call(this,cipher,_ciphertext,derivedParams.key,_cfg);return plaintext;}}]);return PasswordBasedCipher;}(SerializableCipher);/**
2785
+ * Configuration options.
2786
+ *
2787
+ * @property {KDF} kdf
2788
+ * The key derivation function to use to generate a key and IV from a password.
2789
+ * Default: OpenSSL
2790
+ */PasswordBasedCipher.cfg=ObjectAssign(SerializableCipher.cfg,{kdf:OpenSSLKdf});
2791
+
2792
+ var _SBOX=[];var INV_SBOX=[];var _SUB_MIX_0=[];var _SUB_MIX_1=[];var _SUB_MIX_2=[];var _SUB_MIX_3=[];var INV_SUB_MIX_0=[];var INV_SUB_MIX_1=[];var INV_SUB_MIX_2=[];var INV_SUB_MIX_3=[];// Compute lookup tables
2793
+ // Compute double table
2794
+ var d=[];for(var i=0;i<256;i+=1){if(i<128){d[i]=i<<1;}else {d[i]=i<<1^0x11b;}}// Walk GF(2^8)
2795
+ var x=0;var xi=0;for(var _i=0;_i<256;_i+=1){// Compute sbox
2796
+ var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^sx&0xff^0x63;_SBOX[x]=sx;INV_SBOX[sx]=x;// Compute multiplication
2797
+ var x2=d[x];var x4=d[x2];var x8=d[x4];// Compute sub bytes, mix columns tables
2798
+ var t=d[sx]*0x101^sx*0x1010100;_SUB_MIX_0[x]=t<<24|t>>>8;_SUB_MIX_1[x]=t<<16|t>>>16;_SUB_MIX_2[x]=t<<8|t>>>24;_SUB_MIX_3[x]=t;// Compute inv sub bytes, inv mix columns tables
2799
+ t=x8*0x1010101^x4*0x10001^x2*0x101^x*0x1010100;INV_SUB_MIX_0[sx]=t<<24|t>>>8;INV_SUB_MIX_1[sx]=t<<16|t>>>16;INV_SUB_MIX_2[sx]=t<<8|t>>>24;INV_SUB_MIX_3[sx]=t;// Compute next counter
2800
+ if(!x){xi=1;x=xi;}else {x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]];}}// Precomputed Rcon lookup
2801
+ var RCON=[0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36];/**
2802
+ * AES block cipher algorithm.
2803
+ */var AESAlgo=/*#__PURE__*/function(_BlockCipher){_inherits(AESAlgo,_BlockCipher);var _super=_createSuper(AESAlgo);function AESAlgo(){_classCallCheck(this,AESAlgo);return _super.apply(this,arguments);}_createClass(AESAlgo,[{key:"_doReset",value:function _doReset(){var t;// Skip reset of nRounds has been set before and key did not change
2804
+ if(this._nRounds&&this._keyPriorReset===this._key){return;}// Shortcuts
2805
+ this._keyPriorReset=this._key;var key=this._keyPriorReset;var keyWords=key.words;var keySize=key.sigBytes/4;// Compute number of rounds
2806
+ this._nRounds=keySize+6;var nRounds=this._nRounds;// Compute number of key schedule rows
2807
+ var ksRows=(nRounds+1)*4;// Compute key schedule
2808
+ this._keySchedule=[];var keySchedule=this._keySchedule;for(var ksRow=0;ksRow<ksRows;ksRow+=1){if(ksRow<keySize){keySchedule[ksRow]=keyWords[ksRow];}else {t=keySchedule[ksRow-1];if(!(ksRow%keySize)){// Rot word
2809
+ t=t<<8|t>>>24;// Sub word
2810
+ t=_SBOX[t>>>24]<<24|_SBOX[t>>>16&0xff]<<16|_SBOX[t>>>8&0xff]<<8|_SBOX[t&0xff];// Mix Rcon
2811
+ t^=RCON[ksRow/keySize|0]<<24;}else if(keySize>6&&ksRow%keySize===4){// Sub word
2812
+ t=_SBOX[t>>>24]<<24|_SBOX[t>>>16&0xff]<<16|_SBOX[t>>>8&0xff]<<8|_SBOX[t&0xff];}keySchedule[ksRow]=keySchedule[ksRow-keySize]^t;}}// Compute inv key schedule
2813
+ this._invKeySchedule=[];var invKeySchedule=this._invKeySchedule;for(var invKsRow=0;invKsRow<ksRows;invKsRow+=1){var _ksRow=ksRows-invKsRow;if(invKsRow%4){t=keySchedule[_ksRow];}else {t=keySchedule[_ksRow-4];}if(invKsRow<4||_ksRow<=4){invKeySchedule[invKsRow]=t;}else {invKeySchedule[invKsRow]=INV_SUB_MIX_0[_SBOX[t>>>24]]^INV_SUB_MIX_1[_SBOX[t>>>16&0xff]]^INV_SUB_MIX_2[_SBOX[t>>>8&0xff]]^INV_SUB_MIX_3[_SBOX[t&0xff]];}}}},{key:"encryptBlock",value:function encryptBlock(M,offset){this._doCryptBlock(M,offset,this._keySchedule,_SUB_MIX_0,_SUB_MIX_1,_SUB_MIX_2,_SUB_MIX_3,_SBOX);}},{key:"decryptBlock",value:function decryptBlock(M,offset){var _M=M;// Swap 2nd and 4th rows
2814
+ var t=_M[offset+1];_M[offset+1]=_M[offset+3];_M[offset+3]=t;this._doCryptBlock(_M,offset,this._invKeySchedule,INV_SUB_MIX_0,INV_SUB_MIX_1,INV_SUB_MIX_2,INV_SUB_MIX_3,INV_SBOX);// Inv swap 2nd and 4th rows
2815
+ t=_M[offset+1];_M[offset+1]=_M[offset+3];_M[offset+3]=t;}},{key:"_doCryptBlock",value:function _doCryptBlock(M,offset,keySchedule,SUB_MIX_0,SUB_MIX_1,SUB_MIX_2,SUB_MIX_3,SBOX){var _M=M;// Shortcut
2816
+ var nRounds=this._nRounds;// Get input, add round key
2817
+ var s0=_M[offset]^keySchedule[0];var s1=_M[offset+1]^keySchedule[1];var s2=_M[offset+2]^keySchedule[2];var s3=_M[offset+3]^keySchedule[3];// Key schedule row counter
2818
+ var ksRow=4;// Rounds
2819
+ for(var round=1;round<nRounds;round+=1){// Shift rows, sub bytes, mix columns, add round key
2820
+ var _t=SUB_MIX_0[s0>>>24]^SUB_MIX_1[s1>>>16&0xff]^SUB_MIX_2[s2>>>8&0xff]^SUB_MIX_3[s3&0xff]^keySchedule[ksRow];ksRow+=1;var _t2=SUB_MIX_0[s1>>>24]^SUB_MIX_1[s2>>>16&0xff]^SUB_MIX_2[s3>>>8&0xff]^SUB_MIX_3[s0&0xff]^keySchedule[ksRow];ksRow+=1;var _t3=SUB_MIX_0[s2>>>24]^SUB_MIX_1[s3>>>16&0xff]^SUB_MIX_2[s0>>>8&0xff]^SUB_MIX_3[s1&0xff]^keySchedule[ksRow];ksRow+=1;var _t4=SUB_MIX_0[s3>>>24]^SUB_MIX_1[s0>>>16&0xff]^SUB_MIX_2[s1>>>8&0xff]^SUB_MIX_3[s2&0xff]^keySchedule[ksRow];ksRow+=1;// Update state
2821
+ s0=_t;s1=_t2;s2=_t3;s3=_t4;}// Shift rows, sub bytes, add round key
2822
+ var t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&0xff]<<16|SBOX[s2>>>8&0xff]<<8|SBOX[s3&0xff])^keySchedule[ksRow];ksRow+=1;var t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&0xff]<<16|SBOX[s3>>>8&0xff]<<8|SBOX[s0&0xff])^keySchedule[ksRow];ksRow+=1;var t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&0xff]<<16|SBOX[s0>>>8&0xff]<<8|SBOX[s1&0xff])^keySchedule[ksRow];ksRow+=1;var t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&0xff]<<16|SBOX[s1>>>8&0xff]<<8|SBOX[s2&0xff])^keySchedule[ksRow];ksRow+=1;// Set output
2823
+ _M[offset]=t0;_M[offset+1]=t1;_M[offset+2]=t2;_M[offset+3]=t3;}}]);return AESAlgo;}(BlockCipher);AESAlgo.keySize=256/32;/**
2824
+ * Shortcut functions to the cipher's object interface.
2825
+ *
2826
+ * @example
2827
+ *
2828
+ * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
2829
+ * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
2830
+ */var AES=BlockCipher._createHelper(AESAlgo);
2831
+
2832
+ var ENCRYPTION_PREFIX_V1='RudderEncrypt:';var ENCRYPTION_KEY_V1='Rudder';
2833
+
2834
+ var encrypt=function encrypt(value){return "".concat(ENCRYPTION_PREFIX_V1).concat(AES.encrypt(value,ENCRYPTION_KEY_V1).toString());};var decrypt=function decrypt(value){if(value.startsWith(ENCRYPTION_PREFIX_V1)){return AES.decrypt(value.substring(ENCRYPTION_PREFIX_V1.length),ENCRYPTION_KEY_V1).toString(Utf8);}return value;};
2835
+
2836
+ var pluginName$2='StorageEncryptionLegacy';var StorageEncryptionLegacy=function StorageEncryptionLegacy(){return {name:pluginName$2,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$2]);},storage:{encrypt:function encrypt$1(value){return encrypt(value);},decrypt:function decrypt$1(value){return decrypt(value);}}};};
2837
+
2838
+ var STORAGE_MIGRATION_ERROR=function STORAGE_MIGRATION_ERROR(key){return "Failed to retrieve or parse data for ".concat(key," from storage.");};
2839
+
2840
+ var STORAGE_MIGRATOR_PLUGIN='StorageMigratorPlugin';
2841
+
2842
+ var pluginName$1='StorageMigrator';var StorageMigrator=function StorageMigrator(){return {name:pluginName$1,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$1]);},storage:{migrate:function migrate(key,storageEngine,errorHandler,logger){try{var storedVal=storageEngine.getItem(key);if(isNullOrUndefined(storedVal)){return null;}var decryptedVal=decrypt(storedVal);// The value is not encrypted using legacy encryption
2843
+ // Try latest
2844
+ if(decryptedVal===storedVal){decryptedVal=decrypt$1(storedVal);}if(isNullOrUndefined(decryptedVal)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
2845
+ return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,STORAGE_MIGRATOR_PLUGIN,STORAGE_MIGRATION_ERROR(key));return null;}}}};};
2846
+
2847
+ var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=10*1000;// 10 seconds
2848
+ var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
2849
+
2850
+ var EVENT_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event(s) to ").concat(url,".");};
2851
+
2852
+ var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,logger){var batchPayload={batch:events};return stringifyWithoutCircular(batchPayload,true,undefined,logger);};var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,endpoint){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/',DATA_PLANE_API_VERSION,'/',endpoint].join('')),dpUrl).href;};var getBatchDeliveryUrl=function getBatchDeliveryUrl(dataplaneUrl){return getDeliveryUrl(dataplaneUrl,'batch');};var logErrorOnFailure=function logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger){if(isUndefined(details===null||details===void 0?void 0:details.error)||isUndefined(logger)){return;}var isRetryableFailure=isErrRetryable(details);var errMsg=EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN,url);var dropMsg="The event(s) will be dropped.";if(isRetryableFailure){if(willBeRetried){errMsg="".concat(errMsg," It/they will be retried.");if(attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(attemptNumber," of ").concat(maxRetryAttempts,".");}}else {errMsg="".concat(errMsg," Retries exhausted (").concat(maxRetryAttempts,"). ").concat(dropMsg);}}else {errMsg="".concat(errMsg," ").concat(dropMsg);}logger===null||logger===void 0||logger.error(errMsg);};var getRequestInfo=function getRequestInfo(itemData,state,logger){var data;var headers;var url;if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event);});data=getBatchDeliveryPayload(finalEvents,logger);headers=itemData[0]?clone$1(itemData[0].headers):{};url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event);data=getDeliveryPayload(finalEvent,logger);headers=clone$1(eventHeaders);url=eventUrl;}return {data:data,headers:headers,url:url};};
2853
+
2854
+ var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginName,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName]);},dataplaneEventsQueue:{/**
2855
+ * Initialize the queue for delivery
2856
+ * @param state Application state
2857
+ * @param httpClient http client instance
2858
+ * @param storeManager Store Manager instance
2859
+ * @param errorHandler Error handler instance
2860
+ * @param logger Logger instance
2861
+ * @returns RetryQueue instance
2862
+ */init:function init(state,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var finalQOpts=getNormalizedQueueOptions(state.loadOptions.value.queueOptions);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
2863
+ "".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(itemData,done,attemptNumber,maxRetryAttempts,willBeRetried){var _getRequestInfo=getRequestInfo(itemData,state,logger),data=_getRequestInfo.data,url=_getRequestInfo.url,headers=_getRequestInfo.headers;httpClient.getAsyncData({url:url,options:{method:'POST',headers:headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:function callback(result,details){// null means item will not be requeued
2864
+ var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger);done(queueErrResp,result);}});},storeManager,LOCAL_STORAGE,logger,function(itemData){var _getBatchDeliveryPayl;var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to string as we know that the event has already been validated prior to enqueue
2865
+ return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
2866
+ * Add event to the queue for delivery
2867
+ * @param state Application state
2868
+ * @param eventsQueue RetryQueue instance
2869
+ * @param event RudderEvent object
2870
+ * @param errorHandler Error handler instance
2871
+ * @param logger Logger instance
2872
+ * @returns none
2873
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
2874
+ // It'll be updated to the latest timestamp during actual delivery
2875
+ event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl(dataplaneUrl,event.type);// Other default headers are added by the HttpClient
2876
+ // Auth header is added during initialization
2877
+ var headers={// To maintain event ordering while using the HTTP API as per is documentation,
2878
+ // make sure to include anonymousId as a header
2879
+ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:headers,event:event});}}};};
2880
+
2881
+ /**
2882
+ * Map plugin names to direct code imports from plugins package
2883
+ */var getBundledBuildPluginImports=function getBundledBuildPluginImports(){return {BeaconQueue:BeaconQueue,Bugsnag:Bugsnag,CustomConsentManager:CustomConsentManager,DeviceModeDestinations:DeviceModeDestinations,DeviceModeTransformation:DeviceModeTransformation,ErrorReporting:ErrorReporting,ExternalAnonymousId:ExternalAnonymousId,GoogleLinker:GoogleLinker,KetchConsentManager:KetchConsentManager,NativeDestinationQueue:NativeDestinationQueue,OneTrustConsentManager:OneTrustConsentManager,StorageEncryption:StorageEncryption,StorageEncryptionLegacy:StorageEncryptionLegacy,StorageMigrator:StorageMigrator,XhrQueue:XhrQueue};};
2884
+
2885
+ /**
2886
+ * Map of mandatory plugin names and direct imports
2887
+ */var getMandatoryPluginsMap=function getMandatoryPluginsMap(){return {};};/**
2888
+ * Map of optional plugin names and direct imports for legacy builds
2889
+ */var getOptionalPluginsMap=function getOptionalPluginsMap(){return getBundledBuildPluginImports();};/**
2890
+ * Map of optional plugin names and dynamic imports for modern builds
2891
+ */var getRemotePluginsMap=function getRemotePluginsMap(activePluginNames){{return {};}};var pluginsInventory=_objectSpread2(_objectSpread2({},getMandatoryPluginsMap()),getOptionalPluginsMap());var remotePluginsInventory=function remotePluginsInventory(activePluginNames){return _objectSpread2({},getRemotePluginsMap());};
2892
+
2893
+ // TODO: add retry mechanism for getting remote plugins
2894
+ // TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
2895
+ var PluginsManager=/*#__PURE__*/function(){function PluginsManager(engine,errorHandler,logger){_classCallCheck(this,PluginsManager);this.engine=engine;this.errorHandler=errorHandler;this.logger=logger;this.onError=this.onError.bind(this);}/**
2896
+ * Orchestrate the plugin loading and registering
2897
+ */_createClass(PluginsManager,[{key:"init",value:function init(){state.lifecycle.status.value='pluginsLoading';// Expose pluginsCDNPath to global object, so it can be used in the promise that determines
2898
+ this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
2899
+ * Update state based on plugin loaded status
2900
+ */ // eslint-disable-next-line class-methods-use-this
2901
+ },{key:"attachEffects",value:function attachEffects(){O(function(){var isAllPluginsReady=state.plugins.activePlugins.value.length===0||state.plugins.loadedPlugins.value.length+state.plugins.failedPlugins.value.length===state.plugins.totalPluginsToLoad.value;if(isAllPluginsReady){n(function(){state.plugins.ready.value=true;// TODO: decide what to do if a plugin fails to load for any reason.
2902
+ // Should we stop here or should we progress?
2903
+ state.lifecycle.status.value='pluginsReady';});}});}/**
2904
+ * Determine the list of plugins that should be loaded based on sourceConfig & load options
2905
+ */ // eslint-disable-next-line class-methods-use-this
2906
+ },{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _state$nativeDestinat;// This contains the default plugins if load option has been omitted by user
2907
+ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Error reporting related plugins
2908
+ var supportedErrReportingProviderPluginNames=Object.values(ErrorReportingProvidersToPluginNameMap);if(state.reporting.errorReportingProviderPluginName.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.reporting.errorReportingProviderPluginName.value&&supportedErrReportingProviderPluginNames.includes(pluginName));});}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName==='ErrorReporting'||supportedErrReportingProviderPluginNames.includes(pluginName));});}// Cloud mode (dataplane) events delivery plugins
2909
+ if(state.loadOptions.value.useBeacon===true&&state.capabilities.isBeaconAvailable.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!=='XhrQueue';});}else {if(state.loadOptions.value.useBeacon===true){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(UNSUPPORTED_BEACON_API_WARNING(PLUGINS_MANAGER));}pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!=='BeaconQueue';});}// Enforce default cloud mode event delivery queue plugin is none exists
2910
+ if(!pluginsToLoadFromConfig.includes('XhrQueue')&&!pluginsToLoadFromConfig.includes('BeaconQueue')){pluginsToLoadFromConfig.push('XhrQueue');}// Device mode destinations related plugins
2911
+ if(getNonCloudDestinations((_state$nativeDestinat=state.nativeDestinations.configuredDestinations.value)!==null&&_state$nativeDestinat!==void 0?_state$nativeDestinat:[]).length===0){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !['DeviceModeDestinations','DeviceModeTransformation','NativeDestinationQueue'].includes(pluginName);});}// Consent Management related plugins
2912
+ var supportedConsentManagerPlugins=Object.values(ConsentManagersToPluginNameMap);var filterCondition=function filterCondition(pluginName){return !(pluginName!==state.consents.activeConsentManagerPluginName.value&&supportedConsentManagerPlugins.includes(pluginName));};if(!state.consents.enabled.value){filterCondition=function filterCondition(pluginName){return !supportedConsentManagerPlugins.includes(pluginName);};}pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(filterCondition);// Storage encryption related plugins
2913
+ var supportedStorageEncryptionPlugins=Object.values(StorageEncryptionVersionsToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.storage.encryptionPluginName.value&&supportedStorageEncryptionPlugins.includes(pluginName));});// Storage migrator related plugins
2914
+ if(!state.storage.migrate.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!=='StorageMigrator';});}return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}/**
2915
+ * Determine the list of plugins that should be activated
2916
+ */},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
2917
+ var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory)),_toConsumableArray(pluginNamesList));var activePlugins=[];var failedPlugins=[];pluginsToLoad.forEach(function(pluginName){if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.onError(new Error("Ignoring loading of unknown plugins: ".concat(failedPlugins.join(','),". Mandatory plugins: ").concat(Object.keys(getMandatoryPluginsMap()).join(','),". Load option plugins: ").concat(state.plugins.pluginsToLoadFromConfig.value.join(','))));}n(function(){state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
2918
+ * Register plugins that are direct imports to PluginEngine
2919
+ */},{key:"registerLocalPlugins",value:function registerLocalPlugins(){var _this=this;Object.values(pluginsInventory).forEach(function(localPlugin){if(isFunction(localPlugin)&&state.plugins.activePlugins.value.includes(localPlugin().name)){_this.register([localPlugin()]);}});}/**
2920
+ * Register plugins that are dynamic imports to PluginEngine
2921
+ */},{key:"registerRemotePlugins",value:function registerRemotePlugins(){var _this2=this;var remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);Promise.all(Object.keys(remotePluginsList).map(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(remotePluginKey){return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=2;return remotePluginsList[remotePluginKey]().then(function(remotePluginModule){return _this2.register([remotePluginModule.default()]);}).catch(function(err){// TODO: add retry here if dynamic import fails
2922
+ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);_this2.onError(err,remotePluginKey);});case 2:case"end":return _context.stop();}},_callee);}));return function(_x){return _ref.apply(this,arguments);};}())).catch(function(err){_this2.onError(err);});}/**
2923
+ * Extension point invoke that allows multiple plugins to be registered to it with error handling
2924
+ */},{key:"invokeMultiple",value:function invokeMultiple(extPoint){try{var _this$engine;for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}return (_this$engine=this.engine).invokeMultiple.apply(_this$engine,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return [];}}/**
2925
+ * Extension point invoke that allows a single plugin to be registered to it with error handling
2926
+ */},{key:"invokeSingle",value:function invokeSingle(extPoint){try{var _this$engine2;for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return (_this$engine2=this.engine).invokeSingle.apply(_this$engine2,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return null;}}/**
2927
+ * Plugin engine register with error handling
2928
+ */},{key:"register",value:function register(plugins){var _this3=this;plugins.forEach(function(plugin){try{_this3.engine.register(plugin,state);}catch(e){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[plugin.name]);_this3.onError(e);}});}// TODO: Implement reset API instead
2929
+ },{key:"unregisterLocalPlugins",value:function unregisterLocalPlugins(){var _this4=this;Object.values(pluginsInventory).forEach(function(localPlugin){try{_this4.engine.unregister(localPlugin().name);}catch(e){_this4.onError(e);}});}/**
2930
+ * Handle errors
2931
+ */},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);return PluginsManager;}();
2932
+
2933
+ /**
2934
+ * Utility to parse XHR JSON response
2935
+ */var responseTextToJson=function responseTextToJson(responseText,onError){try{return JSON.parse(responseText||'');}catch(err){var error=getMutatedError(err,'Failed to parse response data');if(isFunction(onError)){onError(error);}else {throw error;}}return undefined;};
2936
+
2937
+ var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
2938
+ * Utility to create request configuration based on default options
2939
+ */var createXhrRequestOptions=function createXhrRequestOptions(url,options,basicAuthHeader){var requestOptions=mergeDeepRight(DEFAULT_XHR_REQUEST_OPTIONS,options||{});if(basicAuthHeader){requestOptions.headers=mergeDeepRight(requestOptions.headers,{Authorization:basicAuthHeader});}requestOptions.url=url;return requestOptions;};/**
2940
+ * Utility implementation of XHR, fetch cannot be used as it requires explicit
2941
+ * origin allowed values and not wildcard for CORS requests with credentials and
2942
+ * this is not supported by our sourceConfig API
2943
+ */var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;var logger=arguments.length>2?arguments[2]:undefined;return new Promise(function(resolve,reject){var payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyWithoutCircular(options.data,false,[],logger);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined:undefined,options:options});// return and don't process further if the payload could not be stringified
2944
+ return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
2945
+ var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url);// The timeout property may be set only in the time interval between a call to the open method
2946
+ // and the first call to the send method in legacy browsers
2947
+ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if(options.headers[headerName]){xhr.setRequestHeader(headerName,options.headers[headerName]);}});try{xhr.send(payload);}catch(err){reject({error:getMutatedError(err,XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,options.url)),xhr:xhr,options:options});}});};
2948
+
2949
+ /**
2950
+ * Service to handle data communication with APIs
2951
+ */var HttpClient=/*#__PURE__*/function(){function HttpClient(errorHandler,logger){_classCallCheck(this,HttpClient);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
2952
+ * Implement requests in a blocking way
2953
+ */_createClass(HttpClient,[{key:"getData",value:function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);this.onError((_error=_context.t0.error)!==null&&_error!==void 0?_error:_context.t0);return _context.abrupt("return",{data:undefined,details:_context.t0});case 12:case"end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
2954
+ * Implement requests in a non-blocking way
2955
+ */},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){var _data$error;_this.onError((_data$error=data.error)!==null&&_data$error!==void 0?_data$error:data);if(!isFireAndForget){callback(undefined,data);}});}/**
2956
+ * Handle errors
2957
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,HTTP_CLIENT);}else {throw error;}}/**
2958
+ * Set basic authentication header (eg writekey)
2959
+ */},{key:"setAuthHeader",value:function setAuthHeader(value){var noBtoa=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var authVal=noBtoa?value:toBase64("".concat(value,":"));this.basicAuthHeader="Basic ".concat(authVal);}/**
2960
+ * Clear basic authentication header
2961
+ */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);return HttpClient;}();var defaultHttpClient=new HttpClient(defaultErrorHandler,defaultLogger);
2962
+
2963
+ var STORAGE_TEST_COOKIE='test_rudder_cookie';var STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';var STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';var STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';var CLIENT_DATA_STORE_COOKIE='clientDataInCookie';var CLIENT_DATA_STORE_LS='clientDataInLocalStorage';var CLIENT_DATA_STORE_MEMORY='clientDataInMemory';var CLIENT_DATA_STORE_SESSION='clientDataInSessionStorage';var USER_SESSION_KEYS=['userId','userTraits','anonymousId','groupId','groupTraits','initialReferrer','initialReferringDomain','sessionInfo','authToken'];
2964
+
2965
+ var _storageClientDataSto;var storageClientDataStoreNameMap=(_storageClientDataSto={},_defineProperty(_storageClientDataSto,COOKIE_STORAGE,CLIENT_DATA_STORE_COOKIE),_defineProperty(_storageClientDataSto,LOCAL_STORAGE,CLIENT_DATA_STORE_LS),_defineProperty(_storageClientDataSto,MEMORY_STORAGE,CLIENT_DATA_STORE_MEMORY),_defineProperty(_storageClientDataSto,SESSION_STORAGE,CLIENT_DATA_STORE_SESSION),_storageClientDataSto);
2966
+
2967
+ var detectAdBlockers=function detectAdBlockers(errorHandler,logger){// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
2968
+ // Use source config URL here as it is very unlikely to be blocked by adblockers
2969
+ // Only the extra query param should make it vulnerable to adblockers
2970
+ // This will work even if the users proxies it.
2971
+ // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
2972
+ var baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);var url="".concat(baseUrl.origin).concat(baseUrl.pathname,"?view=ad");var httpClient=new HttpClient(errorHandler,logger);httpClient.setAuthHeader(state.lifecycle.writeKey.value);httpClient.getAsyncData({url:url,options:{// We actually don't need the response from the request, so we are using HEAD
2973
+ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;// not ad blocked if the request is successful or it is not internally redirected on the client side
2974
+ // Often adblockers instead of blocking the request, they redirect it to an internal URL
2975
+ state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:details.error)!==undefined||(details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.responseURL)!==url;}});};
2976
+
2977
+ var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};var hasUAClientHints=function hasUAClientHints(){return !isNullOrUndefined(globalThis.navigator.userAgentData);};var hasBeacon=function hasBeacon(){return !isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);};var isIE11=function isIE11(){return Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));};
2978
+
2979
+ var getUserAgentClientHint=function getUserAgentClientHint(callback){var level=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'none';if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){var _navigator$userAgentD;(_navigator$userAgentD=navigator.userAgentData)===null||_navigator$userAgentD===void 0||_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(function(ua){callback(ua);}).catch(function(){callback();});}};
2980
+
2981
+ var isDatasetAvailable=function isDatasetAvailable(){var testElement=document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};var legacyJSEngineRequiredPolyfills={URLSearchParams:function URLSearchParams(){return !globalThis.URLSearchParams;},URL:function URL(){return !isFunction(globalThis.URL);},MutationObserver:function(_MutationObserver){function MutationObserver(){return _MutationObserver.apply(this,arguments);}MutationObserver.toString=function(){return _MutationObserver.toString();};return MutationObserver;}(function(){return isUndefined(MutationObserver);}),Promise:function(_Promise){function Promise(){return _Promise.apply(this,arguments);}Promise.toString=function(){return _Promise.toString();};return Promise;}(function(){return isUndefined(Promise);}),'Number.isNaN':function NumberIsNaN(){return !Number.isNaN;},'Number.isInteger':function NumberIsInteger(){return !Number.isInteger;},'Array.from':function ArrayFrom(){return !Array.from;},'Array.prototype.find':function ArrayPrototypeFind(){return !Array.prototype.find;},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !Array.prototype.includes;},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !String.prototype.endsWith;},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !String.prototype.startsWith;},'String.prototype.includes':function StringPrototypeIncludes(){return !String.prototype.includes;},'Object.entries':function ObjectEntries(){return !Object.entries;},'Object.values':function ObjectValues(){return !Object.values;},'Object.assign':function ObjectAssign(){return typeof Object.assign!=='function';},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !String.prototype.replaceAll;},TextEncoder:function(_TextEncoder){function TextEncoder(){return _TextEncoder.apply(this,arguments);}TextEncoder.toString=function(){return _TextEncoder.toString();};return TextEncoder;}(function(){return isUndefined(TextEncoder);}),TextDecoder:function(_TextDecoder){function TextDecoder(){return _TextDecoder.apply(this,arguments);}TextDecoder.toString=function(){return _TextDecoder.toString();};return TextDecoder;}(function(){return isUndefined(TextDecoder);}),'String.fromCodePoint':function StringFromCodePoint(){return !String.fromCodePoint;},requestAnimationFrame:function requestAnimationFrame(){return !isFunction(globalThis.requestAnimationFrame);},cancelAnimationFrame:function cancelAnimationFrame(){return !isFunction(globalThis.cancelAnimationFrame);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);},/* eslint-disable-next-line */'navigator.sendBeacon':function navigatorSendBeacon(){return !isFunction(navigator.sendBeacon);}};var isLegacyJSEngine=function isLegacyJSEngine(){var requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);var needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(var i=0;i<requiredCapabilitiesList.length;i++){var isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
2982
+
2983
+ var getScreenDetails=function getScreenDetails(){var screenDetails={density:0,width:0,height:0,innerWidth:0,innerHeight:0};screenDetails={width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight};return screenDetails;};
2984
+
2985
+ var isStorageQuotaExceeded=function isStorageQuotaExceeded(e){var matchingNames=['QuotaExceededError','NS_ERROR_DOM_QUOTA_REACHED'];// [everything except Firefox, Firefox]
2986
+ var matchingCodes=[22,1014];// [everything except Firefox, Firefox]
2987
+ var isQuotaExceededError=matchingNames.includes(e.name)||matchingCodes.includes(e.code);return e instanceof DOMException&&isQuotaExceededError;};// TODO: also check for SecurityErrors
2988
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
2989
+ var isStorageAvailable=function isStorageAvailable(){var type=arguments.length>0&&arguments[0]!==undefined?arguments[0]:LOCAL_STORAGE;var storageInstance=arguments.length>1?arguments[1]:undefined;var logger=arguments.length>2?arguments[2]:undefined;var storage;var testData;try{switch(type){case MEMORY_STORAGE:return true;case COOKIE_STORAGE:storage=storageInstance;testData=STORAGE_TEST_COOKIE;break;case LOCAL_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.localStorage;testData=STORAGE_TEST_LOCAL_STORAGE;// was STORAGE_TEST_LOCAL_STORAGE in ours and generateUUID() in segment retry one
2990
+ break;case SESSION_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.sessionStorage;testData=STORAGE_TEST_SESSION_STORAGE;break;default:return false;}if(!storage){return false;}storage.setItem(testData,'true');if(storage.getItem(testData)){storage.removeItem(testData);return true;}return false;}catch(err){var msgPrefix=STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER,type);var reason='unavailable';if(isStorageQuotaExceeded(err)){reason='full';}logger===null||logger===void 0||logger.error("".concat(msgPrefix).concat(reason,"."),err);return false;}};
2991
+
2992
+ /**
2993
+ * Encode.
2994
+ */var encode=function encode(value,logger){try{return encodeURIComponent(value);}catch(err){logger===null||logger===void 0||logger.error(COOKIE_DATA_ENCODING_ERROR,err);return undefined;}};/**
2995
+ * Decode
2996
+ */var decode=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
2997
+ return undefined;}};/**
2998
+ * Parse cookie `str`
2999
+ */var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}// TODO: Decode only the cookies that are needed by the SDK
3000
+ pairs.forEach(function(pairItem){pair=pairItem.split('=');var keyName=pair[0]?decode(pair[0]):undefined;if(keyName){obj[keyName]=pair[1]?decode(pair[1]):undefined;}});return obj;};/**
3001
+ * Set cookie `name` to `value`
3002
+ */var set=function set(name,value,optionsConfig,logger){var options=_objectSpread2({},optionsConfig)||{};var cookieString="".concat(encode(name,logger),"=").concat(encode(value,logger));if(isNull(value)){options.maxage=-1;}if(options.maxage){options.expires=new Date(+new Date()+options.maxage);}if(options.path){cookieString+="; path=".concat(options.path);}if(options.domain){cookieString+="; domain=".concat(options.domain);}if(options.expires){cookieString+="; expires=".concat(options.expires.toUTCString());}if(options.samesite){cookieString+="; samesite=".concat(options.samesite);}if(options.secure){cookieString+="; secure";}globalThis.document.cookie=cookieString;};/**
3003
+ * Return all cookies
3004
+ */var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
3005
+ * Get cookie `name`
3006
+ */var get=function get(name){return all()[name];};/**
3007
+ * Set or get cookie `name` with `value` and `options` object
3008
+ */ // eslint-disable-next-line func-names
3009
+ var cookie=function cookie(name,value,options,logger){switch(arguments.length){case 4:case 3:case 2:return set(name,value,options,logger);case 1:if(name){return get(name);}return all();default:return all();}};
3010
+
3011
+ var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
3012
+ * Levels returns all levels of the given url
3013
+ *
3014
+ * The method returns an empty array when the hostname is an ip.
3015
+ */var levelsFunc=function levelsFunc(url){var _host$split;// This is called before the polyfills load thus new URL cannot be used
3016
+ var host=typeof globalThis.URL!=='function'?legacyGetHostname(url):new URL(url).hostname;var parts=(_host$split=host===null||host===void 0?void 0:host.split('.'))!==null&&_host$split!==void 0?_host$split:[];var last=parts[parts.length-1];var levels=[];// Ip address.
3017
+ if(parts.length===4&&last&&last===parseInt(last,10).toString()){return levels;}// Localhost.
3018
+ if(parts.length<=1){// Fix to support localhost
3019
+ if(parts[0]&&parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
3020
+ for(var i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}return levels;};/**
3021
+ * Get the top domain.
3022
+ *
3023
+ * The function constructs the levels of domain and attempts to set a global
3024
+ * cookie on each one when it succeeds it returns the top level domain.
3025
+ *
3026
+ * The method returns an empty string when the hostname is an ip.
3027
+ */var domain=function domain(url){var levels=levelsFunc(url);// Lookup the real top level one.
3028
+ // eslint-disable-next-line unicorn/no-for-loop
3029
+ for(var i=0;i<levels.length;i+=1){var _domain=levels[i];var cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;var opts={domain:"".concat(_domain.indexOf('localhost')!==-1?'':'.').concat(_domain)};// Set cookie on domain
3030
+ cookie(cname,1,opts);// If successful
3031
+ if(cookie(cname)){// Remove cookie from domain
3032
+ cookie(cname,null,opts);return _domain;}}return '';};
3033
+
3034
+ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=domain(globalThis.location.href);return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};var getDefaultLocalStorageOptions=function getDefaultLocalStorageOptions(){return {enabled:true};};var getDefaultSessionStorageOptions=function getDefaultSessionStorageOptions(){return {enabled:true};};var getDefaultInMemoryStorageOptions=function getDefaultInMemoryStorageOptions(){return {enabled:true};};
3035
+
3036
+ /**
3037
+ * A storage utility to persist values in cookies via Storage interface
3038
+ */var CookieStorage=/*#__PURE__*/function(){function CookieStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,CookieStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);if(CookieStorage.globalSingleton){// eslint-disable-next-line no-constructor-return
3039
+ return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}_createClass(CookieStorage,[{key:"configure",value:function configure(options){var _this$options;this.options=mergeDeepRight((_this$options=this.options)!==null&&_this$options!==void 0?_this$options:{},options);if(options.sameDomainCookiesOnly){delete this.options.domain;}this.isSupportAvailable=isStorageAvailable(COOKIE_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){cookie(key,value,this.options,this.logger);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
3040
+ },{key:"getItem",value:function getItem(key){var value=cookie(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){var result=this.setItem(key,null);this.length=Object.keys(cookie()).length;return result;}// eslint-disable-next-line class-methods-use-this
3041
+ },{key:"clear",value:function clear(){// Not implemented
3042
+ // getting a list of all cookie storage keys and remove all values
3043
+ // sounds risky to do as it will take on all top domain cookies
3044
+ // better to explicitly clear specific ones if needed
3045
+ }// This cannot be implemented for cookies
3046
+ // eslint-disable-next-line class-methods-use-this
3047
+ },{key:"key",value:function key(index){var cookies=cookie();var cookieNames=Object.keys(cookies);return isUndefined(cookieNames[index])?null:cookieNames[index];}}]);return CookieStorage;}();_defineProperty(CookieStorage,"globalSingleton",null);
3048
+
3049
+ /**
3050
+ * A storage utility to retain values in memory via Storage interface
3051
+ */var InMemoryStorage=/*#__PURE__*/function(){function InMemoryStorage(options,logger){_classCallCheck(this,InMemoryStorage);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"data",{});this.options=getDefaultInMemoryStorageOptions();this.logger=logger;this.configure(options!==null&&options!==void 0?options:{});}_createClass(InMemoryStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isEnabled=Boolean(this.options.enabled);return this.options;}},{key:"setItem",value:function setItem(key,value){this.data[key]=value;this.length=Object.keys(this.data).length;return value;}},{key:"getItem",value:function getItem(key){if(key in this.data){return this.data[key];}return null;}},{key:"removeItem",value:function removeItem(key){if(key in this.data){delete this.data[key];}this.length=Object.keys(this.data).length;return null;}},{key:"clear",value:function clear(){this.data={};this.length=0;}},{key:"key",value:function key(index){return Object.keys(this.data)[index]?Object.keys(this.data)[index]:null;}}]);return InMemoryStorage;}();var defaultInMemoryStorage=new InMemoryStorage({},defaultLogger);
3052
+
3053
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3054
+
3055
+ function getDefaultExportFromCjs (x) {
3056
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3057
+ }
3058
+
3059
+ var store$1 = {exports: {}};
3060
+
3061
+ (function(module,exports){(function(global,factory){module.exports=factory();})(commonjsGlobal,function(){function isJSON(obj){obj=JSON.stringify(obj);if(!/^\{[\s\S]*\}$/.test(obj)){return false;}return true;}function stringify(val){return val===undefined||typeof val==="function"?val+'':JSON.stringify(val);}function deserialize(value){if(typeof value!=='string'){return undefined;}try{return JSON.parse(value);}catch(e){return value;}}function isFunction(value){return {}.toString.call(value)==="[object Function]";}function isArray(value){return Object.prototype.toString.call(value)==="[object Array]";}// https://github.com/jaywcjlove/store.js/pull/8
3062
+ // Error: QuotaExceededError
3063
+ function dealIncognito(storage){var _KEY='_Is_Incognit',_VALUE='yes';try{// NOTE: set default storage when not passed in
3064
+ if(!storage){storage=window.localStorage;}storage.setItem(_KEY,_VALUE);storage.removeItem(_KEY);}catch(e){var inMemoryStorage={};inMemoryStorage._data={};inMemoryStorage.setItem=function(id,val){return inMemoryStorage._data[id]=String(val);};inMemoryStorage.getItem=function(id){return inMemoryStorage._data.hasOwnProperty(id)?inMemoryStorage._data[id]:undefined;};inMemoryStorage.removeItem=function(id){return delete inMemoryStorage._data[id];};inMemoryStorage.clear=function(){return inMemoryStorage._data={};};storage=inMemoryStorage;}finally{if(storage.getItem(_KEY)===_VALUE)storage.removeItem(_KEY);}return storage;}// deal QuotaExceededError if user use incognito mode in browser
3065
+ var storage=dealIncognito();function Store(){if(!(this instanceof Store)){return new Store();}}Store.prototype={set:function set(key,val){if(key&&!isJSON(key)){storage.setItem(key,stringify(val));}else if(isJSON(key)){for(var a in key)this.set(a,key[a]);}return this;},get:function get(key){// Return all entries if no key
3066
+ if(key===undefined){var ret={};this.forEach(function(key,val){return ret[key]=val;});return ret;}if(key.charAt(0)==='?'){return this.has(key.substr(1));}var args=arguments;if(args.length>1){var dt={};for(var i=0,len=args.length;i<len;i++){var value=deserialize(storage.getItem(args[i]));if(this.has(args[i])){dt[args[i]]=value;}}return dt;}return deserialize(storage.getItem(key));},clear:function clear(){storage.clear();return this;},remove:function remove(key){var val=this.get(key);storage.removeItem(key);return val;},has:function has(key){return {}.hasOwnProperty.call(this.get(),key);},keys:function keys(){var d=[];this.forEach(function(k){d.push(k);});return d;},forEach:function forEach(callback){for(var i=0,len=storage.length;i<len;i++){var key=storage.key(i);callback(key,this.get(key));}return this;},search:function search(str){var arr=this.keys(),dt={};for(var i=0,len=arr.length;i<len;i++){if(arr[i].indexOf(str)>-1)dt[arr[i]]=this.get(arr[i]);}return dt;}};var _Store=null;function store(key,data){var argm=arguments;var dt=null;if(!_Store)_Store=Store();if(argm.length===0)return _Store.get();if(argm.length===1){if(typeof key==="string")return _Store.get(key);if(isJSON(key))return _Store.set(key);}if(argm.length===2&&typeof key==="string"){if(!data)return _Store.remove(key);if(data&&typeof data==="string")return _Store.set(key,data);if(data&&isFunction(data)){dt=null;dt=data(key,_Store.get(key));store.set(key,dt);}}if(argm.length===2&&isArray(key)&&isFunction(data)){for(var i=0,len=key.length;i<len;i++){dt=data(key[i],_Store.get(key[i]));store.set(key[i],dt);}}return store;}for(var a in Store.prototype)store[a]=Store.prototype[a];return store;});})(store$1);var storeExports=store$1.exports;var store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
3067
+
3068
+ // check if the get, set overloads and search methods are used at all
3069
+ // if we do, ensure we provide types to support overloads as per storejs docs
3070
+ // https://www.npmjs.com/package/storejs
3071
+ /**
3072
+ * A storage utility to persist values in localstorage via Storage interface
3073
+ */var LocalStorage=/*#__PURE__*/function(){function LocalStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,LocalStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultLocalStorageOptions();this.logger=logger;this.configure(options);}_createClass(LocalStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(LOCAL_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){store.set(key,value);this.length=store.keys().length;}// eslint-disable-next-line class-methods-use-this
3074
+ },{key:"getItem",value:function getItem(key){var value=store.get(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){store.remove(key);this.length=store.keys().length;}},{key:"clear",value:function clear(){store.clear();this.length=0;}// eslint-disable-next-line class-methods-use-this
3075
+ },{key:"key",value:function key(index){return store.keys()[index]?store.keys()[index]:null;}}]);return LocalStorage;}();var defaultLocalStorage=new LocalStorage({},defaultLogger);
3076
+
3077
+ /**
3078
+ * A storage utility to persist values in SessionStorage via Storage interface
3079
+ */var SessionStorage=/*#__PURE__*/function(){function SessionStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,SessionStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"store",globalThis.sessionStorage);this.options=getDefaultSessionStorageOptions();this.logger=logger;this.configure(options);}_createClass(SessionStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(SESSION_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){this.store.setItem(key,value);this.length=this.store.length;}},{key:"getItem",value:function getItem(key){var value=this.store.getItem(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){this.store.removeItem(key);this.length=this.store.length;}},{key:"clear",value:function clear(){this.store.clear();this.length=0;}},{key:"key",value:function key(index){return this.store.key(index);}}]);return SessionStorage;}();var defaultSessionStorage=new SessionStorage({},defaultLogger);
3080
+
3081
+ /**
3082
+ * A utility to retrieve the storage singleton instance by type
3083
+ */var getStorageEngine=function getStorageEngine(type){switch(type){case LOCAL_STORAGE:return defaultLocalStorage;case SESSION_STORAGE:return defaultSessionStorage;case MEMORY_STORAGE:return defaultInMemoryStorage;case COOKIE_STORAGE:return new CookieStorage({},defaultLogger);default:return defaultInMemoryStorage;}};/**
3084
+ * Configure cookie storage singleton
3085
+ */var configureCookieStorageEngine=function configureCookieStorageEngine(options){new CookieStorage({},defaultLogger).configure(options);};/**
3086
+ * Configure local storage singleton
3087
+ */var configureLocalStorageEngine=function configureLocalStorageEngine(options){defaultLocalStorage.configure(options);};/**
3088
+ * Configure in memory storage singleton
3089
+ */var configureInMemoryStorageEngine=function configureInMemoryStorageEngine(options){defaultInMemoryStorage.configure(options);};/**
3090
+ * Configure session storage singleton
3091
+ */var configureSessionStorageEngine=function configureSessionStorageEngine(options){defaultSessionStorage.configure(options);};/**
3092
+ * Configure all storage singleton instances
3093
+ */var configureStorageEngines=function configureStorageEngines(){var cookieStorageOptions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var localStorageOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var inMemoryStorageOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var sessionStorageOptions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};configureCookieStorageEngine(cookieStorageOptions);configureLocalStorageEngine(localStorageOptions);configureInMemoryStorageEngine(inMemoryStorageOptions);configureSessionStorageEngine(sessionStorageOptions);};
3094
+
3095
+ /**
3096
+ * Store Implementation with dedicated storage
3097
+ */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys,_config$errorHandler,_config$logger;_classCallCheck(this,Store);_defineProperty(this,"hasErrorHandler",false);this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==void 0?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==void 0?_config$validKeys:{};this.engine=engine!==null&&engine!==void 0?engine:getStorageEngine(LOCAL_STORAGE);this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=(_config$errorHandler=config.errorHandler)!==null&&_config$errorHandler!==void 0?_config$errorHandler:defaultErrorHandler;this.hasErrorHandler=Boolean(this.errorHandler);this.logger=(_config$logger=config.logger)!==null&&_config$logger!==void 0?_config$logger:defaultLogger;this.pluginsManager=pluginsManager;}/**
3098
+ * Ensure the key is valid and with correct format
3099
+ */_createClass(Store,[{key:"createValidKey",value:function createValidKey(key){var name=this.name,id=this.id,validKeys=this.validKeys,noKeyValidation=this.noKeyValidation,noCompoundKey=this.noCompoundKey;if(noKeyValidation){return noCompoundKey?key:[name,id,key].join('.');}// validate and return undefined if invalid key
3100
+ var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
3101
+ * Switch to inMemoryEngine, bringing any existing data with.
3102
+ */},{key:"swapQueueStoreToInMemoryEngine",value:function swapQueueStoreToInMemoryEngine(){var _this=this;var name=this.name,id=this.id,validKeys=this.validKeys,noCompoundKey=this.noCompoundKey;var inMemoryStorage=getStorageEngine(MEMORY_STORAGE);// grab existing data, but only for this page's queue instance, not all
3103
+ // better to keep other queues in localstorage to be flushed later
3104
+ // than to pull them into memory and remove them from durable storage
3105
+ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key]);var validKey=noCompoundKey?key:[name,id,key].join('.');inMemoryStorage.setItem(validKey,value);// TODO: are we sure we want to drop clientData
3106
+ // if cookies are not available and localstorage is full?
3107
+ _this.remove(key);});this.engine=inMemoryStorage;}/**
3108
+ * Set value by key.
3109
+ */},{key:"set",value:function set(key,value){var validKey=this.createValidKey(key);if(!validKey){return;}try{// storejs that is used in localstorage engine already stringifies json
3110
+ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
3111
+ this.swapQueueStoreToInMemoryEngine();// and save it there
3112
+ this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
3113
+ * Get by Key.
3114
+ */},{key:"get",value:function get(key){var validKey=this.createValidKey(key);try{if(!validKey){return null;}var str=this.decrypt(this.engine.getItem(validKey));if(isNullOrUndefined(str)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
3115
+ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_FETCH_ERROR(key),": ").concat(err.message)));return null;}}/**
3116
+ * Remove by Key.
3117
+ */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
3118
+ * Get original engine
3119
+ */},{key:"getOriginalEngine",value:function getOriginalEngine(){return this.originalEngine;}/**
3120
+ * Decrypt values
3121
+ */},{key:"decrypt",value:function decrypt(value){if(isNullOrUndefined(value)){return null;}return this.crypto(value,'decrypt');}/**
3122
+ * Encrypt value
3123
+ */},{key:"encrypt",value:function encrypt(value){return this.crypto(value,'encrypt');}/**
3124
+ * Extension point to use with encryption plugins
3125
+ */},{key:"crypto",value:function crypto(value,mode){var noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}var extensionPointName="storage.".concat(mode);var formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return typeof formattedValue==='undefined'?value:formattedValue!==null&&formattedValue!==void 0?formattedValue:'';}/**
3126
+ * Handle errors
3127
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,"Store ".concat(this.id));}else {throw error;}}}]);return Store;}();
3128
+
3129
+ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConsentIfApplicable(state,sessionKey){var overriddenStorageType;if(state.consents.preConsent.value.enabled){var _state$consents$preCo;switch((_state$consents$preCo=state.consents.preConsent.value.storage)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.strategy){case'none':overriddenStorageType=NO_STORAGE;break;case'session':if(sessionKey!=='sessionInfo'){overriddenStorageType=NO_STORAGE;}break;case'anonymousId':if(sessionKey!=='anonymousId'){overriddenStorageType=NO_STORAGE;}break;}}return overriddenStorageType;};
3130
+
3131
+ /**
3132
+ * A service to manage stores & available storage client configurations
3133
+ */var StoreManager=/*#__PURE__*/function(){function StoreManager(pluginsManager,errorHandler,logger){_classCallCheck(this,StoreManager);_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.pluginsManager=pluginsManager;this.onError=this.onError.bind(this);}/**
3134
+ * Configure available storage client instances
3135
+ */_createClass(StoreManager,[{key:"init",value:function init(){var _config$cookieStorage,_state$storage$cookie,_state$storage$cookie2;if(this.isInitialized){return;}var loadOptions=state.loadOptions.value;var config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true},sessionStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(mergeDeepRight((_config$cookieStorage=config.cookieStorageOptions)!==null&&_config$cookieStorage!==void 0?_config$cookieStorage:{},(_state$storage$cookie=(_state$storage$cookie2=state.storage.cookie)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.value)!==null&&_state$storage$cookie!==void 0?_state$storage$cookie:{})),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions),removeUndefinedValues(config.sessionStorageOptions));this.initClientDataStores();this.isInitialized=true;}/**
3136
+ * Create store to persist data used by the SDK like session, used details etc
3137
+ */},{key:"initClientDataStores",value:function initClientDataStores(){var _this=this;this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
3138
+ // TODO: should we pass the keys for all in order to validate or leave free as v1.1?
3139
+ // Initializing all the enabled store because previous user data might be in different storage
3140
+ // that needs auto migration
3141
+ var storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(function(storageType){var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled){_this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType});}});}},{key:"initializeStorageState",value:function initializeStorageState(){var _state$loadOptions$va,_this2=this;var globalStorageType=state.storage.type.value;var entriesOptions=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.entries;// Use the storage options from post consent if anything is defined
3142
+ var postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type)||isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries)){globalStorageType=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type;entriesOptions=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries;}var trulyAnonymousTracking=true;var storageEntries={};USER_SESSION_KEYS.forEach(function(sessionKey){var _entriesOptions,_ref,_ref2;var key=sessionKey;var storageKey=sessionKey;var configuredStorageType=(_entriesOptions=entriesOptions)===null||_entriesOptions===void 0||(_entriesOptions=_entriesOptions[key])===null||_entriesOptions===void 0?void 0:_entriesOptions.type;var preConsentStorageType=getStorageTypeFromPreConsentIfApplicable(state,sessionKey);// Storage type precedence order: pre-consent strategy > entry type > global type > default
3143
+ var storageType=(_ref=(_ref2=preConsentStorageType!==null&&preConsentStorageType!==void 0?preConsentStorageType:configuredStorageType)!==null&&_ref2!==void 0?_ref2:globalStorageType)!==null&&_ref!==void 0?_ref:DEFAULT_STORAGE_TYPE;var finalStorageType=_this2.getResolvedStorageTypeForEntry(storageType,sessionKey);if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}storageEntries=_objectSpread2(_objectSpread2({},storageEntries),{},_defineProperty({},sessionKey,{type:finalStorageType,key:USER_SESSION_STORAGE_KEYS[storageKey]}));});n(function(){state.storage.type.value=globalStorageType;state.storage.entries.value=storageEntries;state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;});}},{key:"getResolvedStorageTypeForEntry",value:function getResolvedStorageTypeForEntry(storageType,sessionKey){var _getStorageEngine2,_getStorageEngine3,_getStorageEngine4,_getStorageEngine5,_getStorageEngine6;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case SESSION_STORAGE:if(!((_getStorageEngine3=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:case NO_STORAGE:break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
3144
+ if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==void 0&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==void 0&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==void 0&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
3145
+ * Create a new store
3146
+ */},{key:"setStore",value:function setStore(storeConfig){var storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
3147
+ * Retrieve a store
3148
+ */},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
3149
+ * Handle errors
3150
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);return StoreManager;}();
3151
+
3152
+ /**
3153
+ * Removes trailing slash from url
3154
+ * @param url
3155
+ * @returns url
3156
+ */var removeTrailingSlashes=function removeTrailingSlashes(url){return url&&url.endsWith('/')?removeTrailingSlashes(url.substring(0,url.length-1)):url;};/**
3157
+ * Checks if provided url is valid or not
3158
+ * @param url
3159
+ * @returns true if `url` is valid and false otherwise
3160
+ */var isValidUrl=function isValidUrl(url){try{var validUrl=new URL(url);return Boolean(validUrl);}catch(err){return false;}};/**
3161
+ * Get the referring domain from the referrer URL
3162
+ * @param referrer Page referrer
3163
+ * @returns Page referring domain
3164
+ */var getReferringDomain=function getReferringDomain(referrer){var referringDomain='';try{var url=new URL(referrer);referringDomain=url.host;}catch(error){// Do nothing
3165
+ }return referringDomain;};/**
3166
+ * Extracts UTM parameters from the URL
3167
+ * @param url Page URL
3168
+ * @returns UTM parameters
3169
+ */var extractUTMParameters=function extractUTMParameters(url){var result={};try{var urlObj=new URL(url);var UTM_PREFIX='utm_';urlObj.searchParams.forEach(function(value,sParam){if(sParam.startsWith(UTM_PREFIX)){var utmParam=sParam.substring(UTM_PREFIX.length);// Not sure why we're doing this
3170
+ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(error){// Do nothing
3171
+ }return result;};/**
3172
+ * To get the URL until the hash
3173
+ * @param url The input URL
3174
+ * @returns URL until the hash
3175
+ */var getUrlWithoutHash=function getUrlWithoutHash(url){var urlWithoutHash=url;try{var urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
3176
+ }return urlWithoutHash;};
3177
+
3178
+ var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};var validateDataPlaneUrl=function validateDataPlaneUrl(dataPlaneUrl){if(dataPlaneUrl&&!isValidUrl(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};var validateLoadArgs=function validateLoadArgs(writeKey,dataPlaneUrl){validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};
3179
+
3180
+ /**
3181
+ * Plugins to be loaded in the plugins loadOption is not defined
3182
+ */var defaultOptionalPluginsList=['BeaconQueue','Bugsnag','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
3183
+
3184
+ /**
3185
+ * A function to check given value is a number or not
3186
+ * @param num input value
3187
+ * @returns boolean
3188
+ */var isNumber=function isNumber(num){return typeof num==='number'&&!Number.isNaN(num);};/**
3189
+ * A function to check given number has minimum length or not
3190
+ * @param minimumLength minimum length
3191
+ * @param num input number
3192
+ * @returns boolean
3193
+ */var hasMinLength=function hasMinLength(minimumLength,num){return num.toString().length>=minimumLength;};/**
3194
+ * A function to check given value is a positive integer or not
3195
+ * @param num input value
3196
+ * @returns boolean
3197
+ */var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
3198
+
3199
+ var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s2;// TODO: Maybe add warnings for invalid values
3200
+ var normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$p=normalizedLoadOpts.plugins)!==null&&_normalizedLoadOpts$p!==void 0?_normalizedLoadOpts$p:defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}if(!isObjectLiteralAndNotNull((_normalizedLoadOpts$s2=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s2===void 0?void 0:_normalizedLoadOpts$s2.cookie)){var _normalizedLoadOpts$s3;(_normalizedLoadOpts$s3=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s3===void 0||delete _normalizedLoadOpts$s3.cookie;}else {var _normalizedLoadOpts$s4;normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues((_normalizedLoadOpts$s4=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s4===void 0?void 0:_normalizedLoadOpts$s4.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';// Ideally, this check is not required but URL polyfill
3201
+ // doesn't seem to throw errors for empty URLs
3202
+ // TODO: Need to improve this check to find out if the URL is valid or not
3203
+ if(configUrl){try{var configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}catch(err){logger===null||logger===void 0||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
3204
+
3205
+ /**
3206
+ * A function to filter enabled destinations and map to required properties only
3207
+ * @param destinations
3208
+ *
3209
+ * @returns Destination[]
3210
+ */var filterEnabledDestination=function filterEnabledDestination(destinations){var nativeDestinations=[];destinations.forEach(function(destination){if(destination.enabled&&!destination.deleted){nativeDestinations.push({id:destination.id,displayName:destination.destinationDefinition.displayName,config:destination.config,shouldApplyDeviceModeTransformation:destination.shouldApplyDeviceModeTransformation||false,propagateEventsUntransformedOnError:destination.propagateEventsUntransformedOnError||false,userFriendlyId:"".concat(destination.destinationDefinition.displayName.replaceAll(' ','-'),"___").concat(destination.id)});}});return nativeDestinations;};
3211
+
3212
+ var DEFAULT_REGION='US';/**
3213
+ * A function to get url from source config response
3214
+ * @param {array} urls An array of objects containing urls
3215
+ * @returns
3216
+ */var getDefaultUrlOfRegion=function getDefaultUrlOfRegion(urls){var url;if(Array.isArray(urls)&&urls.length>0){var obj=urls.find(function(elem){return elem.default===true;});if(obj&&isValidUrl(obj.url)){return obj.url;}}return url;};var validateResidencyServerRegion=function validateResidencyServerRegion(residencyServerRegion,logger){var residencyServerRegions=['US','EU'];if(residencyServerRegion&&!residencyServerRegions.includes(residencyServerRegion)){logger===null||logger===void 0||logger.warn(UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(CONFIG_MANAGER,residencyServerRegion,DEFAULT_REGION));return undefined;}return residencyServerRegion;};/**
3217
+ * A function to determine the dataPlaneUrl
3218
+ * @param {Object} dataplanes An object containing dataPlaneUrl for different region
3219
+ * @param {String} serverUrl dataPlaneUrl provided in the load call
3220
+ * @param {String} residencyServerRegion User provided residency server region
3221
+ * @param {Logger} logger logger instance
3222
+ * @returns The data plane URL string to use
3223
+ */var resolveDataPlaneUrl=function resolveDataPlaneUrl(dataplanes,serverUrl,residencyServerRegion,logger){// Check if dataPlanes object is present in source config
3224
+ if(dataplanes&&Object.keys(dataplanes).length>0){var _validateResidencySer;var region=(_validateResidencySer=validateResidencyServerRegion(residencyServerRegion,logger))!==null&&_validateResidencySer!==void 0?_validateResidencySer:DEFAULT_REGION;var regionUrlArr=dataplanes[region]||dataplanes[DEFAULT_REGION];var defaultUrl=getDefaultUrlOfRegion(regionUrlArr);if(defaultUrl){return defaultUrl;}}// return the dataPlaneUrl provided in load API(if available)
3225
+ if(serverUrl){return serverUrl;}// return undefined if data plane url can not be determined
3226
+ return undefined;};
3227
+
3228
+ var DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';var DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
3229
+
3230
+ var isErrorReportingEnabled=function isErrorReportingEnabled(sourceConfig){var _sourceConfig$statsCo;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo=sourceConfig.statsCollection)===null||_sourceConfig$statsCo===void 0||(_sourceConfig$statsCo=_sourceConfig$statsCo.errors)===null||_sourceConfig$statsCo===void 0?void 0:_sourceConfig$statsCo.enabled)===true;};var getErrorReportingProviderNameFromConfig=function getErrorReportingProviderNameFromConfig(sourceConfig){var _sourceConfig$statsCo2;return sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.errors)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.provider;};var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo3;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo3=sourceConfig.statsCollection)===null||_sourceConfig$statsCo3===void 0||(_sourceConfig$statsCo3=_sourceConfig$statsCo3.metrics)===null||_sourceConfig$statsCo3===void 0?void 0:_sourceConfig$statsCo3.enabled)===true;};
3231
+
3232
+ /**
3233
+ * Validates and normalizes the consent options provided by the user
3234
+ * @param options Consent options provided by the user
3235
+ * @returns Validated and normalized consent options
3236
+ */var getValidPostConsentOptions=function getValidPostConsentOptions(options){var validOptions={sendPageEvent:false,trackConsent:false,discardPreConsentEvents:false};if(isObjectLiteralAndNotNull(options)){var _clonedOptions$integr;var clonedOptions=clone$1(options);validOptions.storage=clonedOptions.storage;validOptions.integrations=(_clonedOptions$integr=clonedOptions.integrations)!==null&&_clonedOptions$integr!==void 0?_clonedOptions$integr:DEFAULT_INTEGRATIONS_CONFIG;validOptions.discardPreConsentEvents=clonedOptions.discardPreConsentEvents===true;validOptions.sendPageEvent=clonedOptions.sendPageEvent===true;validOptions.trackConsent=clonedOptions.trackConsent===true;if(isNonEmptyObject(clonedOptions.consentManagement)){// Override enabled value with the current state value
3237
+ validOptions.consentManagement=mergeDeepRight(clonedOptions.consentManagement,{enabled:state.consents.enabled.value});}}return validOptions;};/**
3238
+ * Validates if the input is a valid consents data
3239
+ * @param value Input consents data
3240
+ * @returns true if the input is a valid consents data else false
3241
+ */var isValidConsentsData=function isValidConsentsData(value){return isNonEmptyObject(value)||Array.isArray(value);};/**
3242
+ * Retrieves the corresponding provider and plugin name of the selected consent manager from the supported consent managers
3243
+ * @param consentManagementOpts consent management options
3244
+ * @param logger logger instance
3245
+ * @returns Corresponding provider and plugin name of the selected consent manager from the supported consent managers
3246
+ */var getConsentManagerInfo=function getConsentManagerInfo(consentManagementOpts,logger){var provider=consentManagementOpts.provider;var consentManagerPluginName=ConsentManagersToPluginNameMap[provider];if(provider&&!consentManagerPluginName){logger===null||logger===void 0||logger.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,provider,ConsentManagersToPluginNameMap));// Reset the provider value
3247
+ provider=undefined;}return {provider:provider,consentManagerPluginName:consentManagerPluginName};};/**
3248
+ * Validates and converts the consent management options into a normalized format
3249
+ * @param consentManagementOpts Consent management options provided by the user
3250
+ * @param logger logger instance
3251
+ * @returns An object containing the consent manager plugin name, initialized, enabled and consents data
3252
+ */var getConsentManagementData=function getConsentManagementData(consentManagementOpts,logger){var consentManagerPluginName;var allowedConsentIds=[];var deniedConsentIds=[];var initialized=false;var provider;var enabled=(consentManagementOpts===null||consentManagementOpts===void 0?void 0:consentManagementOpts.enabled)===true;if(isNonEmptyObject(consentManagementOpts)&&enabled){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
3253
+ var _getConsentManagerInf=getConsentManagerInfo(consentManagementOpts,logger);provider=_getConsentManagerInf.provider;consentManagerPluginName=_getConsentManagerInf.consentManagerPluginName;if(isValidConsentsData(consentManagementOpts.allowedConsentIds)){allowedConsentIds=consentManagementOpts.allowedConsentIds;initialized=true;}if(isValidConsentsData(consentManagementOpts.deniedConsentIds)){deniedConsentIds=consentManagementOpts.deniedConsentIds;initialized=true;}}var consentsData={allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};// Enable consent management only if consent manager is supported
3254
+ enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,consentManagerPluginName:consentManagerPluginName,initialized:initialized,enabled:enabled,consentsData:consentsData};};
3255
+
3256
+ /**
3257
+ * Determines the SDK url
3258
+ * @returns sdkURL
3259
+ */var getSDKUrl=function getSDKUrl(){var scripts=document.getElementsByTagName('script');var sdkURL;var scriptList=Array.prototype.slice.call(scripts);scriptList.some(function(script){var curScriptSrc=removeTrailingSlashes(script.getAttribute('src'));if(curScriptSrc){var urlMatches=curScriptSrc.match(/^.*rsa?(\.min)?\.js$/);if(urlMatches){sdkURL=curScriptSrc;return true;}}return false;});return sdkURL;};/**
3260
+ * Updates the reporting state variables from the source config data
3261
+ * @param res Source config
3262
+ * @param logger Logger instance
3263
+ */var updateReportingState=function updateReportingState(res,logger){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config);state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);if(state.reporting.isErrorReportingEnabled.value){var errReportingProvider=getErrorReportingProviderNameFromConfig(res.source.config);// Get the corresponding plugin name of the selected error reporting provider from the supported error reporting providers
3264
+ var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
3265
+ logger===null||logger===void 0||logger.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin!==null&&errReportingProviderPlugin!==void 0?errReportingProviderPlugin:ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var storageOptsFromLoad=state.loadOptions.value.storage;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger===null||logger===void 0||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===void 0||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===void 0?void 0:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
3266
+ logger===null||logger===void 0||logger.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
3267
+ var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===void 0||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}n(function(){state.storage.type.value=storageType;state.storage.cookie.value=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};var updateConsentsStateFromLoadOptions=function updateConsentsStateFromLoadOptions(logger){var _preConsentOpts$stora,_preConsentOpts$stora2,_preConsentOpts$event,_preConsentOpts$event2;var _getConsentManagement=getConsentManagementData(state.loadOptions.value.consentManagement,logger),provider=_getConsentManagement.provider,consentManagerPluginName=_getConsentManagement.consentManagerPluginName,initialized=_getConsentManagement.initialized,enabled=_getConsentManagement.enabled,consentsData=_getConsentManagement.consentsData;// Pre-consent
3268
+ var preConsentOpts=state.loadOptions.value.preConsent;var storageStrategy=(_preConsentOpts$stora=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===void 0?void 0:_preConsentOpts$stora2.strategy)!==null&&_preConsentOpts$stora!==void 0?_preConsentOpts$stora:DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;var StorageStrategies=['none','session','anonymousId'];if(isDefined(storageStrategy)&&!StorageStrategies.includes(storageStrategy)){var _preConsentOpts$stora3;storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger===null||logger===void 0||logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora3=preConsentOpts.storage)===null||_preConsentOpts$stora3===void 0?void 0:_preConsentOpts$stora3.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}var eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===void 0?void 0:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==void 0?_preConsentOpts$event:DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;var deliveryTypes=['immediate','buffer'];if(isDefined(eventsDeliveryType)&&!deliveryTypes.includes(eventsDeliveryType)){var _preConsentOpts$event3;eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger===null||logger===void 0||logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===void 0?void 0:_preConsentOpts$event3.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}n(function(){var _state$loadOptions$va;state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.initialized.value=initialized;state.consents.enabled.value=enabled;state.consents.data.value=consentsData;state.consents.provider.value=provider;state.consents.preConsent.value={// Only enable pre-consent if it is explicitly enabled and
3269
+ // if it is not already initialized and
3270
+ // if consent management is enabled
3271
+ enabled:((_state$loadOptions$va=state.loadOptions.value.preConsent)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.enabled)===true&&initialized===false&&enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType}};});};/**
3272
+ * Determines the consent management state variables from the source config data
3273
+ * @param resp Source config response
3274
+ * @param logger Logger instance
3275
+ */var updateConsentsState=function updateConsentsState(resp){var resolutionStrategy=state.consents.resolutionStrategy.value;var cmpMetadata;if(isObjectLiteralAndNotNull(resp.consentManagementMetadata)){if(state.consents.provider.value){var _resp$consentManageme,_resp$consentManageme2;resolutionStrategy=(_resp$consentManageme=(_resp$consentManageme2=resp.consentManagementMetadata.providers.find(function(p){return p.provider===state.consents.provider.value;}))===null||_resp$consentManageme2===void 0?void 0:_resp$consentManageme2.resolutionStrategy)!==null&&_resp$consentManageme!==void 0?_resp$consentManageme:state.consents.resolutionStrategy.value;}cmpMetadata=resp.consentManagementMetadata;}// If the provider is custom, then the resolution strategy is not applicable
3276
+ if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}n(function(){state.consents.metadata.value=clone$1(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};
3277
+
3278
+ /**
3279
+ * A function that determines integration SDK loading path
3280
+ * @param requiredVersion
3281
+ * @param lockIntegrationsVersion
3282
+ * @param customIntegrationsCDNPath
3283
+ * @returns
3284
+ */var getIntegrationsCDNPath=function getIntegrationsCDNPath(requiredVersion,lockIntegrationsVersion,customIntegrationsCDNPath){var integrationsCDNPath='';// Get the CDN base URL from the user provided URL if any
3285
+ if(customIntegrationsCDNPath){integrationsCDNPath=removeTrailingSlashes(customIntegrationsCDNPath);if(!integrationsCDNPath||integrationsCDNPath&&!isValidUrl(integrationsCDNPath)){throw new Error(INTG_CDN_BASE_URL_ERROR);}return integrationsCDNPath;}// Get the base path from the SDK script tag src attribute or use the default path
3286
+ var sdkURL=getSDKUrl();integrationsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_INT_DIR).join('/'):DEST_SDK_BASE_URL;// If version is not locked it will always get the latest version of the integrations
3287
+ if(lockIntegrationsVersion){integrationsCDNPath=integrationsCDNPath.replace(CDN_ARCH_VERSION_DIR,requiredVersion);}return integrationsCDNPath;};/**
3288
+ * A function that determines plugins SDK loading path
3289
+ * @param customPluginsCDNPath
3290
+ * @returns
3291
+ */var getPluginsCDNPath=function getPluginsCDNPath(customPluginsCDNPath){var pluginsCDNPath='';// Get the CDN base URL from the user provided URL if any
3292
+ if(customPluginsCDNPath){pluginsCDNPath=removeTrailingSlashes(customPluginsCDNPath);if(!pluginsCDNPath||pluginsCDNPath&&!isValidUrl(pluginsCDNPath)){throw new Error(PLUGINS_CDN_BASE_URL_ERROR);}return pluginsCDNPath;}// Get the base path from the SDK script tag src attribute or use the default path
3293
+ var sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_PLUGINS_DIR).join('/'):PLUGINS_BASE_URL;return pluginsCDNPath;};
3294
+
3295
+ var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}_createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;O(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
3296
+ * A function to validate, construct and store loadOption, lifecycle, source and destination
3297
+ * config related information in global state
3298
+ */},{key:"init",value:function init(){var _this2=this;this.attachEffects();validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);var lockIntegrationsVersion=state.loadOptions.value.lockIntegrationsVersion;// determine the path to fetch integration SDK from
3299
+ var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
3300
+ var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
3301
+ n(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(state.loadOptions.value.configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,_this2.logger);});this.getConfig();}/**
3302
+ * Handle errors
3303
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
3304
+ * A callback function that is executed once we fetch the source config response.
3305
+ * Use to construct and store information that are dependent on the sourceConfig.
3306
+ */},{key:"processConfig",value:function processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
3307
+ // We can use isErrRetryable utility method
3308
+ if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details===null||details===void 0?void 0:details.error));return;}var res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR),undefined,true);return;}// set the values in state for reporting slice
3309
+ updateReportingState(res,this.logger);// determine the dataPlane url
3310
+ var dataPlaneUrl=resolveDataPlaneUrl(res.source.dataplanes,state.lifecycle.dataPlaneUrl.value,state.loadOptions.value.residencyServer,this.logger);if(!dataPlaneUrl){this.onError(new Error(DATA_PLANE_URL_ERROR),undefined,true);return;}var nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
3311
+ n(function(){var _state$loadOptions$va;// set source related information in state
3312
+ state.source.value={config:res.source.config,id:res.source.id};// set device mode destination related information in state
3313
+ state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
3314
+ state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:[];updateConsentsState(res);// set application lifecycle state
3315
+ // Cast to string as we are sure that the value is not undefined
3316
+ state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value='configured';});}/**
3317
+ * A function to fetch source config either from /sourceConfig endpoint
3318
+ * or from getSourceConfig load option
3319
+ * @returns
3320
+ */},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){throw new Error(SOURCE_CONFIG_OPTION_ERROR);}// fetch source config from the function
3321
+ var res=sourceConfigFunc();if(res instanceof Promise){res.then(function(pRes){return _this3.processConfig(pRes);}).catch(function(err){_this3.onError(err,'SourceConfig');});}else {this.processConfig(res);}}else {// fetch source config from config url API
3322
+ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);return ConfigManager;}();
3323
+
3324
+ /**
3325
+ * To get the timezone of the user
3326
+ *
3327
+ * @returns string
3328
+ */var getTimezone=function getTimezone(){var timezone=new Date().toString().match(/([A-Z]+[+-]\d+)/);return timezone&&timezone[1]?timezone[1]:'NA';};
3329
+
3330
+ /**
3331
+ * Get the referrer URL
3332
+ * @returns The referrer URL
3333
+ */var getReferrer=function getReferrer(){var _document;return ((_document=document)===null||_document===void 0?void 0:_document.referrer)||'$direct';};/**
3334
+ * To get the canonical URL of the page
3335
+ * @returns canonical URL
3336
+ */var getCanonicalUrl=function getCanonicalUrl(){var tags=document.getElementsByTagName('link');var canonicalUrl='';for(var i=0;tags[i];i+=1){var tag=tags[i];if(tag.getAttribute('rel')==='canonical'&&!canonicalUrl){var _tag$getAttribute;canonicalUrl=(_tag$getAttribute=tag.getAttribute('href'))!==null&&_tag$getAttribute!==void 0?_tag$getAttribute:'';break;}}return canonicalUrl;};var getUserAgent=function getUserAgent(){if(isUndefined(globalThis.navigator)){return null;}var userAgent=globalThis.navigator.userAgent;var _ref=globalThis.navigator,brave=_ref.brave;// For supporting Brave browser detection,
3337
+ // add "Brave/<version>" to the user agent with the version value from the Chrome component
3338
+ if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
3339
+ // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36
3340
+ var matchedArr=userAgent.match(/(chrome)\/([\w.]+)/i);if(matchedArr){userAgent="".concat(userAgent," Brave/").concat(matchedArr[2]);}}return userAgent;};var getLanguage=function getLanguage(){var _globalThis$navigator;if(isUndefined(globalThis.navigator)){return null;}return (_globalThis$navigator=globalThis.navigator.language)!==null&&_globalThis$navigator!==void 0?_globalThis$navigator:globalThis.navigator.browserLanguage;};/**
3341
+ * Default page properties
3342
+ * @returns Default page properties
3343
+ */var getDefaultPageProperties=function getDefaultPageProperties(){var canonicalUrl=getCanonicalUrl();var path=globalThis.location.pathname;var tabUrl=globalThis.location.href;var pageUrl=tabUrl;var search=globalThis.location.search;// If valid canonical url is provided use this as page url.
3344
+ if(canonicalUrl){try{var urlObj=new URL(canonicalUrl);// If existing, query params of canonical url will be used instead of the location.search ones
3345
+ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
3346
+ }}var url=getUrlWithoutHash(pageUrl);var _document2=document,title=_document2.title;var referrer=getReferrer();return {path:path,referrer:referrer,referring_domain:getReferringDomain(referrer),search:search,title:title,url:url,tab_url:tabUrl};};
3347
+
3348
+ var POLYFILL_URL="https://polyfill.io/v3/polyfill.min.js?features=".concat(Object.keys(legacyJSEngineRequiredPolyfills).join('%2C'));var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
3349
+ var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
3350
+
3351
+ var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.logger=logger;this.errorHandler=errorHandler;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}_createClass(CapabilitiesManager,[{key:"init",value:function init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(err){this.onError(err);}}/**
3352
+ * Detect supported capabilities and set values in state
3353
+ */ // eslint-disable-next-line class-methods-use-this
3354
+ },{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;n(function(){// Storage related details
3355
+ state.capabilities.storage.isCookieStorageAvailable.value=isStorageAvailable(COOKIE_STORAGE,getStorageEngine(COOKIE_STORAGE),_this.logger);state.capabilities.storage.isLocalStorageAvailable.value=isStorageAvailable(LOCAL_STORAGE,undefined,_this.logger);state.capabilities.storage.isSessionStorageAvailable.value=isStorageAvailable(SESSION_STORAGE,undefined,_this.logger);// Browser feature detection details
3356
+ state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCHAvailable.value=hasUAClientHints();state.capabilities.isCryptoAvailable.value=hasCrypto();state.capabilities.isIE11.value=isIE11();state.capabilities.isOnline.value=globalThis.navigator.onLine;// Get page context details
3357
+ state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();state.context.timezone.value=getTimezone();if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
3358
+ O(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
3359
+ * Detect if polyfills are required and then load script from polyfill URL
3360
+ */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _state$loadOptions$va,_this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var polyfillUrl=(_state$loadOptions$va=state.loadOptions.value.polyfillURL)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POLYFILL_URL;var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&Boolean(polyfillUrl);if(shouldLoadPolyfill){var _this$externalSrcLoad;var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){// write key specific callback
3361
+ // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
3362
+ var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);var polyfillCallback=function polyfillCallback(){_this2.onReady();// Remove the entry from window so we don't leave room for calling it again
3363
+ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}(_this$externalSrcLoad=this.externalSrcLoader)===null||_this$externalSrcLoad===void 0||_this$externalSrcLoad.loadJSFile({url:polyfillUrl,id:POLYFILL_SCRIPT_ID,async:true,timeout:POLYFILL_LOAD_TIMEOUT,callback:function callback(scriptId){if(!scriptId){_this2.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID,polyfillUrl)));}else if(!isDefaultPolyfillService){_this2.onReady();}}});}else {this.onReady();}}/**
3364
+ * Attach listeners to window to observe event that update capabilities state values
3365
+ */},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;});globalThis.addEventListener('resize',debounce(function(){state.context.screen.value=getScreenDetails();},this));}/**
3366
+ * Set the lifecycle status to next phase
3367
+ */ // eslint-disable-next-line class-methods-use-this
3368
+ },{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
3369
+ * Handles error
3370
+ * @param error The error object
3371
+ */},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);return CapabilitiesManager;}();
3372
+
3373
+ var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
3374
+ var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
3375
+ // Typically, these elements are not allowed to be overridden by the user
3376
+ var CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
3377
+ var RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];
3378
+
3379
+ var MIN_SESSION_ID_LENGTH=10;/**
3380
+ * A function to validate current session and return true/false depending on that
3381
+ * @returns boolean
3382
+ */var hasSessionExpired=function hasSessionExpired(expiresAt){var timestamp=Date.now();return Boolean(!expiresAt||timestamp>expiresAt);};/**
3383
+ * A function to generate session id
3384
+ * @returns number
3385
+ */var generateSessionId=function generateSessionId(){return Date.now();};/**
3386
+ * Function to validate user provided sessionId
3387
+ * @param {number} sessionId
3388
+ * @param logger logger
3389
+ * @returns
3390
+ */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0||logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
3391
+ * A function to generate new auto tracking session
3392
+ * @param sessionTimeout current timestamp
3393
+ * @returns SessionInfo
3394
+ */var generateAutoTrackingSession=function generateAutoTrackingSession(sessionTimeout){var timestamp=Date.now();var timeout=sessionTimeout||DEFAULT_SESSION_TIMEOUT_MS;return {id:timestamp,// set the current timestamp
3395
+ expiresAt:timestamp+timeout,// set the expiry time of the session
3396
+ timeout:timeout,sessionStart:undefined,autoTrack:true};};/**
3397
+ * A function to generate new manual tracking session
3398
+ * @param id Provided sessionId
3399
+ * @param logger Logger module
3400
+ * @returns SessionInfo
3401
+ */var generateManualTrackingSession=function generateManualTrackingSession(id,logger){var sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};var isStorageTypeValidForStoringData=function isStorageTypeValidForStoringData(storageType){return Boolean(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===SESSION_STORAGE||storageType===MEMORY_STORAGE);};/**
3402
+ * Generate a new anonymousId
3403
+ * @returns string anonymousID
3404
+ */var generateAnonymousId=function generateAnonymousId(){return generateUUID();};
3405
+
3406
+ /**
3407
+ * To get the page properties for context object
3408
+ * @param pageProps Page properties
3409
+ * @returns page properties object for context
3410
+ */var getContextPageProperties=function getContextPageProperties(pageProps){// Need to get updated page details on each event as an event to notify on SPA url changes does not seem to exist
3411
+ var curPageProps=getDefaultPageProperties();var ctxPageProps={};Object.keys(curPageProps).forEach(function(key){ctxPageProps[key]=(pageProps===null||pageProps===void 0?void 0:pageProps[key])||curPageProps[key];});ctxPageProps.initial_referrer=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referrer)||state.session.initialReferrer.value;ctxPageProps.initial_referring_domain=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referring_domain)||state.session.initialReferringDomain.value;return ctxPageProps;};/**
3412
+ * Add any missing default page properties using values from options and defaults
3413
+ * @param properties Input page properties
3414
+ * @param options API options
3415
+ */var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};var pageProps=properties;// Need to get updated page details on each event as an event to notify on SPA url changes does not seem to exist
3416
+ var curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(function(key){if(isUndefined(pageProps[key])){pageProps[key]=optionsPageProps[key]||curPageProps[key];}});if(isUndefined(pageProps.initial_referrer)){pageProps.initial_referrer=optionsPageProps.initial_referrer||state.session.initialReferrer.value;}if(isUndefined(pageProps.initial_referring_domain)){pageProps.initial_referring_domain=optionsPageProps.initial_referring_domain||state.session.initialReferringDomain.value;}return pageProps;};/**
3417
+ * Utility to check for reserved keys in the input object
3418
+ * @param obj Generic object
3419
+ * @param parentKeyPath Object's parent key path
3420
+ * @param logger Logger instance
3421
+ */var checkForReservedElementsInObject=function checkForReservedElementsInObject(obj,parentKeyPath,logger){if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(function(property){if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger===null||logger===void 0||logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
3422
+ * Checks for reserved keys in traits, properties, and contextual traits
3423
+ * @param rudderEvent Generated rudder event
3424
+ * @param logger Logger instance
3425
+ */var checkForReservedElements=function checkForReservedElements(rudderEvent,logger){// properties, traits, contextualTraits are either undefined or object
3426
+ var properties=rudderEvent.properties,traits=rudderEvent.traits,context=rudderEvent.context;var contextualTraits=context.traits;checkForReservedElementsInObject(properties,'properties',logger);checkForReservedElementsInObject(traits,'traits',logger);checkForReservedElementsInObject(contextualTraits,'context.traits',logger);};/**
3427
+ * Overrides the top-level event properties with data from API options
3428
+ * @param rudderEvent Generated rudder event
3429
+ * @param options API options
3430
+ */var updateTopLevelEventElements=function updateTopLevelEventElements(rudderEvent,options){if(options.anonymousId&&isString(options.anonymousId)){// eslint-disable-next-line no-param-reassign
3431
+ rudderEvent.anonymousId=options.anonymousId;}if(isObjectLiteralAndNotNull(options.integrations)){// eslint-disable-next-line no-param-reassign
3432
+ rudderEvent.integrations=options.integrations;}if(options.originalTimestamp&&isString(options.originalTimestamp)){// eslint-disable-next-line no-param-reassign
3433
+ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
3434
+ * To merge the contextual information in API options with existing data
3435
+ * @param rudderContext Generated rudder event
3436
+ * @param options API options
3437
+ * @param logger Logger instance
3438
+ */var getMergedContext=function getMergedContext(rudderContext,options,logger){var context=rudderContext;Object.keys(options).forEach(function(key){if(!TOP_LEVEL_ELEMENTS.includes(key)&&!CONTEXT_RESERVED_ELEMENTS.includes(key)){if(key!=='context'){context=mergeDeepRight(context,_defineProperty({},key,options[key]));}else if(!isUndefined(options[key])&&isObjectLiteralAndNotNull(options[key])){var tempContext={};Object.keys(options[key]).forEach(function(e){if(!CONTEXT_RESERVED_ELEMENTS.includes(e)){tempContext[e]=options[key][e];}});context=mergeDeepRight(context,_objectSpread2({},tempContext));}else {logger===null||logger===void 0||logger.warn(INVALID_CONTEXT_OBJECT_WARNING(EVENT_MANAGER));}}});return context;};/**
3439
+ * A function to determine whether SDK should use the integration option provided in load call
3440
+ * @returns boolean
3441
+ */var shouldUseGlobalIntegrationsConfigInEvents=function shouldUseGlobalIntegrationsConfigInEvents(){return state.loadOptions.value.useGlobalIntegrationsConfigInEvents&&isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value);};/**
3442
+ * Updates rudder event object with data from the API options
3443
+ * @param rudderEvent Generated rudder event
3444
+ * @param options API options
3445
+ */var processOptions=function processOptions(rudderEvent,options){// Only allow object type for options
3446
+ if(isObjectLiteralAndNotNull(options)){updateTopLevelEventElements(rudderEvent,options);// eslint-disable-next-line no-param-reassign
3447
+ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
3448
+ * Returns the final integrations config for the event based on the global config and event's config
3449
+ * @param integrationsConfig Event's integrations config
3450
+ * @returns Final integrations config
3451
+ */var getEventIntegrationsConfig=function getEventIntegrationsConfig(integrationsConfig){var finalIntgConfig;if(shouldUseGlobalIntegrationsConfigInEvents()){finalIntgConfig=state.nativeDestinations.loadOnlyIntegrations.value;}else if(isObjectLiteralAndNotNull(integrationsConfig)){finalIntgConfig=integrationsConfig;}else {finalIntgConfig=DEFAULT_INTEGRATIONS_CONFIG;}return finalIntgConfig;};/**
3452
+ * Enrich the base event object with data from state and the API options
3453
+ * @param rudderEvent RudderEvent object
3454
+ * @param options API options
3455
+ * @param pageProps Page properties
3456
+ * @param logger logger
3457
+ * @returns Enriched RudderEvent object
3458
+ */var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var _state$storage$entrie;var commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds),allowedConsentIds:clone$1(state.consents.data.value.allowedConsentIds),provider:state.consents.provider.value,resolutionStrategy:state.consents.resolutionStrategy.value},'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps),timezone:state.context.timezone.value},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(!isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value.anonymousId)===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type)){// Generate new anonymous id for each request
3459
+ commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to string as the user session manager will take care of initializing the value
3460
+ commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
3461
+ if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){var _state$storage$entrie2;commonEventData.context.traits=((_state$storage$entrie2=state.storage.entries.value.userTraits)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type)!==NO_STORAGE?clone$1(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type==='group'){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){var _state$storage$entrie3;commonEventData.traits=((_state$storage$entrie3=state.storage.entries.value.groupTraits)===null||_state$storage$entrie3===void 0?void 0:_state$storage$entrie3.type)!==NO_STORAGE?clone$1(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
3462
+ // matching with v1.1 payload
3463
+ if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options);checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
3464
+ processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
3465
+
3466
+ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logger){_classCallCheck(this,RudderEventFactory);this.logger=logger;}/**
3467
+ * Generate a 'page' event based on the user-input fields
3468
+ * @param category Page's category
3469
+ * @param name Page name
3470
+ * @param properties Page properties
3471
+ * @param options API options
3472
+ */_createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==void 0?properties:{};props.name=name;props.category=category;props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
3473
+ * Generate a 'track' event based on the user-input fields
3474
+ * @param event The event name
3475
+ * @param properties Event properties
3476
+ * @param options API options
3477
+ */},{key:"generateTrackEvent",value:function generateTrackEvent(event,properties,options){var trackEvent={properties:properties,event:event,type:'track'};return getEnrichedEvent(trackEvent,options,undefined,this.logger);}/**
3478
+ * Generate an 'identify' event based on the user-input fields
3479
+ * @param userId New user ID
3480
+ * @param traits new traits
3481
+ * @param options API options
3482
+ */},{key:"generateIdentifyEvent",value:function generateIdentifyEvent(userId,traits,options){var identifyEvent={userId:userId,type:'identify',context:{traits:traits}};return getEnrichedEvent(identifyEvent,options,undefined,this.logger);}/**
3483
+ * Generate an 'alias' event based on the user-input fields
3484
+ * @param to New user ID
3485
+ * @param from Old user ID
3486
+ * @param options API options
3487
+ */},{key:"generateAliasEvent",value:function generateAliasEvent(to,from,options){var aliasEvent={previousId:from,type:'alias'};var enrichedEvent=getEnrichedEvent(aliasEvent,options,undefined,this.logger);// override the User ID from the API inputs
3488
+ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
3489
+ * Generate a 'group' event based on the user-input fields
3490
+ * @param groupId New group ID
3491
+ * @param traits new group traits
3492
+ * @param options API options
3493
+ */},{key:"generateGroupEvent",value:function generateGroupEvent(groupId,traits,options){var groupEvent={type:'group'};if(groupId){groupEvent.groupId=groupId;}if(traits){groupEvent.traits=traits;}return getEnrichedEvent(groupEvent,options,undefined,this.logger);}/**
3494
+ * Generates a new RudderEvent object based on the user-input fields
3495
+ * @param event API event parameters object
3496
+ * @returns A RudderEvent object
3497
+ */},{key:"create",value:function create(event){var eventObj;switch(event.type){case'page':eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case'track':eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case'identify':eventObj=this.generateIdentifyEvent(event.userId,event.traits,event.options);break;case'alias':eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case'group':eventObj=this.generateGroupEvent(event.groupId,event.traits,event.options);break;}return eventObj;}}]);return RudderEventFactory;}();
3498
+
3499
+ /**
3500
+ * A service to generate valid event payloads and queue them for processing
3501
+ */var EventManager=/*#__PURE__*/function(){/**
3502
+ *
3503
+ * @param eventRepository Event repository instance
3504
+ * @param userSessionManager UserSession Manager instance
3505
+ * @param errorHandler Error handler object
3506
+ * @param logger Logger object
3507
+ */function EventManager(eventRepository,userSessionManager,errorHandler,logger){_classCallCheck(this,EventManager);this.eventRepository=eventRepository;this.userSessionManager=userSessionManager;this.errorHandler=errorHandler;this.logger=logger;this.eventFactory=new RudderEventFactory(this.logger);this.onError=this.onError.bind(this);}/**
3508
+ * Initializes the event manager
3509
+ */_createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
3510
+ * Consumes a new incoming event
3511
+ * @param event Incoming event data
3512
+ */},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);if(rudderEvent){this.eventRepository.enqueue(rudderEvent,event.callback);}else {this.onError(new Error(EVENT_OBJECT_GENERATION_ERROR));}}/**
3513
+ * Handles error
3514
+ * @param error The error object
3515
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);return EventManager;}();
3516
+
3517
+ var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,storeManager){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.onError=this.onError.bind(this);}/**
3518
+ * Initialize User session with values from storage
3519
+ */_createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
3520
+ this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
3521
+ this.setUserId(this.getUserId());this.setUserTraits(this.getUserTraits());this.setGroupId(this.getGroupId());this.setGroupTraits(this.getGroupTraits());this.setAnonymousId(this.getAnonymousId(state.loadOptions.value.anonymousIdOptions));this.setAuthToken(this.getAuthToken());this.setInitialReferrerInfo();this.configureSessionTracking();}},{key:"configureSessionTracking",value:function configureSessionTracking(){var sessionInfo=this.getSessionInfo();if(this.isPersistenceEnabledForStorageEntry('sessionInfo')){var _this$getSessionInfo;var configuredSessionTrackingInfo=this.getConfiguredSessionTrackingInfo();var persistedSessionInfo=(_this$getSessionInfo=this.getSessionInfo())!==null&&_this$getSessionInfo!==void 0?_this$getSessionInfo:defaultSessionInfo;sessionInfo=_objectSpread2(_objectSpread2(_objectSpread2({},persistedSessionInfo),configuredSessionTrackingInfo),{},{autoTrack:configuredSessionTrackingInfo.autoTrack&&persistedSessionInfo.manualTrack!==true});}this.setSessionInfo(sessionInfo);}},{key:"setInitialReferrerInfo",value:function setInitialReferrerInfo(){var persistedInitialReferrer=this.getInitialReferrer();var persistedInitialReferringDomain=this.getInitialReferringDomain();if(persistedInitialReferrer&&persistedInitialReferringDomain){this.setInitialReferrer(persistedInitialReferrer);this.setInitialReferringDomain(persistedInitialReferringDomain);}else {var initialReferrer=persistedInitialReferrer||getReferrer();this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}}},{key:"isPersistenceEnabledForStorageEntry",value:function isPersistenceEnabledForStorageEntry(entryName){var _state$storage$entrie;return isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value[entryName])===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type);}},{key:"migrateDataFromPreviousStorage",value:function migrateDataFromPreviousStorage(){var _this=this;var entries=state.storage.entries.value;var storageTypesForMigration=[COOKIE_STORAGE,LOCAL_STORAGE,SESSION_STORAGE];Object.keys(entries).forEach(function(entry){var _entries$key,_this$storeManager;var key=entry;var currentStorage=(_entries$key=entries[key])===null||_entries$key===void 0?void 0:_entries$key.type;var curStore=(_this$storeManager=_this.storeManager)===null||_this$storeManager===void 0?void 0:_this$storeManager.getStore(storageClientDataStoreNameMap[currentStorage]);if(curStore){storageTypesForMigration.forEach(function(storage){var _this$storeManager2;var store=(_this$storeManager2=_this.storeManager)===null||_this$storeManager2===void 0?void 0:_this$storeManager2.getStore(storageClientDataStoreNameMap[storage]);if(store&&storage!==currentStorage){var value=store.get(USER_SESSION_STORAGE_KEYS[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore.set(USER_SESSION_STORAGE_KEYS[key],value);}store.remove(USER_SESSION_STORAGE_KEYS[key]);}});}});}},{key:"migrateStorageIfNeeded",value:function migrateStorageIfNeeded(){var _this2=this;if(!state.storage.migrate.value){return;}var persistentStoreNames=[CLIENT_DATA_STORE_COOKIE,CLIENT_DATA_STORE_LS,CLIENT_DATA_STORE_SESSION];var stores=[];persistentStoreNames.forEach(function(storeName){var _this2$storeManager;var store=(_this2$storeManager=_this2.storeManager)===null||_this2$storeManager===void 0?void 0:_this2$storeManager.getStore(storeName);if(store){stores.push(store);}});Object.keys(USER_SESSION_STORAGE_KEYS).forEach(function(storageKey){var storageEntry=USER_SESSION_STORAGE_KEYS[storageKey];stores.forEach(function(store){var _this2$pluginsManager;var migratedVal=(_this2$pluginsManager=_this2.pluginsManager)===null||_this2$pluginsManager===void 0?void 0:_this2$pluginsManager.invokeSingle('storage.migrate',storageEntry,store.engine,_this2.errorHandler,_this2.logger);// Skip setting the value if it is null or undefined
3522
+ // as those values indicate there is no need for migration or
3523
+ // migration failed
3524
+ if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}},{key:"getConfiguredSessionTrackingInfo",value:function getConfiguredSessionTrackingInfo(){var _state$loadOptions$va,_state$loadOptions$va2;var autoTrack=((_state$loadOptions$va=state.loadOptions.value.sessions)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.autoTrack)!==false;// Do not validate any further if autoTrack is disabled
3525
+ if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTimeout=(_state$loadOptions$va2=state.loadOptions.value.sessions)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.timeout;if(!isPositiveInteger(configuredSessionTimeout)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
3526
+ // and will proceed with it
3527
+ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}return {timeout:timeout,autoTrack:autoTrack};}/**
3528
+ * Handles error
3529
+ * @param error The error object
3530
+ */},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER);}else {throw error;}}/**
3531
+ * A function to sync values in storage
3532
+ * @param sessionKey
3533
+ * @param value
3534
+ */},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey,_entries$sessionKey2;var entries=state.storage.entries.value;var storage=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;var key=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;if(isStorageTypeValidForStoringData(storage)){var _this$storeManager3;var curStore=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storageClientDataStoreNameMap[storage]);if(value&&isString(value)||isNonEmptyObject(value)){curStore===null||curStore===void 0||curStore.set(key,value);}else {curStore===null||curStore===void 0||curStore.remove(key);}}}/**
3535
+ * Function to update storage whenever state value changes
3536
+ */},{key:"registerEffects",value:function registerEffects(){var _this3=this;// This will work as long as the user session entry key names are same as the state keys
3537
+ USER_SESSION_KEYS.forEach(function(sessionKey){O(function(){_this3.syncValueToStorage(sessionKey,state.session[sessionKey].value);});});}/**
3538
+ * Sets anonymous id in the following precedence:
3539
+ *
3540
+ * 1. anonymousId: Id directly provided to the function.
3541
+ * 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
3542
+ * using parseLinker util.
3543
+ * 3. generateUUID: A new unique id is generated and assigned.
3544
+ */},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager;var linkerPluginsResult=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
3545
+ * Fetches anonymousId
3546
+ * @param options option to fetch it from external source
3547
+ * @returns anonymousId
3548
+ */},{key:"getAnonymousId",value:function getAnonymousId(options){var _state$storage$entrie2;var storage=(_state$storage$entrie2=state.storage.entries.value.anonymousId)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type;// fetch the anonymousId from storage
3549
+ if(isStorageTypeValidForStoringData(storage)){var persistedAnonymousId=this.getEntryValue('anonymousId');if(!persistedAnonymousId&&options){var _this$pluginsManager2;// fetch anonymousId from external source
3550
+ var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0?void 0:_this$pluginsManager2.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||generateAnonymousId();}return state.session.anonymousId.value;}},{key:"getEntryValue",value:function getEntryValue(sessionKey){var _entries$sessionKey3;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey3=entries[sessionKey])===null||_entries$sessionKey3===void 0?void 0:_entries$sessionKey3.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager4,_entries$sessionKey4,_store$get;var store=(_this$storeManager4=this.storeManager)===null||_this$storeManager4===void 0?void 0:_this$storeManager4.getStore(storageClientDataStoreNameMap[storageType]);var storageKey=(_entries$sessionKey4=entries[sessionKey])===null||_entries$sessionKey4===void 0?void 0:_entries$sessionKey4.key;return (_store$get=store===null||store===void 0?void 0:store.get(storageKey))!==null&&_store$get!==void 0?_store$get:null;}return null;}/**
3551
+ * Fetches User Id
3552
+ * @returns
3553
+ */},{key:"getUserId",value:function getUserId(){return this.getEntryValue('userId');}/**
3554
+ * Fetches User Traits
3555
+ * @returns
3556
+ */},{key:"getUserTraits",value:function getUserTraits(){return this.getEntryValue('userTraits');}/**
3557
+ * Fetches Group Id
3558
+ * @returns
3559
+ */},{key:"getGroupId",value:function getGroupId(){return this.getEntryValue('groupId');}/**
3560
+ * Fetches Group Traits
3561
+ * @returns
3562
+ */},{key:"getGroupTraits",value:function getGroupTraits(){return this.getEntryValue('groupTraits');}/**
3563
+ * Fetches Initial Referrer
3564
+ * @returns
3565
+ */},{key:"getInitialReferrer",value:function getInitialReferrer(){return this.getEntryValue('initialReferrer');}/**
3566
+ * Fetches Initial Referring domain
3567
+ * @returns
3568
+ */},{key:"getInitialReferringDomain",value:function getInitialReferringDomain(){return this.getEntryValue('initialReferringDomain');}/**
3569
+ * Fetches session tracking information from storage
3570
+ * @returns
3571
+ */},{key:"getSessionInfo",value:function getSessionInfo(){return this.getEntryValue('sessionInfo');}/**
3572
+ * Fetches auth token from storage
3573
+ * @returns
3574
+ */},{key:"getAuthToken",value:function getAuthToken(){return this.getEntryValue('authToken');}/**
3575
+ * If session is active it returns the sessionId
3576
+ * @returns
3577
+ */},{key:"getSessionId",value:function getSessionId(){var sessionInfo=state.session.sessionInfo.value;if(sessionInfo.autoTrack&&!hasSessionExpired(sessionInfo.expiresAt)||sessionInfo.manualTrack){var _sessionInfo$id;return (_sessionInfo$id=sessionInfo.id)!==null&&_sessionInfo$id!==void 0?_sessionInfo$id:null;}return null;}/**
3578
+ * A function to update current session info after each event call
3579
+ */},{key:"refreshSession",value:function refreshSession(){var sessionInfo=state.session.sessionInfo.value;if(sessionInfo.autoTrack||sessionInfo.manualTrack){if(sessionInfo.autoTrack){this.startOrRenewAutoTracking();}// Re-assigning the variable with the same value intentionally as
3580
+ // startOrRenewAutoTracking() will update the sessionInfo value
3581
+ sessionInfo=state.session.sessionInfo.value;if(sessionInfo.sessionStart===undefined){state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:true});}else if(sessionInfo.sessionStart){state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:false});}}}/**
3582
+ * Reset state values
3583
+ * @param resetAnonymousId
3584
+ * @param noNewSessionStart
3585
+ * @returns
3586
+ */},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var _this4=this;var session=state.session;var _session$sessionInfo$=session.sessionInfo.value,manualTrack=_session$sessionInfo$.manualTrack,autoTrack=_session$sessionInfo$.autoTrack;n(function(){session.userId.value=DEFAULT_USER_SESSION_VALUES.userId;session.userTraits.value=DEFAULT_USER_SESSION_VALUES.userTraits;session.groupId.value=DEFAULT_USER_SESSION_VALUES.groupId;session.groupTraits.value=DEFAULT_USER_SESSION_VALUES.groupTraits;session.authToken.value=DEFAULT_USER_SESSION_VALUES.authToken;if(resetAnonymousId){// This will generate a new anonymous ID
3587
+ _this4.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;_this4.startOrRenewAutoTracking();}else if(manualTrack){_this4.startManualTrackingInternal();}});}},{key:"setSessionInfo",value:function setSessionInfo(sessionInfo){state.session.sessionInfo.value=this.isPersistenceEnabledForStorageEntry('sessionInfo')?sessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;// If auto session tracking is enabled start the session tracking
3588
+ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}/**
3589
+ * Set user Id
3590
+ * @param userId
3591
+ */},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
3592
+ * Set user traits
3593
+ * @param traits
3594
+ */},{key:"setUserTraits",value:function setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&traits?mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==void 0?_state$session$userTr:{},traits):DEFAULT_USER_SESSION_VALUES.userTraits;}/**
3595
+ * Set group Id
3596
+ * @param groupId
3597
+ */},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
3598
+ * Set group traits
3599
+ * @param traits
3600
+ */},{key:"setGroupTraits",value:function setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&traits?mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==void 0?_state$session$groupT:{},traits):DEFAULT_USER_SESSION_VALUES.groupTraits;}/**
3601
+ * Set initial referrer
3602
+ * @param referrer
3603
+ */},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
3604
+ * Set initial referring domain
3605
+ * @param {String} referringDomain
3606
+ */},{key:"setInitialReferringDomain",value:function setInitialReferringDomain(referringDomain){state.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry('initialReferringDomain')&&referringDomain?referringDomain:DEFAULT_USER_SESSION_VALUES.initialReferringDomain;}/**
3607
+ * A function to check for existing session details and depending on that create a new session
3608
+ */},{key:"startOrRenewAutoTracking",value:function startOrRenewAutoTracking(){var sessionInfo=state.session.sessionInfo.value;if(hasSessionExpired(sessionInfo.expiresAt)){state.session.sessionInfo.value=generateAutoTrackingSession(sessionInfo.timeout);}else {var timestamp=Date.now();var timeout=sessionInfo.timeout;state.session.sessionInfo.value=mergeDeepRight(sessionInfo,{expiresAt:timestamp+timeout// set the expiry time of the session
3609
+ });}}/**
3610
+ * A function method to start a manual session
3611
+ * @param {number} id session identifier
3612
+ * @returns
3613
+ */},{key:"start",value:function start(id){state.session.sessionInfo.value=generateManualTrackingSession(id,this.logger);}/**
3614
+ * An internal function to start manual session
3615
+ */},{key:"startManualTrackingInternal",value:function startManualTrackingInternal(){this.start(Date.now());}/**
3616
+ * A public method to end an ongoing session.
3617
+ */},{key:"end",value:function end(){state.session.sessionInfo.value={};}/**
3618
+ * Set auth token
3619
+ * @param userId
3620
+ */},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);return UserSessionManager;}();
3621
+
3622
+ /**
3623
+ * A buffer queue to serve as a store for any type of data
3624
+ */var BufferQueue=/*#__PURE__*/function(){function BufferQueue(){_classCallCheck(this,BufferQueue);this.items=[];}_createClass(BufferQueue,[{key:"enqueue",value:function enqueue(item){this.items.push(item);}},{key:"dequeue",value:function dequeue(){if(this.items.length===0){return null;}return this.items.shift();}},{key:"isEmpty",value:function isEmpty(){return this.items.length===0;}},{key:"size",value:function size(){return this.items.length;}},{key:"clear",value:function clear(){this.items=[];}}]);return BufferQueue;}();
3625
+
3626
+ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
3627
+
3628
+ /**
3629
+ * Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
3630
+ * @param eventIntgConfig User supplied integrations config at event level
3631
+ * @param destinationsIntgConfig Cumulative integrations config from all destinations
3632
+ * @returns Filtered user supplied integrations config
3633
+ */var getOverriddenIntegrationOptions=function getOverriddenIntegrationOptions(eventIntgConfig,destinationsIntgConfig){return Object.keys(eventIntgConfig).filter(function(intgName){return eventIntgConfig[intgName]!==true||!destinationsIntgConfig[intgName];}).reduce(function(obj,key){var retVal=clone$1(obj);retVal[key]=eventIntgConfig[key];return retVal;},{});};/**
3634
+ * Returns the event object with final integrations config
3635
+ * @param event RudderEvent object
3636
+ * @param state Application state
3637
+ * @returns Mutated event with final integrations config
3638
+ */var getFinalEvent=function getFinalEvent(event,state){var _event$integrations;var finalEvent=clone$1(event);// Merge the destination specific integrations config with the event's integrations config
3639
+ // In general, the preference is given to the event's integrations config
3640
+ var eventIntgConfig=(_event$integrations=event.integrations)!==null&&_event$integrations!==void 0?_event$integrations:DEFAULT_INTEGRATIONS_CONFIG;var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var overriddenIntgOpts=getOverriddenIntegrationOptions(eventIntgConfig,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};var shouldBufferEventsForPreConsent=function shouldBufferEventsForPreConsent(state){var _state$consents$preCo,_state$consents$preCo2,_state$consents$preCo3;return state.consents.preConsent.value.enabled&&((_state$consents$preCo=state.consents.preConsent.value.events)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.delivery)==='buffer'&&(((_state$consents$preCo2=state.consents.preConsent.value.storage)===null||_state$consents$preCo2===void 0?void 0:_state$consents$preCo2.strategy)==='session'||((_state$consents$preCo3=state.consents.preConsent.value.storage)===null||_state$consents$preCo3===void 0?void 0:_state$consents$preCo3.strategy)==='none');};
3641
+
3642
+ /**
3643
+ * Event repository class responsible for queuing events for further processing and delivery
3644
+ */var EventRepository=/*#__PURE__*/function(){/**
3645
+ *
3646
+ * @param pluginsManager Plugins manager instance
3647
+ * @param storeManager Store Manager instance
3648
+ * @param errorHandler Error handler object
3649
+ * @param logger Logger object
3650
+ */function EventRepository(pluginsManager,storeManager,errorHandler,logger){_classCallCheck(this,EventRepository);this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.logger=logger;this.httpClient=new HttpClient(errorHandler,logger);this.storeManager=storeManager;this.onError=this.onError.bind(this);}/**
3651
+ * Initializes the event repository
3652
+ */_createClass(EventRepository,[{key:"init",value:function init(){var _this=this;this.dataplaneEventsQueue=this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".init"),state,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.dmtEventsQueue=this.pluginsManager.invokeSingle("".concat(DMT_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger);// Start the queue once the client destinations are ready
3653
+ O(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve,_this$dmtEventsQueue;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===void 0||_this$destinationsEve.start();(_this$dmtEventsQueue=_this.dmtEventsQueue)===null||_this$dmtEventsQueue===void 0||_this$dmtEventsQueue.start();}});var bufferEventsBeforeConsent=shouldBufferEventsForPreConsent(state);// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
3654
+ // However, events will be enqueued for now.
3655
+ // At the time of processing the events, the integrations config data from destinations
3656
+ // is merged into the event object
3657
+ var timeoutId;O(function(){var _this$dataplaneEvents;var shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;var hybridDestExist=state.nativeDestinations.activeDestinations.value.some(function(dest){return isHybridModeDestination(dest);});if((hybridDestExist===false||shouldBufferDpEvents===false)&&!bufferEventsBeforeConsent&&((_this$dataplaneEvents=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents===void 0?void 0:_this$dataplaneEvents.scheduleTimeoutActive)!==true){var _this$dataplaneEvents2;globalThis.clearTimeout(timeoutId);(_this$dataplaneEvents2=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents2===void 0||_this$dataplaneEvents2.start();}});// Force start the data plane events queue processing after a timeout
3658
+ if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(function(){var _this$dataplaneEvents3;if(((_this$dataplaneEvents3=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents3===void 0?void 0:_this$dataplaneEvents3.scheduleTimeoutActive)!==true){var _this$dataplaneEvents4;(_this$dataplaneEvents4=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents4===void 0||_this$dataplaneEvents4.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}},{key:"resume",value:function resume(){var _this$dataplaneEvents5;if(((_this$dataplaneEvents5=this.dataplaneEventsQueue)===null||_this$dataplaneEvents5===void 0?void 0:_this$dataplaneEvents5.scheduleTimeoutActive)!==true){var _this$dataplaneEvents7;if(state.consents.postConsent.value.discardPreConsentEvents){var _this$dataplaneEvents6,_this$destinationsEve2;(_this$dataplaneEvents6=this.dataplaneEventsQueue)===null||_this$dataplaneEvents6===void 0||_this$dataplaneEvents6.clear();(_this$destinationsEve2=this.destinationsEventsQueue)===null||_this$destinationsEve2===void 0||_this$destinationsEve2.clear();}(_this$dataplaneEvents7=this.dataplaneEventsQueue)===null||_this$dataplaneEvents7===void 0||_this$dataplaneEvents7.start();}}/**
3659
+ * Enqueues the event for processing
3660
+ * @param event RudderEvent object
3661
+ * @param callback API callback function
3662
+ */},{key:"enqueue",value:function enqueue(event,callback){var dpQEvent=getFinalEvent(event,state);this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);var dQEvent=clone$1(event);this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);// Invoke the callback if it exists
3663
+ try{// Using the event sent to the data plane queue here
3664
+ // to ensure the mutated (if any) event is sent to the callback
3665
+ callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
3666
+ * Handles error
3667
+ * @param error The error object
3668
+ * @param customMessage a message
3669
+ * @param shouldAlwaysThrow if it should throw or use logger
3670
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);return EventRepository;}();
3671
+
3672
+ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};
3673
+
3674
+ /*
3675
+ * Analytics class with lifecycle based on state ad user triggered events
3676
+ */var Analytics=/*#__PURE__*/function(){/**
3677
+ * Initialize services and components or use default ones if singletons
3678
+ */function Analytics(){_classCallCheck(this,Analytics);this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.capabilitiesManager=new CapabilitiesManager(this.errorHandler,this.logger);this.httpClient=defaultHttpClient;}/**
3679
+ * Start application lifecycle if not already started
3680
+ */_createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}var clonedDataPlaneUrl=clone$1(dataPlaneUrl);var clonedLoadOptions=clone$1(loadOptions);// dataPlaneUrl is not provided
3681
+ if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
3682
+ n(function(){state.lifecycle.writeKey.value=writeKey;state.lifecycle.dataPlaneUrl.value=clonedDataPlaneUrl;state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,clonedLoadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
3683
+ if(state.loadOptions.value.logLevel){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.loadOptions.value.logLevel);}// Expose state to global objects
3684
+ setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
3685
+ // State application lifecycle
3686
+ this.startLifecycle();}// Start lifecycle methods
3687
+ /**
3688
+ * Orchestrate the lifecycle of the application phases/status
3689
+ */},{key:"startLifecycle",value:function startLifecycle(){var _this=this;O(function(){try{switch(state.lifecycle.status.value){case'mounted':_this.onMounted();break;case'browserCapabilitiesReady':_this.onBrowserCapabilitiesReady();break;case'configured':_this.onConfigured();break;case'pluginsLoading':break;case'pluginsReady':_this.onPluginsReady();break;case'initialized':_this.onInitialized();break;case'loaded':_this.onLoaded();break;case'destinationsLoading':break;case'destinationsReady':_this.onDestinationsReady();break;case'ready':_this.onReady();break;default:break;}}catch(err){var issue='Failed to load the SDK';_this.errorHandler.onError(getMutatedError(err,issue),ANALYTICS_CORE);}});}},{key:"onBrowserCapabilitiesReady",value:function onBrowserCapabilitiesReady(){// initialize the preloaded events enqueuing
3690
+ retrievePreloadBufferEvents(this);this.prepareInternalServices();this.loadConfig();}},{key:"onLoaded",value:function onLoaded(){this.processBufferedEvents();// Short-circuit the life cycle and move to the ready state if pre-consent behavior is enabled
3691
+ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value='ready';}else {this.loadDestinations();}}/**
3692
+ * Load browser polyfill if required
3693
+ */},{key:"onMounted",value:function onMounted(){this.capabilitiesManager.init();}/**
3694
+ * Enqueue in SDK preload buffer events, used from preloadBuffer component
3695
+ */},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone$1(bufferedEvent));});}}/**
3696
+ * Process the buffer preloaded events by passing their arguments to the respective facade methods
3697
+ */},{key:"processDataInPreloadBuffer",value:function processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){var eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent(_toConsumableArray(eventToProcess),this);}}}},{key:"prepareInternalServices",value:function prepareInternalServices(){this.pluginsManager=new PluginsManager(defaultPluginEngine,this.errorHandler,this.logger);this.storeManager=new StoreManager(this.pluginsManager,this.errorHandler,this.logger);this.configManager=new ConfigManager(this.httpClient,this.errorHandler,this.logger);this.userSessionManager=new UserSessionManager(this.errorHandler,this.logger,this.pluginsManager,this.storeManager);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
3698
+ * Load configuration
3699
+ */},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}(_this$configManager=this.configManager)===null||_this$configManager===void 0||_this$configManager.init();}/**
3700
+ * Initialize the storage and event queue
3701
+ */},{key:"onPluginsReady",value:function onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.externalSrcLoader);// Initialize storage
3702
+ (_this$storeManager=this.storeManager)===null||_this$storeManager===void 0||_this$storeManager.init();(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===void 0||_this$userSessionMana.init();// Initialize the appropriate consent manager plugin
3703
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0||_this$pluginsManager.invokeSingle("consentManager.init",state,this.logger);if(state.consents.preConsent.value.enabled===false){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0||_this$pluginsManager2.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}}// Initialize event manager
3704
+ (_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
3705
+ state.lifecycle.status.value='initialized';}/**
3706
+ * Load plugins
3707
+ */},{key:"onConfigured",value:function onConfigured(){var _this$pluginsManager3;(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0||_this$pluginsManager3.init();// TODO: are we going to enable custom plugins to be passed as load options?
3708
+ // registerCustomPlugins(state.loadOptions.value.customPlugins);
3709
+ }/**
3710
+ * Trigger onLoaded callback if any is provided in config & emit initialised event
3711
+ */},{key:"onInitialized",value:function onInitialized(){// Process any preloaded events
3712
+ this.processDataInPreloadBuffer();// TODO: we need to avoid passing the window object to the callback function
3713
+ // as this will prevent us from supporting multiple SDK instances in the same page
3714
+ // Execute onLoaded callback if provided in load options
3715
+ if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
3716
+ n(function(){state.lifecycle.loaded.value=true;state.lifecycle.status.value='loaded';});this.initialized=true;// Emit an event to use as substitute to the onLoaded callback
3717
+ dispatchSDKEvent('RSA_Initialised');}/**
3718
+ * Emit ready event
3719
+ */ // eslint-disable-next-line class-methods-use-this
3720
+ },{key:"onReady",value:function onReady(){var _this3=this;state.eventBuffer.readyCallbacksArray.value.forEach(function(callback){try{callback();}catch(err){_this3.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}});// Emit an event to use as substitute to the ready callback
3721
+ dispatchSDKEvent('RSA_Ready');}/**
3722
+ * Consume preloaded events buffer
3723
+ */},{key:"processBufferedEvents",value:function processBufferedEvents(){var _this4=this;// Process buffered events
3724
+ state.eventBuffer.toBeProcessedArray.value.forEach(function(bufferedItem){var methodName=bufferedItem[0];if(isFunction(_this4[methodName])){var _ref;(_ref=_this4)[methodName].apply(_ref,_toConsumableArray(bufferedItem.slice(1)));}});state.eventBuffer.toBeProcessedArray.value=[];}/**
3725
+ * Load device mode destinations
3726
+ */},{key:"loadDestinations",value:function loadDestinations(){var _this$pluginsManager4,_this$pluginsManager5;if(state.nativeDestinations.clientDestinationsReady.value){return;}// Set in state the desired activeDestinations to inject in DOM
3727
+ (_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0||_this$pluginsManager4.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);var totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value='destinationsReady';return;}// Start loading native integration scripts and create instances
3728
+ state.lifecycle.status.value='destinationsLoading';(_this$pluginsManager5=this.pluginsManager)===null||_this$pluginsManager5===void 0||_this$pluginsManager5.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
3729
+ O(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){n(function(){state.lifecycle.status.value='destinationsReady';state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
3730
+ * Move to the ready state
3731
+ */ // eslint-disable-next-line class-methods-use-this
3732
+ },{key:"onDestinationsReady",value:function onDestinationsReady(){// May be do any destination specific actions here
3733
+ // Mark the ready status if not already done
3734
+ if(state.lifecycle.status.value!=='ready'){state.lifecycle.status.value='ready';}}// End lifecycle methods
3735
+ // Start consumer exposed methods
3736
+ },{key:"ready",value:function ready(callback){var type='ready';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,callback]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!isFunction(callback)){this.logger.error(READY_API_CALLBACK_ERROR(READY_API));return;}/**
3737
+ * If destinations are loaded or no integration is available for loading
3738
+ * execute the callback immediately else push the callbacks to a queue that
3739
+ * will be executed after loading completes
3740
+ */if(state.lifecycle.status.value==='ready'){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}else {state.eventBuffer.readyCallbacksArray.value.push(callback);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
3741
+ // Send automatic ad blocked page event if ad-blockers are detected on the page
3742
+ // Check page category to avoid infinite loop
3743
+ if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){this.page(pageArgumentsToCallOptions(ADBLOCK_PAGE_CATEGORY,ADBLOCK_PAGE_NAME,{// 'title' is intentionally omitted as it does not make sense
3744
+ // in v3 implementation
3745
+ path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type:type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
3746
+ if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0||_this$eventManager4.addEvent({type:type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"alias",value:function alias(payload){var _ref2,_payload$from,_this$userSessionMana4,_this$userSessionMana5,_this$eventManager5;var type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var previousId=(_ref2=(_payload$from=payload.from)!==null&&_payload$from!==void 0?_payload$from:(_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===void 0?void 0:_this$userSessionMana4.getUserId())!==null&&_ref2!==void 0?_ref2:(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===void 0?void 0:_this$userSessionMana5.getAnonymousId();(_this$eventManager5=this.eventManager)===null||_this$eventManager5===void 0||_this$eventManager5.addEvent({type:type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}},{key:"group",value:function group(payload){var _this$userSessionMana7,_this$eventManager6;var type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
3747
+ if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0||_this$userSessionMana6.setGroupId(payload.groupId);}(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0||_this$userSessionMana7.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===void 0||_this$eventManager6.addEvent({type:type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(resetAnonymousId){var _this$userSessionMana8;var type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,resetAnonymousId]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation, resetAnonymousId: ").concat(resetAnonymousId));(_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===void 0||_this$userSessionMana8.reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$userSessionMana9;return (_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===void 0?void 0:_this$userSessionMana9.getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var _this$userSessionMana10;var type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
3748
+ if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,anonymousId,rudderAmpLinkerParam]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0||_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
3749
+ },{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
3750
+ },{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
3751
+ },{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
3752
+ },{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,sessionId]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana12;var type='endSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0||_this$userSessionMana12.end();}// eslint-disable-next-line class-methods-use-this
3753
+ },{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13;var sessionId=(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0?void 0:_this$userSessionMana13.getSessionId();return sessionId!==null&&sessionId!==void 0?sessionId:null;}},{key:"consent",value:function consent(options){var _this5=this,_this$storeManager2,_this$userSessionMana14,_this$eventManager7;this.errorHandler.leaveBreadcrumb("New consent invocation");n(function(){state.consents.preConsent.value=_objectSpread2(_objectSpread2({},state.consents.preConsent.value),{},{enabled:false});state.consents.postConsent.value=getValidPostConsentOptions(options);var _getConsentManagement=getConsentManagementData(state.consents.postConsent.value.consentManagement,_this5.logger),initialized=_getConsentManagement.initialized,consentsData=_getConsentManagement.consentsData;state.consents.initialized.value=initialized||state.consents.initialized.value;state.consents.data.value=consentsData;});// Update consents data in state
3754
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager6;(_this$pluginsManager6=this.pluginsManager)===null||_this$pluginsManager6===void 0||_this$pluginsManager6.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}// Re-init store manager
3755
+ (_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
3756
+ (_this$userSessionMana14=this.userSessionManager)===null||_this$userSessionMana14===void 0||_this$userSessionMana14.syncStorageDataToState();// Resume event manager to process the events to destinations
3757
+ (_this$eventManager7=this.eventManager)===null||_this$eventManager7===void 0||_this$eventManager7.resume();this.loadDestinations();this.sendTrackingEvents();}},{key:"sendTrackingEvents",value:function sendTrackingEvents(){if(state.consents.postConsent.value.trackConsent){this.track(trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME));}if(state.consents.postConsent.value.sendPageEvent){this.page(pageArgumentsToCallOptions());}}},{key:"setAuthToken",value:function setAuthToken(token){var _this$userSessionMana15;(_this$userSessionMana15=this.userSessionManager)===null||_this$userSessionMana15===void 0||_this$userSessionMana15.setAuthToken(token);}// End consumer exposed methods
3758
+ }]);return Analytics;}();
3759
+
3760
+ /*
3761
+ * RudderAnalytics facade singleton that is exposed as global object and will:
3762
+ * expose overloaded methods
3763
+ * handle multiple Analytics instances
3764
+ * consume SDK preload event buffer
3765
+ */var RudderAnalytics=/*#__PURE__*/function(){// Singleton with constructor bind methods
3766
+ function RudderAnalytics(){_classCallCheck(this,RudderAnalytics);_defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');_defineProperty(this,"logger",defaultLogger);if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
3767
+ // eslint-disable-next-line no-constructor-return
3768
+ return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
3769
+ }this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this);this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this);this.load=this.load.bind(this);this.ready=this.ready.bind(this);this.getPreloadBuffer=this.getPreloadBuffer.bind(this);this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this);this.page=this.page.bind(this);this.track=this.track.bind(this);this.identify=this.identify.bind(this);this.alias=this.alias.bind(this);this.group=this.group.bind(this);this.reset=this.reset.bind(this);this.getAnonymousId=this.getAnonymousId.bind(this);this.setAnonymousId=this.setAnonymousId.bind(this);this.getUserId=this.getUserId.bind(this);this.getUserTraits=this.getUserTraits.bind(this);this.getGroupId=this.getGroupId.bind(this);this.getGroupTraits=this.getGroupTraits.bind(this);this.startSession=this.startSession.bind(this);this.endSession=this.endSession.bind(this);this.getSessionId=this.getSessionId.bind(this);this.setAuthToken=this.setAuthToken.bind(this);this.consent=this.consent.bind(this);RudderAnalytics.globalSingleton=this;// get the preloaded events before replacing global object
3770
+ this.getPreloadBuffer();// start loading if a load event was buffered or wait for explicit load call
3771
+ this.triggerBufferedLoadEvent();}/**
3772
+ * Set instance to use if no specific writeKey is provided in methods
3773
+ * automatically for the first created instance
3774
+ * TODO: to support multiple analytics instances in the near future
3775
+ */_createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
3776
+ * Retrieve an existing analytics instance
3777
+ */},{key:"getAnalyticsInstance",value:function getAnalyticsInstance(writeKey){var instanceId=writeKey!==null&&writeKey!==void 0?writeKey:this.defaultAnalyticsKey;var analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}/**
3778
+ * Create new analytics instance and trigger application lifecycle start
3779
+ */},{key:"load",value:function load(writeKey,dataPlaneUrl,loadOptions){if(!isString(writeKey)){this.logger.error(WRITE_KEY_NOT_A_STRING_ERROR(RS_APP,writeKey));return;}if(this.analyticsInstances[writeKey]){return;}this.setDefaultInstanceKey(writeKey);this.analyticsInstances[writeKey]=new Analytics();this.getAnalyticsInstance(writeKey).load(writeKey,dataPlaneUrl,loadOptions);}/**
3780
+ * Get preloaded events in buffer queue if exists
3781
+ */ // eslint-disable-next-line class-methods-use-this
3782
+ },{key:"getPreloadBuffer",value:function getPreloadBuffer(){var preloadedEventsArray=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[];// Expose buffer to global objects
3783
+ setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone$1(preloadedEventsArray));}/**
3784
+ * Trigger load event in buffer queue if exists
3785
+ */},{key:"triggerBufferedLoadEvent",value:function triggerBufferedLoadEvent(){var preloadedEventsArray=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[];// Get any load method call that is buffered if any
3786
+ var loadEvent=getPreloadedLoadEvent(preloadedEventsArray);// Process load method if present in the buffered requests
3787
+ if(loadEvent.length>0){// Remove the event name from the Buffered Event array and keep only arguments
3788
+ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
3789
+ // @ts-ignore
3790
+ this.load.apply(null,loadEvent);}}/**
3791
+ * Get ready callback arguments and forward to ready call
3792
+ */},{key:"ready",value:function ready(callback){this.getAnalyticsInstance().ready(callback);}/**
3793
+ * Process page arguments and forward to page call
3794
+ */},{key:"page",value:function page(category,name,properties,options,callback){this.getAnalyticsInstance().page(pageArgumentsToCallOptions(category,name,properties,options,callback));}/**
3795
+ * Process track arguments and forward to page call
3796
+ */},{key:"track",value:function track(event,properties,options,callback){this.getAnalyticsInstance().track(trackArgumentsToCallOptions(event,properties,options,callback));}/**
3797
+ * Process identify arguments and forward to page call
3798
+ */},{key:"identify",value:function identify(userId,traits,options,callback){this.getAnalyticsInstance().identify(identifyArgumentsToCallOptions(userId,traits,options,callback));}/**
3799
+ * Process alias arguments and forward to page call
3800
+ */},{key:"alias",value:function alias(to,from,options,callback){this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to,from,options,callback));}/**
3801
+ * Process group arguments and forward to page call
3802
+ */},{key:"group",value:function group(groupId,traits,options,callback){if(arguments.length===0){this.logger.error(EMPTY_GROUP_CALL_ERROR(RS_APP));return;}this.getAnalyticsInstance().group(groupArgumentsToCallOptions(groupId,traits,options,callback));}},{key:"reset",value:function reset(resetAnonymousId){this.getAnalyticsInstance().reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){return this.getAnalyticsInstance().getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){this.getAnalyticsInstance().setAnonymousId(anonymousId,rudderAmpLinkerParam);}},{key:"getUserId",value:function getUserId(){return this.getAnalyticsInstance().getUserId();}},{key:"getUserTraits",value:function getUserTraits(){return this.getAnalyticsInstance().getUserTraits();}},{key:"getGroupId",value:function getGroupId(){return this.getAnalyticsInstance().getGroupId();}},{key:"getGroupTraits",value:function getGroupTraits(){return this.getAnalyticsInstance().getGroupTraits();}},{key:"startSession",value:function startSession(sessionId){return this.getAnalyticsInstance().startSession(sessionId);}},{key:"endSession",value:function endSession(){return this.getAnalyticsInstance().endSession();}},{key:"getSessionId",value:function getSessionId(){return this.getAnalyticsInstance().getSessionId();}},{key:"setAuthToken",value:function setAuthToken(token){return this.getAnalyticsInstance().setAuthToken(token);}},{key:"consent",value:function consent(options){return this.getAnalyticsInstance().consent(options);}}]);return RudderAnalytics;}();_defineProperty(RudderAnalytics,"globalSingleton",null);
3803
+
3804
+ //=====================================================================================
3805
+
3806
+ console.log("This prints to the console of the page (injected only if the page url matched)");
3807
+
3808
+ const rudderanalytics = new RudderAnalytics();
3809
+
3810
+ const initialiseRudderstack = () => {
3811
+ rudderanalytics.load(
3812
+ "2L8Fl7ryPss3Zku133Pj5ox7NeP",
3813
+ "https://rudderstacpn.dataplane.rudderstack.com",
3814
+ {
3815
+ integrations: {
3816
+ All: false
3817
+ },
3818
+ plugins: [
3819
+ 'StorageEncryption',
3820
+ 'XhrQueue',
3821
+ ]
3822
+ }
3823
+ );
3824
+
3825
+ rudderanalytics.ready(() => {
3826
+ console.log("we are all set!!!");
3827
+ });
3828
+
3829
+ rudderanalytics.setDefaultInstanceKey("<writeKey>");
3830
+ }
3831
+
3832
+
3833
+ const testEvents = () => {
3834
+ rudderanalytics.page();
3835
+
3836
+ rudderanalytics.identify(
3837
+ "moumita123",
3838
+ {email: "name@domain.com"},
3839
+ {
3840
+ page: {
3841
+ path: "",
3842
+ referrer: "",
3843
+ search: "",
3844
+ title: "",
3845
+ url: "",
3846
+ },
3847
+ },
3848
+ () => {
3849
+ console.log("in identify call");
3850
+ }
3851
+ );
3852
+
3853
+ rudderanalytics.track(
3854
+ "test track event GA3",
3855
+ {
3856
+ revenue: 30,
3857
+ currency: "USD",
3858
+ user_actual_id: 12345,
3859
+ },
3860
+ () => {
3861
+ console.log("in track call");
3862
+ }
3863
+ );
3864
+ };
3865
+
3866
+ chrome.runtime.onMessage.addListener((obj, sender, response) => {
3867
+ const { type, value} = obj;
3868
+
3869
+ if (type === "track") {
3870
+ testEvents(value);
3871
+ }
3872
+ });
3873
+
3874
+ initialiseRudderstack();
3875
+ })();