castled-js-sdk 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (660) hide show
  1. package/.env.example +8 -0
  2. package/.eslintignore +15 -0
  3. package/.eslintrc.json +41 -0
  4. package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
  5. package/.github/ISSUE_TEMPLATE/feature_request.md +19 -0
  6. package/.github/pull_request_template.md +22 -0
  7. package/.github/workflows/build-and-quality-checks.yml +50 -0
  8. package/.github/workflows/deploy-beta.yml +55 -0
  9. package/.github/workflows/deploy-cdn.yml +113 -0
  10. package/.github/workflows/deploy-npm.yml +80 -0
  11. package/.github/workflows/deploy-sanity-suite.yml +46 -0
  12. package/.github/workflows/test.yml +39 -0
  13. package/.husky/commit-msg +4 -0
  14. package/.husky/pre-commit +4 -0
  15. package/.nvmrc +1 -0
  16. package/.prettierignore +10 -0
  17. package/.prettierrc +7 -0
  18. package/.size-limit.js +30 -0
  19. package/.versionrc +12 -0
  20. package/LICENSE +67 -0
  21. package/README.md +102 -22
  22. package/__mocks__/BraveBrowser.js +9 -0
  23. package/__mocks__/fixtures.js +130 -0
  24. package/__mocks__/msw.handlers.js +34 -0
  25. package/__mocks__/msw.server.js +6 -0
  26. package/__tests__/camelcase.test.js +29 -0
  27. package/__tests__/data-residency.test.js +238 -0
  28. package/__tests__/features/core/metrics/errorReporting/ErrorReportingService.test.js +80 -0
  29. package/__tests__/integrations/BingAds/__mocks__/data.js +17 -0
  30. package/__tests__/integrations/BingAds/browser.test.js +148 -0
  31. package/__tests__/integrations/BingAds/utils.test.js +138 -0
  32. package/__tests__/integrations/Braze/Braze.test.js +462 -0
  33. package/__tests__/integrations/FacebookPixel/FacebookPixel.test.js +347 -0
  34. package/__tests__/integrations/FacebookPixel/utils.test.js +688 -0
  35. package/__tests__/integrations/Fullstory/fullstory.test.js +147 -0
  36. package/__tests__/integrations/GA4/__mocks__/data.js +1480 -0
  37. package/__tests__/integrations/GA4/browser.test.js +94 -0
  38. package/__tests__/integrations/GA4/utils.test.js +337 -0
  39. package/__tests__/integrations/GoogleAds/__mocks__/data.js +235 -0
  40. package/__tests__/integrations/GoogleAds/browser.test.js +202 -0
  41. package/__tests__/integrations/GoogleAds/utils.test.js +110 -0
  42. package/__tests__/integrations/LaunchDarkly/__mocks__/data.js +61 -0
  43. package/__tests__/integrations/LaunchDarkly/browser.test.js +148 -0
  44. package/__tests__/integrations/LaunchDarkly/utils.test.js +36 -0
  45. package/__tests__/integrations/Lemnisk/lemnisk.test.js +156 -0
  46. package/__tests__/integrations/Mixpanel/browser.test.js +60 -0
  47. package/__tests__/integrations/PinterestTag/__mocks__/data.js +24 -0
  48. package/__tests__/integrations/PinterestTag/utils.test.js +19 -0
  49. package/__tests__/integrations/TikTokAds/tiktokads.test.js +231 -0
  50. package/__tests__/ketchConsent.test.js +49 -0
  51. package/__tests__/oneTrustCookieConsent.test.js +89 -0
  52. package/__tests__/script.test.js +167 -0
  53. package/__tests__/service-worker/__mocks__/fixtures.js +79 -0
  54. package/__tests__/service-worker/__mocks__/msw.server.js +12 -0
  55. package/__tests__/service-worker/index.test.js +109 -0
  56. package/__tests__/transformationHandler.test.js +169 -0
  57. package/__tests__/utils/IntegrationsData.test.js +105 -0
  58. package/__tests__/utils/ObjectUtils.test.js +227 -0
  59. package/__tests__/utils/cdnPaths.test.js +63 -0
  60. package/__tests__/utils/clientHint.test.js +87 -0
  61. package/__tests__/utils/commonUtils.test.js +271 -0
  62. package/__tests__/utils/errorHandler.test.js +60 -0
  63. package/__tests__/utils/eventProcessorUtils.test.js +266 -0
  64. package/__tests__/utils/navigator.test.js +38 -0
  65. package/__tests__/utils/preProcessQueue.test.js +78 -0
  66. package/__tests__/utils/screenDetails.test.js +19 -0
  67. package/__tests__/utils/utils.test.js +348 -0
  68. package/assets/integrations/AdobeAnalytics/adobe-analytics-heartbeat.js +12384 -0
  69. package/assets/integrations/AdobeAnalytics/adobe-analytics-js.js +5046 -0
  70. package/babel.config.json +34 -0
  71. package/commitlint.config.js +3 -0
  72. package/examples/SampleEventsTest.Html +133 -0
  73. package/examples/TC/TC_001.js +4 -0
  74. package/examples/TC/TC_002.js +4 -0
  75. package/examples/TC/TC_003.js +4 -0
  76. package/examples/TC/TC_004.js +4 -0
  77. package/examples/TC/TC_005.js +4 -0
  78. package/examples/chrome-extension/USAGE.md +131 -0
  79. package/examples/chrome-extension/background-script/LICENSE +21 -0
  80. package/examples/chrome-extension/background-script/README.md +101 -0
  81. package/examples/chrome-extension/background-script/foreground.js +7 -0
  82. package/examples/chrome-extension/background-script/logo/logo-128.png +0 -0
  83. package/examples/chrome-extension/background-script/logo/logo-16.png +0 -0
  84. package/examples/chrome-extension/background-script/logo/logo-48.png +0 -0
  85. package/examples/chrome-extension/background-script/logo/logo.svg +138 -0
  86. package/examples/chrome-extension/background-script/manifest.json +37 -0
  87. package/examples/chrome-extension/background-script/popup/popup.css +11 -0
  88. package/examples/chrome-extension/background-script/popup/popup.html +11 -0
  89. package/examples/chrome-extension/background-script/rudderAnalytics.js +5345 -0
  90. package/examples/chrome-extension/background-script/service-worker.js +32 -0
  91. package/examples/chrome-extension/background-script/settings/settings.css +8 -0
  92. package/examples/chrome-extension/background-script/settings/settings.html +12 -0
  93. package/examples/chrome-extension/background-script-websockets/LICENSE +21 -0
  94. package/examples/chrome-extension/background-script-websockets/README.md +101 -0
  95. package/examples/chrome-extension/background-script-websockets/foreground.js +7 -0
  96. package/examples/chrome-extension/background-script-websockets/logo/logo-128.png +0 -0
  97. package/examples/chrome-extension/background-script-websockets/logo/logo-16.png +0 -0
  98. package/examples/chrome-extension/background-script-websockets/logo/logo-48.png +0 -0
  99. package/examples/chrome-extension/background-script-websockets/logo/logo.svg +138 -0
  100. package/examples/chrome-extension/background-script-websockets/manifest.json +37 -0
  101. package/examples/chrome-extension/background-script-websockets/popup/popup.css +11 -0
  102. package/examples/chrome-extension/background-script-websockets/popup/popup.html +11 -0
  103. package/{service-worker/index.es.js → examples/chrome-extension/background-script-websockets/rudderAnalytics.js} +1283 -1274
  104. package/examples/chrome-extension/background-script-websockets/service-worker.js +60 -0
  105. package/examples/chrome-extension/background-script-websockets/settings/settings.css +8 -0
  106. package/examples/chrome-extension/background-script-websockets/settings/settings.html +12 -0
  107. package/examples/chrome-extension/content-script/LICENSE +21 -0
  108. package/examples/chrome-extension/content-script/README.md +101 -0
  109. package/examples/chrome-extension/content-script/foreground.js +65 -0
  110. package/examples/chrome-extension/content-script/logo/logo-128.png +0 -0
  111. package/examples/chrome-extension/content-script/logo/logo-16.png +0 -0
  112. package/examples/chrome-extension/content-script/logo/logo-48.png +0 -0
  113. package/examples/chrome-extension/content-script/logo/logo.svg +138 -0
  114. package/examples/chrome-extension/content-script/manifest.json +39 -0
  115. package/examples/chrome-extension/content-script/popup/popup.css +11 -0
  116. package/examples/chrome-extension/content-script/popup/popup.html +11 -0
  117. package/examples/chrome-extension/content-script/service-worker-utils.js +17 -0
  118. package/examples/chrome-extension/content-script/service-worker.js +12 -0
  119. package/examples/chrome-extension/content-script/settings/settings.css +8 -0
  120. package/examples/chrome-extension/content-script/settings/settings.html +12 -0
  121. package/examples/chrome-extension/websocket-server/server.mjs +19 -0
  122. package/examples/html/autotrack-test.html +96 -0
  123. package/examples/html/ecomm_test.html +358 -0
  124. package/examples/html/script-test.html +968 -0
  125. package/examples/html/segment.html +177 -0
  126. package/examples/html/test_poster.jpg +0 -0
  127. package/examples/umd/index.js +11 -0
  128. package/examples/umd/package.json +42 -0
  129. package/examples/umd/rollup.config.js +36 -0
  130. package/examples/umd/tests/test.html +5 -0
  131. package/examples/v1.1/tc1.html +139 -0
  132. package/examples/v1.1/tc2.1.html +140 -0
  133. package/examples/v1.1/tc2.2.html +139 -0
  134. package/examples/v1.1/tc2.3.html +143 -0
  135. package/examples/v1.1/tc3.1.html +139 -0
  136. package/examples/v1.1/tc3.2.html +142 -0
  137. package/examples/v1.1/tc3.3.html +142 -0
  138. package/examples/v1.1/tc3.4.html +144 -0
  139. package/examples/v1.1/tc3.5.html +142 -0
  140. package/examples/v1.1/tc4.html +142 -0
  141. package/examples/v1.1/tc5.html +150 -0
  142. package/github-release.config.js +5 -0
  143. package/jest/jest.global-setup.js +3 -0
  144. package/jest/jest.polyfills.js +10 -0
  145. package/jest/jest.setup-dom.js +49 -0
  146. package/jest.config.js +196 -0
  147. package/package.json +198 -39
  148. package/packages/npm/README.md +125 -0
  149. package/packages/npm/package.json +50 -0
  150. package/patches/@segment+localstorage-retry+1.3.0.patch +73 -0
  151. package/patches/@segment+top-domain+3.0.1.patch +34 -0
  152. package/public/index.html +136 -0
  153. package/public/list_integration_sdks.html +390 -0
  154. package/rollup-configs/rollup.integrations.config.js +29 -0
  155. package/rollup-configs/rollup.sdk.browser.js +32 -0
  156. package/rollup-configs/rollup.sdk.npm.js +43 -0
  157. package/rollup-configs/rollup.utilities.js +120 -0
  158. package/rollup-configs/rollup.worker.config.js +37 -0
  159. package/sanity-suite/.babelrc +33 -0
  160. package/sanity-suite/.env.example +6 -0
  161. package/sanity-suite/__mocks__/alias1.json +137 -0
  162. package/sanity-suite/__mocks__/alias2.json +97 -0
  163. package/sanity-suite/__mocks__/alias5.json +103 -0
  164. package/sanity-suite/__mocks__/alias6.json +137 -0
  165. package/sanity-suite/__mocks__/group1.json +120 -0
  166. package/sanity-suite/__mocks__/group2.json +86 -0
  167. package/sanity-suite/__mocks__/group4.json +101 -0
  168. package/sanity-suite/__mocks__/group5.json +67 -0
  169. package/sanity-suite/__mocks__/group6.json +66 -0
  170. package/sanity-suite/__mocks__/identify1.json +136 -0
  171. package/sanity-suite/__mocks__/identify2.json +102 -0
  172. package/sanity-suite/__mocks__/identify3.json +99 -0
  173. package/sanity-suite/__mocks__/identify4.json +65 -0
  174. package/sanity-suite/__mocks__/identify5.json +102 -0
  175. package/sanity-suite/__mocks__/identify6.json +103 -0
  176. package/sanity-suite/__mocks__/identify7.json +102 -0
  177. package/sanity-suite/__mocks__/identify8.json +103 -0
  178. package/sanity-suite/__mocks__/page1.json +119 -0
  179. package/sanity-suite/__mocks__/page2.json +86 -0
  180. package/sanity-suite/__mocks__/page4.json +112 -0
  181. package/sanity-suite/__mocks__/page5.json +79 -0
  182. package/sanity-suite/__mocks__/page6.json +77 -0
  183. package/sanity-suite/__mocks__/page7.json +77 -0
  184. package/sanity-suite/__mocks__/page8.json +75 -0
  185. package/sanity-suite/__mocks__/page9.json +155 -0
  186. package/sanity-suite/__mocks__/sourceConfig1.json +988 -0
  187. package/sanity-suite/__mocks__/track1.json +150 -0
  188. package/sanity-suite/__mocks__/track2.json +118 -0
  189. package/sanity-suite/__mocks__/track4.json +134 -0
  190. package/sanity-suite/__mocks__/track5.json +102 -0
  191. package/sanity-suite/__mocks__/track6.json +81 -0
  192. package/sanity-suite/__mocks__/track7.json +81 -0
  193. package/sanity-suite/package-lock.json +7951 -0
  194. package/sanity-suite/package.json +67 -0
  195. package/sanity-suite/public/eventFiltering/index-cdn.html +112 -0
  196. package/sanity-suite/public/eventFiltering/index-local.html +109 -0
  197. package/sanity-suite/public/eventFiltering/index-npm.html +92 -0
  198. package/sanity-suite/public/index-cdn.html +112 -0
  199. package/sanity-suite/public/index-local.html +109 -0
  200. package/sanity-suite/public/index-npm.html +92 -0
  201. package/sanity-suite/public/preloadBuffer/index-cdn.html +112 -0
  202. package/sanity-suite/public/preloadBuffer/index-local.html +109 -0
  203. package/sanity-suite/public/preloadBuffer/index-npm.html +92 -0
  204. package/sanity-suite/rollup.config.js +199 -0
  205. package/sanity-suite/src/index-npm.js +65 -0
  206. package/sanity-suite/src/index.js +5 -0
  207. package/sanity-suite/src/testBook/ResultAssertions.js +51 -0
  208. package/sanity-suite/src/testBook/TestBook.js +345 -0
  209. package/sanity-suite/src/testBook/ignoredProperties.js +150 -0
  210. package/sanity-suite/src/testBook/index.js +11 -0
  211. package/sanity-suite/src/testBookSuites/alias.js +287 -0
  212. package/sanity-suite/src/testBookSuites/group.js +240 -0
  213. package/sanity-suite/src/testBookSuites/identify.js +455 -0
  214. package/sanity-suite/src/testBookSuites/index.js +31 -0
  215. package/sanity-suite/src/testBookSuites/page.js +258 -0
  216. package/sanity-suite/src/testBookSuites/sourceConfig.js +84 -0
  217. package/sanity-suite/src/testBookSuites/track.js +451 -0
  218. package/scripts/integrationBuildScript.js +77 -0
  219. package/scripts/run_tests.sh +6 -0
  220. package/src/core/analytics.js +1668 -0
  221. package/src/features/core/cookieConsent/CookieConsentFactory.js +32 -0
  222. package/src/features/core/cookieConsent/OneTrust/browser.js +102 -0
  223. package/src/features/core/cookieConsent/OneTrust/index.js +3 -0
  224. package/src/features/core/cookieConsent/ketch/browser.js +114 -0
  225. package/src/features/core/cookieConsent/ketch/index.js +1 -0
  226. package/src/features/core/deviceModeTransformation/transformationHandler.js +189 -0
  227. package/src/features/core/deviceModeTransformation/util.js +23 -0
  228. package/src/features/core/metrics/errorReporting/ErrorReportingService.js +116 -0
  229. package/src/features/core/metrics/errorReporting/providers/Bugsnag.js +240 -0
  230. package/src/features/core/session/index.js +207 -0
  231. package/src/integrations/ActiveCampaign/browser.js +52 -0
  232. package/src/integrations/ActiveCampaign/constants.js +14 -0
  233. package/src/integrations/ActiveCampaign/index.js +3 -0
  234. package/src/integrations/ActiveCampaign/nativeSdkLoader.js +24 -0
  235. package/src/integrations/AdobeAnalytics/browser.js +276 -0
  236. package/src/integrations/AdobeAnalytics/constants.js +14 -0
  237. package/src/integrations/AdobeAnalytics/eCommHandle.js +56 -0
  238. package/src/integrations/AdobeAnalytics/heartbeatHandle.js +266 -0
  239. package/src/integrations/AdobeAnalytics/index.js +1 -0
  240. package/src/integrations/AdobeAnalytics/util.js +678 -0
  241. package/src/integrations/Adroll/browser.js +125 -0
  242. package/src/integrations/Adroll/constants.js +10 -0
  243. package/src/integrations/Adroll/index.js +1 -0
  244. package/src/integrations/Adroll/util.js +48 -0
  245. package/src/integrations/Amplitude/browser.js +352 -0
  246. package/src/integrations/Amplitude/constants.js +9 -0
  247. package/src/integrations/Amplitude/index.js +1 -0
  248. package/src/integrations/Amplitude/nativeSdkLoader.js +112 -0
  249. package/src/integrations/Amplitude/test/test_amplitude.html +157 -0
  250. package/src/integrations/Amplitude/utils.js +25 -0
  251. package/src/integrations/Appcues/browser.js +79 -0
  252. package/src/integrations/Appcues/constants.js +9 -0
  253. package/src/integrations/Appcues/index.js +1 -0
  254. package/src/integrations/Axeptio/browser.js +61 -0
  255. package/src/integrations/Axeptio/constants.js +8 -0
  256. package/src/integrations/Axeptio/index.js +1 -0
  257. package/src/integrations/Axeptio/nativeSdkLoader.js +14 -0
  258. package/src/integrations/Axeptio/utils.js +16 -0
  259. package/src/integrations/BingAds/browser.js +79 -0
  260. package/src/integrations/BingAds/constants.js +12 -0
  261. package/src/integrations/BingAds/index.js +1 -0
  262. package/src/integrations/BingAds/nativeSdkLoader.js +30 -0
  263. package/src/integrations/BingAds/utils.js +101 -0
  264. package/src/integrations/Braze/browser.js +284 -0
  265. package/src/integrations/Braze/constants.js +11 -0
  266. package/src/integrations/Braze/index.js +1 -0
  267. package/src/integrations/Braze/nativeSdkLoader.js +35 -0
  268. package/src/integrations/Braze/utils.js +51 -0
  269. package/src/integrations/Bugsnag/browser.js +60 -0
  270. package/src/integrations/Bugsnag/constants.js +8 -0
  271. package/src/integrations/Bugsnag/index.js +1 -0
  272. package/src/integrations/Chartbeat/browser.js +148 -0
  273. package/src/integrations/Chartbeat/constants.js +10 -0
  274. package/src/integrations/Chartbeat/index.js +1 -0
  275. package/src/integrations/Chartbeat/nativeSdkLoader.js +7 -0
  276. package/src/integrations/Clevertap/browser.js +206 -0
  277. package/src/integrations/Clevertap/constants.js +8 -0
  278. package/src/integrations/Clevertap/index.js +1 -0
  279. package/src/integrations/Comscore/browser.js +130 -0
  280. package/src/integrations/Comscore/constants.js +11 -0
  281. package/src/integrations/Comscore/index.js +1 -0
  282. package/src/integrations/Comscore/nativeSdkLoader.js +10 -0
  283. package/src/integrations/ConvertFlow/browser.js +59 -0
  284. package/src/integrations/ConvertFlow/constants.js +15 -0
  285. package/src/integrations/ConvertFlow/index.js +1 -0
  286. package/src/integrations/ConvertFlow/utils.js +107 -0
  287. package/src/integrations/Criteo/browser.js +155 -0
  288. package/src/integrations/Criteo/constants.js +11 -0
  289. package/src/integrations/Criteo/index.js +1 -0
  290. package/src/integrations/Criteo/utils.js +343 -0
  291. package/src/integrations/CustomerIO/browser.js +74 -0
  292. package/src/integrations/CustomerIO/constants.js +10 -0
  293. package/src/integrations/CustomerIO/index.js +1 -0
  294. package/src/integrations/CustomerIO/nativeSdkLoader.js +31 -0
  295. package/src/integrations/DCMFloodlight/browser.js +240 -0
  296. package/src/integrations/DCMFloodlight/constants.js +15 -0
  297. package/src/integrations/DCMFloodlight/index.js +1 -0
  298. package/src/integrations/DCMFloodlight/utils.js +336 -0
  299. package/src/integrations/Drip/browser.js +169 -0
  300. package/src/integrations/Drip/constants.js +8 -0
  301. package/src/integrations/Drip/index.js +1 -0
  302. package/src/integrations/Drip/nativeSdkLoader.js +10 -0
  303. package/src/integrations/Drip/utils.js +29 -0
  304. package/src/integrations/Engage/browser.js +124 -0
  305. package/src/integrations/Engage/constants.js +16 -0
  306. package/src/integrations/Engage/index.js +1 -0
  307. package/src/integrations/Engage/nativeSdkLoader.js +25 -0
  308. package/src/integrations/Engage/utils.js +69 -0
  309. package/src/integrations/FacebookPixel/browser.js +313 -0
  310. package/src/integrations/FacebookPixel/constants.js +77 -0
  311. package/src/integrations/FacebookPixel/index.js +1 -0
  312. package/src/integrations/FacebookPixel/utils.js +310 -0
  313. package/src/integrations/Fullstory/browser.js +169 -0
  314. package/src/integrations/Fullstory/constants.js +13 -0
  315. package/src/integrations/Fullstory/index.js +1 -0
  316. package/src/integrations/Fullstory/nativeSdkLoader.js +69 -0
  317. package/src/integrations/GA/browser.js +816 -0
  318. package/src/integrations/GA/constants.js +10 -0
  319. package/src/integrations/GA/index.js +1 -0
  320. package/src/integrations/GA/index.test.js +184 -0
  321. package/src/integrations/GA360/browser.js +58 -0
  322. package/src/integrations/GA360/constants.js +14 -0
  323. package/src/integrations/GA360/index.js +1 -0
  324. package/src/integrations/GA4/browser.js +264 -0
  325. package/src/integrations/GA4/config.js +296 -0
  326. package/src/integrations/GA4/constants.js +15 -0
  327. package/src/integrations/GA4/index.js +1 -0
  328. package/src/integrations/GA4/utils.js +329 -0
  329. package/src/integrations/GoogleAds/browser.js +212 -0
  330. package/src/integrations/GoogleAds/constants.js +11 -0
  331. package/src/integrations/GoogleAds/index.js +1 -0
  332. package/src/integrations/GoogleAds/nativeSdkLoader.js +26 -0
  333. package/src/integrations/GoogleAds/utils.js +117 -0
  334. package/src/integrations/GoogleOptimize/browser.js +79 -0
  335. package/src/integrations/GoogleOptimize/constants.js +13 -0
  336. package/src/integrations/GoogleOptimize/index.js +1 -0
  337. package/src/integrations/GoogleTagManager/browser.js +95 -0
  338. package/src/integrations/GoogleTagManager/constants.js +10 -0
  339. package/src/integrations/GoogleTagManager/index.js +1 -0
  340. package/src/integrations/GoogleTagManager/nativeSdkLoader.js +21 -0
  341. package/src/integrations/Heap/browser.js +67 -0
  342. package/src/integrations/Heap/constants.js +9 -0
  343. package/src/integrations/Heap/index.js +1 -0
  344. package/src/integrations/Heap/nativeSdkLoader.js +40 -0
  345. package/src/integrations/Heap/util.js +23 -0
  346. package/src/integrations/Hotjar/browser.js +86 -0
  347. package/src/integrations/Hotjar/constants.js +10 -0
  348. package/src/integrations/Hotjar/index.js +1 -0
  349. package/src/integrations/Hotjar/nativeSdkLoader.js +21 -0
  350. package/src/integrations/HubSpot/browser.js +96 -0
  351. package/src/integrations/HubSpot/constants.js +11 -0
  352. package/src/integrations/HubSpot/index.js +1 -0
  353. package/src/integrations/INTERCOM/browser.js +107 -0
  354. package/src/integrations/INTERCOM/constants.js +8 -0
  355. package/src/integrations/INTERCOM/index.js +1 -0
  356. package/src/integrations/INTERCOM/nativeSdkLoader.js +46 -0
  357. package/src/integrations/INTERCOM/utils.js +68 -0
  358. package/src/integrations/Iterable/browser.js +185 -0
  359. package/src/integrations/Iterable/constants.js +8 -0
  360. package/src/integrations/Iterable/index.js +1 -0
  361. package/src/integrations/Iterable/utils.js +111 -0
  362. package/src/integrations/June/browser.js +98 -0
  363. package/src/integrations/June/constants.js +8 -0
  364. package/src/integrations/June/index.js +1 -0
  365. package/src/integrations/Keen/browser.js +153 -0
  366. package/src/integrations/Keen/constants.js +10 -0
  367. package/src/integrations/Keen/index.js +1 -0
  368. package/src/integrations/Kissmetrics/browser.js +254 -0
  369. package/src/integrations/Kissmetrics/constants.js +8 -0
  370. package/src/integrations/Kissmetrics/index.js +1 -0
  371. package/src/integrations/Kissmetrics/nativeSdkLoader.js +23 -0
  372. package/src/integrations/Klaviyo/browser.js +195 -0
  373. package/src/integrations/Klaviyo/constants.js +8 -0
  374. package/src/integrations/Klaviyo/index.js +1 -0
  375. package/src/integrations/Klaviyo/util.js +91 -0
  376. package/src/integrations/LaunchDarkly/browser.js +74 -0
  377. package/src/integrations/LaunchDarkly/constants.js +11 -0
  378. package/src/integrations/LaunchDarkly/index.js +1 -0
  379. package/src/integrations/LaunchDarkly/utils.js +24 -0
  380. package/src/integrations/Lemnisk/browser.js +85 -0
  381. package/src/integrations/Lemnisk/constants.js +13 -0
  382. package/src/integrations/Lemnisk/index.js +1 -0
  383. package/src/integrations/Lemnisk/nativeSdkLoader.js +34 -0
  384. package/src/integrations/LinkedInInsightTag/browser.js +71 -0
  385. package/src/integrations/LinkedInInsightTag/constants.js +16 -0
  386. package/src/integrations/LinkedInInsightTag/index.js +1 -0
  387. package/src/integrations/LiveChat/browser.js +82 -0
  388. package/src/integrations/LiveChat/constants.js +12 -0
  389. package/src/integrations/LiveChat/index.js +1 -0
  390. package/src/integrations/LiveChat/nativeSdkLoader.js +40 -0
  391. package/src/integrations/LiveChat/util.js +71 -0
  392. package/src/integrations/Lotame/LotameStorage.js +21 -0
  393. package/src/integrations/Lotame/browser.js +172 -0
  394. package/src/integrations/Lotame/constants.js +8 -0
  395. package/src/integrations/Lotame/index.js +1 -0
  396. package/src/integrations/Lytics/browser.js +87 -0
  397. package/src/integrations/Lytics/constants.js +8 -0
  398. package/src/integrations/Lytics/index.js +1 -0
  399. package/src/integrations/Lytics/nativeSdkLoader.js +77 -0
  400. package/src/integrations/Lytics/test/script-test-lytics.html +250 -0
  401. package/src/integrations/Matomo/browser.js +188 -0
  402. package/src/integrations/Matomo/constants.js +8 -0
  403. package/src/integrations/Matomo/index.js +1 -0
  404. package/src/integrations/Matomo/nativeSdkLoader.js +20 -0
  405. package/src/integrations/Matomo/util.js +417 -0
  406. package/src/integrations/MicrosoftClarity/browser.js +70 -0
  407. package/src/integrations/MicrosoftClarity/constants.js +14 -0
  408. package/src/integrations/MicrosoftClarity/index.js +1 -0
  409. package/src/integrations/MicrosoftClarity/nativeSdkLoader.js +22 -0
  410. package/src/integrations/Mixpanel/browser.js +326 -0
  411. package/src/integrations/Mixpanel/constants.js +11 -0
  412. package/src/integrations/Mixpanel/index.js +1 -0
  413. package/src/integrations/Mixpanel/nativeSdkLoader.js +71 -0
  414. package/src/integrations/Mixpanel/util.js +178 -0
  415. package/src/integrations/MoEngage/browser.js +133 -0
  416. package/src/integrations/MoEngage/constants.js +12 -0
  417. package/src/integrations/MoEngage/index.js +1 -0
  418. package/src/integrations/MoEngage/nativeSdkLoader.js +66 -0
  419. package/src/integrations/MoEngage/test/script-test-moengage.html +216 -0
  420. package/src/integrations/Mouseflow/browser.js +98 -0
  421. package/src/integrations/Mouseflow/constants.js +14 -0
  422. package/src/integrations/Mouseflow/index.js +1 -0
  423. package/src/integrations/Mouseflow/utils.js +27 -0
  424. package/src/integrations/Olark/browser.js +94 -0
  425. package/src/integrations/Olark/constants.js +8 -0
  426. package/src/integrations/Olark/index.js +1 -0
  427. package/src/integrations/Olark/nativeSdkLoader.js +31 -0
  428. package/src/integrations/Olark/utils.js +51 -0
  429. package/src/integrations/Optimizely/browser.js +230 -0
  430. package/src/integrations/Optimizely/constants.js +8 -0
  431. package/src/integrations/Optimizely/index.js +1 -0
  432. package/src/integrations/Optimizely/utils.js +23 -0
  433. package/src/integrations/Pendo/browser.js +119 -0
  434. package/src/integrations/Pendo/constants.js +8 -0
  435. package/src/integrations/Pendo/index.js +1 -0
  436. package/src/integrations/Pendo/nativeSdkLoader.js +32 -0
  437. package/src/integrations/PinterestTag/browser.js +241 -0
  438. package/src/integrations/PinterestTag/constants.js +19 -0
  439. package/src/integrations/PinterestTag/index.js +1 -0
  440. package/src/integrations/PinterestTag/nativeSdkLoader.js +19 -0
  441. package/src/integrations/PinterestTag/propertyMappingConfig.js +57 -0
  442. package/src/integrations/PinterestTag/test/input.js +180 -0
  443. package/src/integrations/PinterestTag/test/output.js +129 -0
  444. package/src/integrations/PinterestTag/utils.js +47 -0
  445. package/src/integrations/Podsights/browser.js +178 -0
  446. package/src/integrations/Podsights/constants.js +206 -0
  447. package/src/integrations/Podsights/index.js +1 -0
  448. package/src/integrations/Podsights/utils.js +65 -0
  449. package/src/integrations/PostAffiliatePro/browser.js +133 -0
  450. package/src/integrations/PostAffiliatePro/constants.js +13 -0
  451. package/src/integrations/PostAffiliatePro/index.js +1 -0
  452. package/src/integrations/PostAffiliatePro/utils.js +40 -0
  453. package/src/integrations/Posthog/browser.js +154 -0
  454. package/src/integrations/Posthog/constants.js +12 -0
  455. package/src/integrations/Posthog/index.js +1 -0
  456. package/src/integrations/Posthog/nativeSdkLoader.js +48 -0
  457. package/src/integrations/Posthog/test/test_posthog.html +77 -0
  458. package/src/integrations/Posthog/utils.js +36 -0
  459. package/src/integrations/ProfitWell/browser.js +72 -0
  460. package/src/integrations/ProfitWell/constants.js +12 -0
  461. package/src/integrations/ProfitWell/index.js +1 -0
  462. package/src/integrations/ProfitWell/nativeSdkLoader.js +25 -0
  463. package/src/integrations/Qualaroo/browser.js +116 -0
  464. package/src/integrations/Qualaroo/constants.js +8 -0
  465. package/src/integrations/Qualaroo/index.js +1 -0
  466. package/src/integrations/Qualaroo/utils.js +83 -0
  467. package/src/integrations/Qualtrics/browser.js +89 -0
  468. package/src/integrations/Qualtrics/constants.js +8 -0
  469. package/src/integrations/Qualtrics/index.js +1 -0
  470. package/src/integrations/Qualtrics/nativeSdkLoader.js +79 -0
  471. package/src/integrations/QuantumMetric/browser.js +63 -0
  472. package/src/integrations/QuantumMetric/constants.js +13 -0
  473. package/src/integrations/QuantumMetric/index.js +1 -0
  474. package/src/integrations/QuoraPixel/browser.js +64 -0
  475. package/src/integrations/QuoraPixel/constants.js +15 -0
  476. package/src/integrations/QuoraPixel/index.js +1 -0
  477. package/src/integrations/QuoraPixel/nativeSdkLoader.js +21 -0
  478. package/src/integrations/RedditPixel/browser.js +98 -0
  479. package/src/integrations/RedditPixel/constants.js +13 -0
  480. package/src/integrations/RedditPixel/index.js +1 -0
  481. package/src/integrations/RedditPixel/nativeSdkLoader.js +21 -0
  482. package/src/integrations/Refiner/browser.js +119 -0
  483. package/src/integrations/Refiner/constants.js +8 -0
  484. package/src/integrations/Refiner/index.js +1 -0
  485. package/src/integrations/Refiner/nativeSdkLoader.js +20 -0
  486. package/src/integrations/Refiner/utils.js +44 -0
  487. package/src/integrations/Rockerbox/browser.js +89 -0
  488. package/src/integrations/Rockerbox/constants.js +12 -0
  489. package/src/integrations/Rockerbox/index.js +1 -0
  490. package/src/integrations/Rockerbox/nativeSdkLoader.js +32 -0
  491. package/src/integrations/RollBar/browser.js +92 -0
  492. package/src/integrations/RollBar/constants.js +13 -0
  493. package/src/integrations/RollBar/index.js +1 -0
  494. package/src/integrations/RollBar/nativeSdkLoader.js +383 -0
  495. package/src/integrations/Satismeter/browser.js +94 -0
  496. package/src/integrations/Satismeter/constants.js +9 -0
  497. package/src/integrations/Satismeter/index.js +1 -0
  498. package/src/integrations/Satismeter/nativeSdkLoader.js +23 -0
  499. package/src/integrations/Satismeter/util.js +54 -0
  500. package/src/integrations/Sendinblue/browser.js +111 -0
  501. package/src/integrations/Sendinblue/constants.js +25 -0
  502. package/src/integrations/Sendinblue/index.js +1 -0
  503. package/src/integrations/Sendinblue/nativeSdkLoader.js +36 -0
  504. package/src/integrations/Sendinblue/utils.js +112 -0
  505. package/src/integrations/Sentry/browser.js +118 -0
  506. package/src/integrations/Sentry/constants.js +8 -0
  507. package/src/integrations/Sentry/index.js +1 -0
  508. package/src/integrations/Sentry/utils.js +80 -0
  509. package/src/integrations/Shynet/browser.js +97 -0
  510. package/src/integrations/Shynet/constants.js +15 -0
  511. package/src/integrations/Shynet/index.js +1 -0
  512. package/src/integrations/SnapEngage/browser.js +75 -0
  513. package/src/integrations/SnapEngage/constants.js +12 -0
  514. package/src/integrations/SnapEngage/index.js +1 -0
  515. package/src/integrations/SnapEngage/nativeSdkLoader.js +24 -0
  516. package/src/integrations/SnapEngage/util.js +63 -0
  517. package/src/integrations/SnapPixel/browser.js +232 -0
  518. package/src/integrations/SnapPixel/constants.js +13 -0
  519. package/src/integrations/SnapPixel/index.js +1 -0
  520. package/src/integrations/SnapPixel/nativeSdkLoader.js +20 -0
  521. package/src/integrations/SnapPixel/util.js +211 -0
  522. package/src/integrations/TVSquared/browser.js +96 -0
  523. package/src/integrations/TVSquared/constants.js +14 -0
  524. package/src/integrations/TVSquared/index.js +1 -0
  525. package/src/integrations/TVSquared/utils.js +40 -0
  526. package/src/integrations/TiktokAds/browser.js +103 -0
  527. package/src/integrations/TiktokAds/constants.js +86 -0
  528. package/src/integrations/TiktokAds/index.js +1 -0
  529. package/src/integrations/TiktokAds/nativeSdkLoader.js +52 -0
  530. package/src/integrations/TiktokAds/util.js +71 -0
  531. package/src/integrations/VWO/browser.js +131 -0
  532. package/src/integrations/VWO/constants.js +13 -0
  533. package/src/integrations/VWO/index.js +1 -0
  534. package/src/integrations/VWO/nativeSdkLoader.js +64 -0
  535. package/src/integrations/Vero/browser.js +165 -0
  536. package/src/integrations/Vero/constants.js +8 -0
  537. package/src/integrations/Vero/index.js +1 -0
  538. package/src/integrations/Woopra/browser.js +83 -0
  539. package/src/integrations/Woopra/constants.js +8 -0
  540. package/src/integrations/Woopra/index.js +1 -0
  541. package/src/integrations/Woopra/nativeSdkLoader.js +43 -0
  542. package/src/integrations/YandexMetrica/browser.js +143 -0
  543. package/src/integrations/YandexMetrica/constants.js +10 -0
  544. package/src/integrations/YandexMetrica/index.js +1 -0
  545. package/src/integrations/YandexMetrica/nativeSdkLoader.js +35 -0
  546. package/src/integrations/YandexMetrica/utils.js +138 -0
  547. package/src/integrations/index.js +155 -0
  548. package/src/service-worker/index.js +466 -0
  549. package/src/utils/EventRepository.js +78 -0
  550. package/src/utils/HtElement.js +33 -0
  551. package/src/utils/HtElementBuilder.js +29 -0
  552. package/src/utils/IntegrationsData.js +61 -0
  553. package/src/utils/JSFileLoader.js +66 -0
  554. package/src/utils/ObjectUtils.js +68 -0
  555. package/src/utils/PreProcessQueue.js +66 -0
  556. package/src/utils/RudderApp.js +9 -0
  557. package/src/utils/RudderContext.js +21 -0
  558. package/src/utils/RudderInfo.js +41 -0
  559. package/src/utils/RudderMessage.js +28 -0
  560. package/src/utils/ScriptLoader.js +53 -0
  561. package/src/utils/beaconQueue.js +133 -0
  562. package/src/utils/camelcase.js +48 -0
  563. package/src/utils/cdnPaths.js +43 -0
  564. package/src/utils/clientHint.js +28 -0
  565. package/src/utils/client_server_name.js +78 -0
  566. package/src/utils/commonUtils.js +207 -0
  567. package/src/utils/config_to_integration_names.js +80 -0
  568. package/src/utils/constants.js +82 -0
  569. package/src/utils/errorHandler.js +88 -0
  570. package/src/utils/eventProcessorUtils.js +53 -0
  571. package/src/utils/integration_cname.js +156 -0
  572. package/src/utils/linker/base64decoder.js +31 -0
  573. package/src/utils/linker/crc32.js +42 -0
  574. package/src/utils/linker/index.js +134 -0
  575. package/src/utils/linker/userLib.js +20 -0
  576. package/src/utils/logUtil.js +51 -0
  577. package/src/utils/logger.js +106 -0
  578. package/src/utils/navigator.js +32 -0
  579. package/src/utils/notifyError.js +16 -0
  580. package/src/utils/pageProperties.js +74 -0
  581. package/src/utils/screenDetails.js +23 -0
  582. package/src/utils/storage/cookie.js +93 -0
  583. package/src/utils/storage/index.js +3 -0
  584. package/src/utils/storage/storage.js +459 -0
  585. package/src/utils/storage/store.js +72 -0
  586. package/src/utils/storage/v3DecryptionUtils.js +19 -0
  587. package/src/utils/utils.js +966 -0
  588. package/src/utils/xhrModule.js +111 -0
  589. package/stats/AdobeAnalytics.html +4044 -0
  590. package/stats/Adroll.html +4044 -0
  591. package/stats/Amplitude.html +4044 -0
  592. package/stats/Appcues.html +4044 -0
  593. package/stats/BingAds.html +4044 -0
  594. package/stats/Braze.html +4044 -0
  595. package/stats/Bugsnag.html +4044 -0
  596. package/stats/Chartbeat.html +4044 -0
  597. package/stats/Clevertap.html +4044 -0
  598. package/stats/Comscore.html +4044 -0
  599. package/stats/ConvertFlow.html +4044 -0
  600. package/stats/Criteo.html +4044 -0
  601. package/stats/CustomerIO.html +4044 -0
  602. package/stats/DCMFloodlight.html +4044 -0
  603. package/stats/Drip.html +4044 -0
  604. package/stats/Engage.html +4044 -0
  605. package/stats/FacebookPixel.html +4044 -0
  606. package/stats/Fullstory.html +4044 -0
  607. package/stats/GA.html +4044 -0
  608. package/stats/GA360.html +4044 -0
  609. package/stats/GA4.html +4044 -0
  610. package/stats/GoogleAds.html +4044 -0
  611. package/stats/GoogleOptimize.html +4044 -0
  612. package/stats/GoogleTagManager.html +4044 -0
  613. package/stats/Heap.html +4044 -0
  614. package/stats/Hotjar.html +4044 -0
  615. package/stats/HubSpot.html +4044 -0
  616. package/stats/INTERCOM.html +4044 -0
  617. package/stats/Iterable.html +4044 -0
  618. package/stats/June.html +4044 -0
  619. package/stats/Keen.html +4044 -0
  620. package/stats/Kissmetrics.html +4044 -0
  621. package/stats/Klaviyo.html +4044 -0
  622. package/stats/LaunchDarkly.html +4044 -0
  623. package/stats/LinkedInInsightTag.html +4044 -0
  624. package/stats/LiveChat.html +4044 -0
  625. package/stats/Lotame.html +4044 -0
  626. package/stats/Lytics.html +4044 -0
  627. package/stats/Matomo.html +4044 -0
  628. package/stats/Mixpanel.html +4044 -0
  629. package/stats/MoEngage.html +4044 -0
  630. package/stats/Mouseflow.html +4044 -0
  631. package/stats/Optimizely.html +4044 -0
  632. package/stats/Pendo.html +4044 -0
  633. package/stats/PinterestTag.html +4044 -0
  634. package/stats/Podsights.html +4044 -0
  635. package/stats/PostAffiliatePro.html +4044 -0
  636. package/stats/Posthog.html +4044 -0
  637. package/stats/ProfitWell.html +4044 -0
  638. package/stats/Qualaroo.html +4044 -0
  639. package/stats/Qualtrics.html +4044 -0
  640. package/stats/QuantumMetric.html +4044 -0
  641. package/stats/QuoraPixel.html +4044 -0
  642. package/stats/RedditPixel.html +4044 -0
  643. package/stats/Refiner.html +4044 -0
  644. package/stats/Rockerbox.html +4044 -0
  645. package/stats/RollBar.html +4044 -0
  646. package/stats/Sentry.html +4044 -0
  647. package/stats/Shynet.html +4044 -0
  648. package/stats/SnapEngage.html +4044 -0
  649. package/stats/SnapPixel.html +4044 -0
  650. package/stats/TVSquared.html +4044 -0
  651. package/stats/VWO.html +4044 -0
  652. package/stats/Vero.html +4044 -0
  653. package/stats/Woopra.html +4044 -0
  654. package/stats/YandexMetrica.html +4044 -0
  655. package/stats/rudder-analytics.html +4044 -0
  656. package/index.es.js +0 -1
  657. package/index.js +0 -1
  658. package/service-worker/index.js +0 -5346
  659. /package/{index.d.ts → packages/npm/index.d.ts} +0 -0
  660. /package/{service-worker → src/service-worker}/index.d.ts +0 -0
@@ -0,0 +1,1668 @@
1
+ /* eslint-disable prefer-rest-params */
2
+ /* eslint-disable no-use-before-define */
3
+ /* eslint-disable new-cap */
4
+ /* eslint-disable func-names */
5
+ /* eslint-disable eqeqeq */
6
+ /* eslint-disable no-prototype-builtins */
7
+ /* eslint-disable class-methods-use-this */
8
+ /* eslint-disable no-restricted-syntax */
9
+ /* eslint-disable guard-for-in */
10
+ /* eslint-disable no-sequences */
11
+ /* eslint-disable no-multi-assign */
12
+ /* eslint-disable no-unused-expressions */
13
+ /* eslint-disable import/extensions */
14
+ /* eslint-disable no-param-reassign */
15
+ /* eslint-disable sonarjs/cognitive-complexity */
16
+ import Emitter from 'component-emitter';
17
+ import * as R from 'ramda';
18
+ import {
19
+ getJSONTrimmed,
20
+ generateUUID,
21
+ getUserProvidedConfigUrl,
22
+ findAllEnabledDestinations,
23
+ transformToRudderNames,
24
+ transformToServerNames,
25
+ checkReservedKeywords,
26
+ getConfigUrl,
27
+ getSDKUrlInfo,
28
+ commonNames,
29
+ getStringId,
30
+ resolveDataPlaneUrl,
31
+ fetchCookieConsentState,
32
+ parseQueryString,
33
+ } from '../utils/utils';
34
+ import { getReferrer, getReferringDomain, getDefaultPageProperties } from '../utils/pageProperties';
35
+ import { handleError } from '../utils/errorHandler';
36
+ import {
37
+ MAX_WAIT_FOR_INTEGRATION_LOAD,
38
+ INTEGRATION_LOAD_CHECK_INTERVAL,
39
+ DEST_SDK_BASE_URL,
40
+ INTG_SUFFIX,
41
+ POLYFILL_URL,
42
+ SAMESITE_COOKIE_OPTS,
43
+ UA_CH_LEVELS,
44
+ DEFAULT_INTEGRATIONS_CONFIG,
45
+ DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,
46
+ } from '../utils/constants';
47
+ import HtElementBuilder from '../utils/HtElementBuilder';
48
+ import Storage from '../utils/storage';
49
+ import { EventRepository } from '../utils/EventRepository';
50
+ import PreProcessQueue from '../utils/PreProcessQueue';
51
+ import logger from '../utils/logUtil';
52
+ import ScriptLoader from '../utils/ScriptLoader';
53
+ import parseLinker from '../utils/linker';
54
+ import { configToIntNames } from '../utils/config_to_integration_names';
55
+ import CookieConsentFactory from '../features/core/cookieConsent/CookieConsentFactory';
56
+ import { UserSession } from '../features/core/session';
57
+ import { mergeContext, mergeTopLevelElementsMutator } from '../utils/eventProcessorUtils';
58
+ import {
59
+ getMergedClientSuppliedIntegrations,
60
+ constructMessageIntegrationsObj,
61
+ } from '../utils/IntegrationsData';
62
+ import { getIntegrationsCDNPath } from '../utils/cdnPaths';
63
+ import { ErrorReportingService } from '../features/core/metrics/errorReporting/ErrorReportingService';
64
+ import { getUserAgentClientHint } from '../utils/clientHint';
65
+ import { DeviceModeTransformations } from '../features/core/deviceModeTransformation/transformationHandler';
66
+ import { isNonEmptyObject } from '../utils/ObjectUtils';
67
+
68
+ /**
69
+ * class responsible for handling core
70
+ * event tracking functionalities
71
+ */
72
+ class Analytics {
73
+ /**
74
+ * Creates an instance of Analytics.
75
+ * @memberof Analytics
76
+ */
77
+ constructor() {
78
+ this.initialized = false;
79
+ this.clientIntegrations = [];
80
+ this.loadOnlyIntegrations = {};
81
+ this.clientIntegrationObjects = undefined;
82
+ this.successfullyLoadedIntegration = [];
83
+ this.failedToBeLoadedIntegration = [];
84
+ this.toBeProcessedArray = [];
85
+ this.toBeProcessedByIntegrationArray = [];
86
+ this.storage = Storage;
87
+ this.eventRepository = EventRepository;
88
+ this.preProcessQueue = new PreProcessQueue();
89
+ this.sendAdblockPage = false;
90
+ this.sendAdblockPageOptions = {};
91
+ this.clientSuppliedCallbacks = {};
92
+ // Array to store the callback functions registered in the ready API
93
+ this.readyCallbacks = [];
94
+ this.methodToCallbackMapping = {
95
+ syncPixel: 'syncPixelCallback',
96
+ };
97
+ this.loaded = false;
98
+ this.loadIntegration = true;
99
+ this.bufferDataPlaneEventsUntilReady = false;
100
+ this.dataPlaneEventsBufferTimeout = DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS;
101
+ this.integrationsData = {};
102
+ this.dynamicallyLoadedIntegrations = {};
103
+ this.destSDKBaseURL = DEST_SDK_BASE_URL;
104
+ this.cookieConsentOptions = {};
105
+ this.logLevel = undefined;
106
+ // flag to indicate client integrations` ready status
107
+ this.clientIntegrationsReady = false;
108
+ this.uSession = UserSession;
109
+ this.version = '__PACKAGE_VERSION__';
110
+ this.lockIntegrationsVersion = false;
111
+ this.errorReporting = new ErrorReportingService(logger);
112
+ this.deniedConsentIds = [];
113
+ this.transformationHandler = DeviceModeTransformations;
114
+ }
115
+
116
+ /**
117
+ * initialize the user after load config
118
+ * @param {* | undefined} [anonymousIdOptions]
119
+ * @param {* | undefined} [userIdOptions]
120
+ */
121
+ initializeUser(anonymousIdOptions, userIdOptions) {
122
+ // By default, auto import other userID on SDK.load()
123
+ this.userId =
124
+ this.storage.getUserId(userIdOptions || { autoCapture: { enabled: true, source: 'auto' } }) ||
125
+ '';
126
+ // save once for storing older values to encrypted
127
+ this.storage.setUserId(this.userId);
128
+
129
+ this.userTraits = this.storage.getUserTraits() || {};
130
+ this.storage.setUserTraits(this.userTraits);
131
+
132
+ this.groupId = this.storage.getGroupId() || '';
133
+ this.storage.setGroupId(this.groupId);
134
+
135
+ this.groupTraits = this.storage.getGroupTraits() || {};
136
+ this.storage.setGroupTraits(this.groupTraits);
137
+
138
+ // By default, auto import other anonymous IDs on SDK.load()
139
+ this.anonymousId = this.getAnonymousId(
140
+ anonymousIdOptions || { autoCapture: { enabled: true, source: 'auto' } },
141
+ );
142
+ this.storage.setAnonymousId(this.anonymousId);
143
+ }
144
+
145
+ setInitialPageProperties() {
146
+ if (
147
+ this.storage.getInitialReferrer() == null &&
148
+ this.storage.getInitialReferringDomain() == null
149
+ ) {
150
+ const initialReferrer = getReferrer();
151
+ this.storage.setInitialReferrer(initialReferrer);
152
+ this.storage.setInitialReferringDomain(getReferringDomain(initialReferrer));
153
+ }
154
+ }
155
+
156
+ allModulesInitialized(time = 0) {
157
+ return new Promise((resolve) => {
158
+ if (
159
+ this.clientIntegrations.every(
160
+ (intg) =>
161
+ this.dynamicallyLoadedIntegrations[`${configToIntNames[intg.name]}${INTG_SUFFIX}`] !=
162
+ undefined,
163
+ )
164
+ ) {
165
+ // logger.debug(
166
+ // "All integrations loaded dynamically",
167
+ // this.dynamicallyLoadedIntegrations
168
+ // );
169
+ resolve(this);
170
+ } else if (time >= 2 * MAX_WAIT_FOR_INTEGRATION_LOAD) {
171
+ // logger.debug("Max wait for dynamically loaded integrations over")
172
+ resolve(this);
173
+ } else {
174
+ this.pause(INTEGRATION_LOAD_CHECK_INTERVAL).then(() =>
175
+ // logger.debug("Check if all integration SDKs are loaded after pause")
176
+ this.allModulesInitialized(time + INTEGRATION_LOAD_CHECK_INTERVAL).then(resolve),
177
+ );
178
+ }
179
+ });
180
+ }
181
+
182
+ /**
183
+ * Function to execute the ready method callbacks
184
+ * @param {Analytics} self
185
+ */
186
+ executeReadyCallback() {
187
+ this.readyCallbacks.forEach((callback) => callback());
188
+ }
189
+
190
+ /**
191
+ * A function to validate integration SDK is available in window
192
+ * and integration constructor is not undefined
193
+ * @param {string} pluginName
194
+ * @param {string} modName
195
+ * @returns boolean
196
+ */
197
+ integrationSDKLoaded(pluginName, modName) {
198
+ return (
199
+ window[pluginName] &&
200
+ window[pluginName][modName] &&
201
+ window[pluginName][modName].prototype &&
202
+ typeof window[pluginName][modName].prototype.constructor !== 'undefined'
203
+ );
204
+ }
205
+
206
+ /**
207
+ * Process the response from control plane and
208
+ * call initialize for integrations
209
+ *
210
+ * @param {*} status
211
+ * @param {*} responseVal
212
+ * @memberof Analytics
213
+ */
214
+ processResponse(status, responseVal) {
215
+ try {
216
+ // logger.debug(`===in process response=== ${status}`);
217
+
218
+ let response = responseVal;
219
+ try {
220
+ if (typeof responseVal === 'string') {
221
+ response = JSON.parse(responseVal);
222
+ }
223
+
224
+ // Do not proceed if the ultimate response value is not an object
225
+ if (!response || typeof response !== 'object' || Array.isArray(response)) {
226
+ logger.error('Invalid source configuration' + JSON.stringify(response));
227
+ return;
228
+ }
229
+ } catch (err) {
230
+ handleError(err);
231
+ return;
232
+ }
233
+
234
+ // Initialise error reporting provider if set in source config
235
+ try {
236
+ this.errorReporting.init(response.source.config, response.source.id);
237
+ } catch (err) {
238
+ handleError(err);
239
+ }
240
+
241
+ // determine the dataPlaneUrl
242
+ this.serverUrl = resolveDataPlaneUrl(response, this.serverUrl, this.options);
243
+
244
+ // Initialize event repository
245
+ this.eventRepository.initialize(this.writeKey, this.serverUrl, this.options);
246
+ this.loaded = true;
247
+ // Initialize transformation handler once we determine the dataPlaneUrl
248
+ this.transformationHandler.init(this.writeKey, this.serverUrl, this.storage.getAuthToken());
249
+
250
+ // Execute onLoaded callback if provided in load options
251
+ if (this.options && typeof this.options.onLoaded === 'function') {
252
+ this.options.onLoaded(this);
253
+ }
254
+
255
+ // Execute any pending buffered requests
256
+ // (needed if the load call was not previously buffered)
257
+ processDataInAnalyticsArray(this);
258
+
259
+ response.source.destinations.forEach(function (destination) {
260
+ // logger.debug(
261
+ // `Destination ${index} Enabled? ${destination.enabled} Type: ${destination.destinationDefinition.name} Use Native SDK? true`
262
+ // );
263
+ if (destination.enabled) {
264
+ this.clientIntegrations.push({
265
+ name: destination.destinationDefinition.name,
266
+ config: destination.config,
267
+ destinationInfo: {
268
+ shouldApplyDeviceModeTransformation:
269
+ destination.shouldApplyDeviceModeTransformation || false,
270
+ propagateEventsUntransformedOnError:
271
+ destination.propagateEventsUntransformedOnError || false,
272
+ destinationId: destination.id,
273
+ },
274
+ });
275
+ }
276
+ }, this);
277
+
278
+ // intersection of config-plane native sdk destinations with sdk load time destination list
279
+ this.clientIntegrations = findAllEnabledDestinations(
280
+ this.loadOnlyIntegrations,
281
+ this.clientIntegrations,
282
+ );
283
+ // Check if cookie consent manager is being set through load options
284
+ if (Object.keys(this.cookieConsentOptions).length > 0) {
285
+ // Call the cookie consent factory to initialise and return the type of cookie
286
+ // consent being set. For now we only support OneTrust.
287
+ try {
288
+ const cookieConsent = CookieConsentFactory.initialize(this.cookieConsentOptions);
289
+ // Fetch denied consent group Ids and pass it to cloud mode
290
+ this.deniedConsentIds = cookieConsent && cookieConsent.getDeniedList();
291
+ // If cookie consent object is return we filter according to consents given by user
292
+ // else we do not consider any filtering for cookie consent.
293
+ this.clientIntegrations = this.clientIntegrations.filter(
294
+ (intg) =>
295
+ !cookieConsent || // check if cookieconsent object is present and then do filtering
296
+ (cookieConsent && cookieConsent.isEnabled(intg.config)),
297
+ );
298
+ } catch (e) {
299
+ handleError(e);
300
+ }
301
+ }
302
+
303
+ // filter destination that doesn't have mapping config-->Integration names
304
+ this.clientIntegrations = this.clientIntegrations.filter((intg) => {
305
+ if (configToIntNames[intg.name]) {
306
+ return true;
307
+ }
308
+ logger.error(`[Analytics] Integration:: ${intg.name} not available for initialization`);
309
+ return false;
310
+ });
311
+
312
+ let suffix = ''; // default suffix
313
+
314
+ // Get the CDN base URL, if staging url
315
+ const { isStaging } = getSDKUrlInfo();
316
+ if (isStaging) {
317
+ suffix = '-staging'; // stagging suffix
318
+ }
319
+
320
+ if (this.bufferDataPlaneEventsUntilReady) {
321
+ // Fallback logic to process buffered cloud mode events if integrations are failed to load in given interval
322
+ setTimeout(() => {
323
+ this.processBufferedCloudModeEvents();
324
+ }, this.dataPlaneEventsBufferTimeout);
325
+ }
326
+
327
+ this.errorReporting.leaveBreadcrumb('Starting device-mode initialization');
328
+ // logger.debug("this.clientIntegrations: ", this.clientIntegrations)
329
+ // Load all the client integrations dynamically
330
+ this.clientIntegrations.forEach((intg) => {
331
+ const modName = configToIntNames[intg.name]; // script URL can be constructed from this
332
+ const pluginName = `${modName}${INTG_SUFFIX}`; // this is the name of the object loaded on the window
333
+ const modURL = `${this.destSDKBaseURL}/${modName}${suffix}.min.js`;
334
+
335
+ if (!window.hasOwnProperty(pluginName)) {
336
+ ScriptLoader(pluginName, modURL, { isNonNativeSDK: true });
337
+ }
338
+
339
+ const self = this;
340
+ const interval = setInterval(() => {
341
+ if (self.integrationSDKLoaded(pluginName, modName)) {
342
+ const intMod = window[pluginName];
343
+ clearInterval(interval);
344
+
345
+ // logger.debug(pluginName, " dynamically loaded integration SDK");
346
+
347
+ let intgInstance;
348
+ try {
349
+ const msg = `[Analytics] processResponse :: trying to initialize integration name:: ${pluginName}`;
350
+ // logger.debug(msg);
351
+ this.errorReporting.leaveBreadcrumb(msg);
352
+ intgInstance = new intMod[modName](intg.config, self, intg.destinationInfo);
353
+ intgInstance.init();
354
+
355
+ // logger.debug(pluginName, " initializing destination");
356
+
357
+ self.isInitialized(intgInstance).then(() => {
358
+ // logger.debug(pluginName, " module init sequence complete");
359
+ self.dynamicallyLoadedIntegrations[pluginName] = intMod[modName];
360
+ });
361
+ } catch (e) {
362
+ const message = `[Analytics] 'integration.init()' failed :: ${pluginName} :: ${e.message}`;
363
+ handleError(e, message);
364
+ self.failedToBeLoadedIntegration.push(intgInstance);
365
+ }
366
+ }
367
+ }, 100);
368
+
369
+ setTimeout(() => {
370
+ clearInterval(interval);
371
+ }, MAX_WAIT_FOR_INTEGRATION_LOAD);
372
+ });
373
+
374
+ const self = this;
375
+ this.allModulesInitialized().then(() => {
376
+ if (!self.clientIntegrations || self.clientIntegrations.length === 0) {
377
+ // If no integrations are there to be loaded
378
+ // set clientIntegrationsReady to be true
379
+ this.clientIntegrationsReady = true;
380
+ // Execute the callbacks if any
381
+ this.executeReadyCallback();
382
+ this.toBeProcessedByIntegrationArray = [];
383
+ return;
384
+ }
385
+
386
+ self.replayEvents(self);
387
+ });
388
+ } catch (error) {
389
+ handleError(error);
390
+ }
391
+ }
392
+
393
+ /**
394
+ * A function to send single event to a destination
395
+ * @param {instance} destination
396
+ * @param {Object} htElement
397
+ * @param {String} methodName
398
+ */
399
+ sendDataToDestination(destination, htElement, methodName) {
400
+ try {
401
+ if (destination[methodName]) {
402
+ const clonedHtElement = R.clone(htElement);
403
+ destination[methodName](clonedHtElement);
404
+ }
405
+ } catch (err) {
406
+ const message = `[sendToNative]:: [Destination: ${destination.name}]:: `;
407
+ handleError(err, message);
408
+ }
409
+ }
410
+
411
+ /**
412
+ * A function that gets the transformed event and
413
+ * depending on the response either send the transformed/untransformed event to destination or just log error.
414
+ * @param {Array} destWithTransformation List of device mode destination that has transformation connected
415
+ * @param {Object} htElement Rudder event
416
+ * @param {string} methodName Type of event page/track/identify etc.
417
+ */
418
+ sendTransformedDataToDestination(destWithTransformation, htElement, methodName) {
419
+ try {
420
+ // convert integrations object to server identified names, kind of hack now!
421
+ transformToServerNames(htElement.message.integrations);
422
+ const destinationIds = destWithTransformation.map((e) => e.destinationId);
423
+ // Process Transformation
424
+ this.transformationHandler.enqueue(
425
+ htElement,
426
+ destinationIds,
427
+ ({ status, transformedPayload, errorMessage }) => {
428
+ destWithTransformation.forEach((intg) => {
429
+ try {
430
+ switch (status) {
431
+ // The transformation request is successful
432
+ case 200: {
433
+ // filter destination specific transformed payload
434
+ const destTransformedResult = transformedPayload.find(
435
+ (e) => e.id === intg.destinationId,
436
+ );
437
+ const eventsToSend = [];
438
+ destTransformedResult?.payload.forEach((tEvent) => {
439
+ // Transformation successful
440
+ // event level status is 200
441
+ if (tEvent.status === '200') {
442
+ // push transformed event to the queue
443
+ eventsToSend.push(tEvent);
444
+ } else {
445
+ const msgPrefix = `[DMT]:: Event transformation unsuccessful for destination "${intg.name}". Reason: `;
446
+
447
+ let reason = 'Unknown';
448
+ if (tEvent.status === '410') {
449
+ reason = 'Transformation is not available';
450
+ }
451
+
452
+ let action = 'Dropping the event';
453
+ let logMethod = logger.error;
454
+ if (intg.propagateEventsUntransformedOnError === true) {
455
+ action = 'Sending untransformed event to the destination';
456
+ logMethod = logger.warn;
457
+ eventsToSend.push({ event: htElement.message });
458
+ }
459
+
460
+ const logMsg = `${msgPrefix} ${reason}. ${action}.`;
461
+ logMethod(logMsg);
462
+ }
463
+ });
464
+ // send events to destination
465
+ eventsToSend?.forEach((tEvent) => {
466
+ // send only if the event is not null/undefined/empty object
467
+ if (isNonEmptyObject(tEvent.event)) {
468
+ this.sendDataToDestination(intg, { message: tEvent.event }, methodName);
469
+ }
470
+ });
471
+ break;
472
+ }
473
+ // Transformation server access denied
474
+ case 404: {
475
+ logger.warn(
476
+ `[DMT]:: Transformation server access is denied. The configuration data seems to be out of sync. Sending untransformed event to the destination.`,
477
+ );
478
+ // send untransformed event to destination
479
+ this.sendDataToDestination(intg, htElement, methodName);
480
+ break;
481
+ }
482
+ // For any other cases
483
+ default: {
484
+ if (intg.propagateEventsUntransformedOnError === true) {
485
+ logger.warn(
486
+ `[DMT]::[Destination: ${intg.name}] :: Transformation request failed with status: ${status} ${errorMessage}. Sending untransformed event.`,
487
+ );
488
+ // send untransformed event to destination
489
+ this.sendDataToDestination(intg, htElement, methodName);
490
+ } else {
491
+ logger.error(
492
+ `[DMT]::[Destination: ${intg.name}] :: Transformation request failed with status: ${status} ${errorMessage}. Dropping the event.`,
493
+ );
494
+ }
495
+ break;
496
+ }
497
+ }
498
+ } catch (e) {
499
+ if (e instanceof Error) {
500
+ e.message = `[DMT]::[Destination:${intg.name}]:: ${e.message}`;
501
+ }
502
+ handleError(e);
503
+ }
504
+ });
505
+ },
506
+ );
507
+ } catch (e) {
508
+ if (e instanceof Error) {
509
+ e.message = `[DMT]:: ${e.message}`;
510
+ }
511
+ handleError(e);
512
+ }
513
+ }
514
+
515
+ /**
516
+ * A function to process and send events to device mode destinations
517
+ * @param {instance} destinations
518
+ * @param {Object} htElement
519
+ * @param {String} methodName
520
+ */
521
+ processAndSendEventsToDeviceMode(destinations, htElement, methodName) {
522
+ const destWithoutTransformation = [];
523
+ const destWithTransformation = [];
524
+
525
+ // Depending on transformation is connected or not
526
+ // create two sets of destinations
527
+ destinations.forEach((intg) => {
528
+ const sendEvent = !this.IsEventBlackListed(htElement.message.event, intg.name);
529
+
530
+ // Block the event if it is blacklisted for the device-mode destination
531
+ if (sendEvent) {
532
+ if (intg.shouldApplyDeviceModeTransformation) {
533
+ destWithTransformation.push(intg);
534
+ } else {
535
+ destWithoutTransformation.push(intg);
536
+ }
537
+ }
538
+ });
539
+ // loop through destinations that doesn't have
540
+ // transformation connected with it and send events
541
+ destWithoutTransformation.forEach((intg) => {
542
+ this.sendDataToDestination(intg, htElement, methodName);
543
+ });
544
+
545
+ if (destWithTransformation.length > 0) {
546
+ this.sendTransformedDataToDestination(destWithTransformation, htElement, methodName);
547
+ }
548
+ }
549
+
550
+ /**
551
+ *
552
+ * @param {*} type
553
+ * @param {*} htElement
554
+ * Sends cloud mode events to server
555
+ */
556
+ queueEventForDataPlane(type, htElement) {
557
+ // if not specified at event level, All: true is default
558
+ const clientSuppliedIntegrations = htElement.message.integrations || { All: true };
559
+ htElement.message.integrations = getMergedClientSuppliedIntegrations(
560
+ this.integrationsData,
561
+ clientSuppliedIntegrations,
562
+ );
563
+ // self analytics process, send to ht events
564
+ this.eventRepository.enqueue(htElement, type);
565
+ }
566
+
567
+ /**
568
+ * Processes the buffered cloud mode events and sends it to server
569
+ */
570
+ processBufferedCloudModeEvents() {
571
+ if (this.bufferDataPlaneEventsUntilReady) {
572
+ this.preProcessQueue.activateProcessor();
573
+ }
574
+ }
575
+
576
+ // eslint-disable-next-line class-methods-use-this
577
+ replayEvents(object) {
578
+ // logger.debug(
579
+ // "===replay events called====",
580
+ // " successfully loaded count: ",
581
+ // object.successfullyLoadedIntegration.length,
582
+ // " failed loaded count: ",
583
+ // object.failedToBeLoadedIntegration.length
584
+ // );
585
+ this.errorReporting.leaveBreadcrumb(`Started replaying buffered events`);
586
+ // eslint-disable-next-line no-param-reassign
587
+ object.clientIntegrationObjects = [];
588
+ // eslint-disable-next-line no-param-reassign
589
+ object.clientIntegrationObjects = object.successfullyLoadedIntegration;
590
+
591
+ // logger.debug(
592
+ // "==registering after callback===",
593
+ // " after to be called after count : ",
594
+ // object.clientIntegrationObjects.length
595
+ // );
596
+
597
+ if (object.clientIntegrationObjects.every((intg) => !intg.isReady || intg.isReady())) {
598
+ // Integrations are ready
599
+ // set clientIntegrationsReady to be true
600
+ this.integrationsData = constructMessageIntegrationsObj(
601
+ this.integrationsData,
602
+ object.clientIntegrationObjects,
603
+ );
604
+ object.clientIntegrationsReady = true;
605
+ // Execute the callbacks if any
606
+ object.executeReadyCallback();
607
+ }
608
+
609
+ this.processBufferedCloudModeEvents();
610
+
611
+ // send the queued events to the fetched integration
612
+ object.toBeProcessedByIntegrationArray.forEach((event) => {
613
+ const methodName = event[0];
614
+ event.shift();
615
+
616
+ // convert common names to sdk identified name
617
+ if (Object.keys(event[0].message.integrations).length > 0) {
618
+ transformToRudderNames(event[0].message.integrations);
619
+ }
620
+
621
+ // if not specified at event level, All: true is default
622
+ const clientSuppliedIntegrations = event[0].message.integrations;
623
+
624
+ // get intersection between config plane native enabled destinations
625
+ // (which were able to successfully load on the page) vs user supplied integrations
626
+ const successfulLoadedIntersectClientSuppliedIntegrations = findAllEnabledDestinations(
627
+ clientSuppliedIntegrations,
628
+ object.clientIntegrationObjects,
629
+ );
630
+
631
+ // send to all integrations now from the 'toBeProcessedByIntegrationArray' replay queue
632
+ this.processAndSendEventsToDeviceMode(
633
+ successfulLoadedIntersectClientSuppliedIntegrations,
634
+ event[0],
635
+ methodName,
636
+ );
637
+ });
638
+ object.toBeProcessedByIntegrationArray = [];
639
+ }
640
+
641
+ pause(time) {
642
+ return new Promise((resolve) => {
643
+ setTimeout(resolve, time);
644
+ });
645
+ }
646
+
647
+ isInitialized(instance, time = 0) {
648
+ return new Promise((resolve) => {
649
+ if (instance.isLoaded()) {
650
+ // logger.debug("===integration loaded successfully====", instance.name)
651
+ this.successfullyLoadedIntegration.push(instance);
652
+ resolve(this);
653
+ } else if (time >= MAX_WAIT_FOR_INTEGRATION_LOAD) {
654
+ // logger.debug("====max wait over====")
655
+ this.failedToBeLoadedIntegration.push(instance);
656
+ resolve(this);
657
+ } else {
658
+ this.pause(INTEGRATION_LOAD_CHECK_INTERVAL).then(() =>
659
+ // logger.debug("====after pause, again checking====")
660
+ this.isInitialized(instance, time + INTEGRATION_LOAD_CHECK_INTERVAL).then(resolve),
661
+ );
662
+ }
663
+ });
664
+ }
665
+
666
+ /**
667
+ * Process page params and forward to page call
668
+ *
669
+ * @param {*} category
670
+ * @param {*} name
671
+ * @param {*} properties
672
+ * @param {*} options
673
+ * @param {*} callback
674
+ * @memberof Analytics
675
+ */
676
+ page(category, name, properties, options, callback) {
677
+ this.errorReporting.leaveBreadcrumb(`Page event`);
678
+ if (!this.loaded) {
679
+ this.toBeProcessedArray.push(['page', ...arguments]);
680
+ return;
681
+ }
682
+ if (typeof options === 'function') (callback = options), (options = null);
683
+ if (typeof properties === 'function') (callback = properties), (options = properties = null);
684
+ if (typeof name === 'function') (callback = name), (options = properties = name = null);
685
+ if (typeof category === 'function')
686
+ (callback = category), (options = properties = name = category = null);
687
+ if (typeof category === 'object' && category != null && category != undefined)
688
+ (options = name), (properties = category), (name = category = null);
689
+ if (typeof name === 'object' && name != null && name != undefined)
690
+ (options = properties), (properties = name), (name = null);
691
+ if (typeof category === 'string' && typeof name !== 'string')
692
+ (name = category), (category = null);
693
+ if (this.sendAdblockPage && category != 'EventsJS-Initiated') {
694
+ this.sendSampleRequest();
695
+ }
696
+ let clonedProperties = R.clone(properties);
697
+ const clonedOptions = R.clone(options);
698
+
699
+ const htElement = new HtElementBuilder().setType('page').build();
700
+ if (!clonedProperties) {
701
+ clonedProperties = {};
702
+ }
703
+ if (name) {
704
+ htElement.message.name = clonedProperties.name = name;
705
+ }
706
+ if (category) {
707
+ htElement.message.category = clonedProperties.category = category;
708
+ }
709
+
710
+ htElement.message.properties = this.getPageProperties(clonedProperties);
711
+
712
+ this.processAndSendDataToDestinations('page', htElement, clonedOptions, callback);
713
+ }
714
+
715
+ /**
716
+ * Process track params and forward to track call
717
+ *
718
+ * @param {*} event
719
+ * @param {*} properties
720
+ * @param {*} options
721
+ * @param {*} callback
722
+ * @memberof Analytics
723
+ */
724
+ track(event, properties, options, callback) {
725
+ this.errorReporting.leaveBreadcrumb(`Track event`);
726
+ if (!this.loaded) {
727
+ this.toBeProcessedArray.push(['track', ...arguments]);
728
+ return;
729
+ }
730
+ if (typeof options === 'function') (callback = options), (options = null);
731
+ if (typeof properties === 'function')
732
+ (callback = properties), (options = null), (properties = null);
733
+
734
+ const clonedProperties = R.clone(properties);
735
+ const clonedOptions = R.clone(options);
736
+
737
+ const htElement = new HtElementBuilder().setType('track').build();
738
+ if (event) {
739
+ htElement.setEventName(event);
740
+ }
741
+ htElement.setProperty(clonedProperties || {});
742
+
743
+ this.processAndSendDataToDestinations('track', htElement, clonedOptions, callback);
744
+ }
745
+
746
+ /**
747
+ * Process identify params and forward to identify call
748
+ *
749
+ * @param {*} userId
750
+ * @param {*} traits
751
+ * @param {*} options
752
+ * @param {*} callback
753
+ * @memberof Analytics
754
+ */
755
+ identify(userId, traits, options, callback) {
756
+ console.log('completed identify 1');
757
+
758
+ this.errorReporting.leaveBreadcrumb(`Identify event`);
759
+ if (!this.loaded) {
760
+ this.toBeProcessedArray.push(['identify', ...arguments]);
761
+ return;
762
+ }
763
+ console.log('completed identify 2');
764
+
765
+ if (typeof options === 'function') (callback = options), (options = null);
766
+ if (typeof traits === 'function') (callback = traits), (options = null), (traits = null);
767
+ if (typeof userId === 'object') (options = traits), (traits = userId), (userId = this.userId);
768
+
769
+ const normalisedUserId = getStringId(userId);
770
+ if (normalisedUserId && this.userId && normalisedUserId !== this.userId) {
771
+ this.reset();
772
+ }
773
+ this.userId = normalisedUserId;
774
+ this.storage.setUserId(this.userId);
775
+
776
+ const clonedTraits = R.clone(traits);
777
+ const clonedOptions = R.clone(options);
778
+
779
+ if (clonedTraits) {
780
+ for (const key in clonedTraits) {
781
+ this.userTraits[key] = clonedTraits[key];
782
+ }
783
+ this.storage.setUserTraits(this.userTraits);
784
+ }
785
+ const htElement = new HtElementBuilder().setType('identify').build();
786
+
787
+ this.processAndSendDataToDestinations('identify', htElement, clonedOptions, callback);
788
+ console.log('completed identify 3');
789
+ }
790
+
791
+ /**
792
+ *
793
+ * @param {*} to
794
+ * @param {*} from
795
+ * @param {*} options
796
+ * @param {*} callback
797
+ */
798
+ alias(to, from, options, callback) {
799
+ this.errorReporting.leaveBreadcrumb(`Alias event`);
800
+ if (!this.loaded) {
801
+ this.toBeProcessedArray.push(['alias', ...arguments]);
802
+ return;
803
+ }
804
+ if (typeof options === 'function') (callback = options), (options = null);
805
+ if (typeof from === 'function') (callback = from), (options = null), (from = null);
806
+ if (typeof to === 'function') (callback = to), (options = null), (from = null), (to = null);
807
+ if (typeof from === 'object') (options = from), (from = null);
808
+ if (typeof to === 'object') (options = to), (from = null), (to = null);
809
+
810
+ const htElement = new HtElementBuilder().setType('alias').build();
811
+
812
+ htElement.message.previousId =
813
+ getStringId(from) || (this.userId ? this.userId : this.getAnonymousId());
814
+ htElement.message.userId = getStringId(to);
815
+ const clonedOptions = R.clone(options);
816
+
817
+ this.processAndSendDataToDestinations('alias', htElement, clonedOptions, callback);
818
+ }
819
+
820
+ /**
821
+ *
822
+ * @param {*} to
823
+ * @param {*} from
824
+ * @param {*} options
825
+ * @param {*} callback
826
+ */
827
+ group(groupId, traits, options, callback) {
828
+ this.errorReporting.leaveBreadcrumb(`Group event`);
829
+ if (!this.loaded) {
830
+ this.toBeProcessedArray.push(['group', ...arguments]);
831
+ return;
832
+ }
833
+ if (arguments.length === 0) return;
834
+
835
+ if (typeof options === 'function') (callback = options), (options = null);
836
+ if (typeof traits === 'function') (callback = traits), (options = null), (traits = null);
837
+ if (typeof groupId === 'object')
838
+ (options = traits), (traits = groupId), (groupId = this.groupId);
839
+ if (typeof groupId === 'function')
840
+ (callback = groupId), (options = null), (traits = null), (groupId = this.groupId);
841
+
842
+ this.groupId = getStringId(groupId);
843
+ this.storage.setGroupId(this.groupId);
844
+ const clonedTraits = R.clone(traits);
845
+ const clonedOptions = R.clone(options);
846
+
847
+ const htElement = new HtElementBuilder().setType('group').build();
848
+
849
+ if (clonedTraits) {
850
+ for (const key in clonedTraits) {
851
+ this.groupTraits[key] = clonedTraits[key];
852
+ }
853
+ } else {
854
+ this.groupTraits = {};
855
+ }
856
+ this.storage.setGroupTraits(this.groupTraits);
857
+
858
+ this.processAndSendDataToDestinations('group', htElement, clonedOptions, callback);
859
+ }
860
+
861
+ IsEventBlackListed(eventName, intgName) {
862
+ if (!eventName || !(typeof eventName === 'string')) {
863
+ return false;
864
+ }
865
+ const sdkIntgName = commonNames[intgName];
866
+ const intg = this.clientIntegrations.find(
867
+ (clientIntegration) => clientIntegration.name === sdkIntgName,
868
+ );
869
+
870
+ const { blacklistedEvents, whitelistedEvents, eventFilteringOption } = intg.config;
871
+
872
+ if (!eventFilteringOption) {
873
+ return false;
874
+ }
875
+
876
+ const formattedEventName = eventName.trim().toUpperCase();
877
+ switch (eventFilteringOption) {
878
+ // disabled filtering
879
+ case 'disable':
880
+ return false;
881
+ // Blacklist is chosen for filtering events
882
+ case 'blacklistedEvents':
883
+ if (Array.isArray(blacklistedEvents)) {
884
+ return blacklistedEvents.some(
885
+ (eventObj) => eventObj.eventName.trim().toUpperCase() === formattedEventName,
886
+ );
887
+ }
888
+ return false;
889
+
890
+ // Whitelist is chosen for filtering events
891
+ case 'whitelistedEvents':
892
+ if (Array.isArray(whitelistedEvents)) {
893
+ return !whitelistedEvents.some(
894
+ (eventObj) => eventObj.eventName.trim().toUpperCase() === formattedEventName,
895
+ );
896
+ }
897
+ return true;
898
+
899
+ default:
900
+ return false;
901
+ }
902
+ }
903
+
904
+ /**
905
+ * A function to determine whether SDK should use the integration option provided in load call
906
+ * @returns boolean
907
+ */
908
+ shouldUseGlobalIntegrationsConfigInEvents() {
909
+ return (
910
+ this.useGlobalIntegrationsConfigInEvents &&
911
+ this.loadOnlyIntegrations &&
912
+ Object.keys(this.loadOnlyIntegrations).length > 0
913
+ );
914
+ }
915
+
916
+ /**
917
+ * Process and send data to destinations along with ht events BE
918
+ *
919
+ * @param {*} type
920
+ * @param {*} htElement
921
+ * @param {*} callback
922
+ * @memberof Analytics
923
+ */
924
+ processAndSendDataToDestinations(type, htElement, options, callback) {
925
+ try {
926
+ if (!this.anonymousId) {
927
+ this.setAnonymousId();
928
+ }
929
+
930
+ // assign page properties to context
931
+ // htElement.message.context.page = getDefaultPageProperties();
932
+ this.errorReporting.leaveBreadcrumb('Started sending data to destinations');
933
+ htElement.message.context.traits = {
934
+ ...this.userTraits,
935
+ };
936
+
937
+ if (type == 'identify') {
938
+ htElement.message.traits = {
939
+ ...this.userTraits,
940
+ };
941
+ }
942
+
943
+ // logger.debug("anonymousId: ", this.anonymousId)
944
+ htElement.message.anonymousId = this.anonymousId;
945
+ htElement.message.userId = htElement.message.userId ? htElement.message.userId : this.userId;
946
+
947
+ if (type == 'group') {
948
+ if (this.groupId) {
949
+ htElement.message.groupId = this.groupId;
950
+ }
951
+ if (this.groupTraits) {
952
+ htElement.message.traits = {
953
+ ...this.groupTraits,
954
+ };
955
+ }
956
+ }
957
+ // If auto/manual session tracking is enabled sessionId will be sent in the context
958
+ try {
959
+ const { sessionId, sessionStart } = this.uSession.getSessionInfo();
960
+ htElement.message.context.sessionId = sessionId;
961
+ if (sessionStart) htElement.message.context.sessionStart = true;
962
+ } catch (e) {
963
+ handleError(e);
964
+ }
965
+ // If cookie consent is enabled attach the denied consent group Ids to the context
966
+ if (fetchCookieConsentState(this.cookieConsentOptions)) {
967
+ htElement.message.context.consentManagement = {
968
+ deniedConsentIds: this.deniedConsentIds || [],
969
+ };
970
+ }
971
+
972
+ this.processOptionsParam(htElement, options);
973
+ // logger.debug(JSON.stringify(htElement))
974
+
975
+ // check for reserved keys and log
976
+ checkReservedKeywords(htElement.message, type);
977
+
978
+ let clientSuppliedIntegrations = htElement.message.integrations;
979
+
980
+ if (clientSuppliedIntegrations) {
981
+ // structure user supplied integrations object to ht events format
982
+ transformToRudderNames(clientSuppliedIntegrations);
983
+ } else if (this.shouldUseGlobalIntegrationsConfigInEvents()) {
984
+ // when useGlobalIntegrationsConfigInEvents load option is set to true and integration object provided in load
985
+ // is not empty use it at event level
986
+ clientSuppliedIntegrations = this.loadOnlyIntegrations;
987
+ } else {
988
+ // if not specified at event level, use default integration option
989
+ clientSuppliedIntegrations = DEFAULT_INTEGRATIONS_CONFIG;
990
+ }
991
+
992
+ htElement.message.integrations = clientSuppliedIntegrations;
993
+
994
+ try {
995
+ htElement.message.context['ua-ch'] = this.uach;
996
+ } catch (err) {
997
+ handleError(err);
998
+ }
999
+
1000
+ // config plane native enabled destinations, still not completely loaded
1001
+ // in the page, add the events to a queue and process later
1002
+ if (!this.clientIntegrationObjects) {
1003
+ // logger.debug("pushing in replay queue")
1004
+ // new event processing after analytics initialized but integrations not fetched from BE
1005
+ this.toBeProcessedByIntegrationArray.push([type, htElement]);
1006
+ } else {
1007
+ // get intersection between config plane native enabled destinations
1008
+ // (which were able to successfully load on the page) vs user supplied integrations
1009
+ const successfulLoadedIntersectClientSuppliedIntegrations = findAllEnabledDestinations(
1010
+ clientSuppliedIntegrations,
1011
+ this.clientIntegrationObjects,
1012
+ );
1013
+
1014
+ // try to first send to all integrations, if list populated from BE
1015
+ this.processAndSendEventsToDeviceMode(
1016
+ successfulLoadedIntersectClientSuppliedIntegrations,
1017
+ htElement,
1018
+ type,
1019
+ );
1020
+ }
1021
+
1022
+ const clonedHtElement = R.clone(htElement);
1023
+ // convert integrations object to server identified names, kind of hack now!
1024
+ transformToServerNames(clonedHtElement.message.integrations);
1025
+
1026
+ // Holding the cloud mode events based on flag and integrations load check
1027
+ const shouldNotBufferDataPlaneEvents =
1028
+ !this.bufferDataPlaneEventsUntilReady || this.clientIntegrationObjects;
1029
+ if (shouldNotBufferDataPlaneEvents) {
1030
+ this.queueEventForDataPlane(type, clonedHtElement);
1031
+ } else {
1032
+ this.preProcessQueue.enqueue(type, clonedHtElement);
1033
+ }
1034
+
1035
+ // logger.debug(`${type} is called `)
1036
+ if (callback && typeof callback === 'function') {
1037
+ callback(clonedHtElement);
1038
+ }
1039
+ } catch (error) {
1040
+ handleError(error);
1041
+ }
1042
+ }
1043
+
1044
+ utm(url) {
1045
+ const result = {};
1046
+ try {
1047
+ const urlObj = new URL(url);
1048
+ const UTM_PREFIX = 'utm_';
1049
+ urlObj.searchParams.forEach((value, sParam) => {
1050
+ if (sParam.startsWith(UTM_PREFIX)) {
1051
+ let utmParam = sParam.substring(UTM_PREFIX.length);
1052
+ // Not sure why we're doing this
1053
+ if (utmParam === 'campaign') {
1054
+ utmParam = 'name';
1055
+ }
1056
+ result[utmParam] = value;
1057
+ }
1058
+ });
1059
+ } catch (error) {
1060
+ // Do nothing
1061
+ }
1062
+ return result;
1063
+ }
1064
+
1065
+ /**
1066
+ * add campaign parsed details under context
1067
+ * @param {*} htElement
1068
+ */
1069
+ addCampaignInfo(htElement) {
1070
+ const msgContext = htElement.message.context;
1071
+ if (msgContext && typeof msgContext === 'object') {
1072
+ htElement.message.context.campaign = this.utm(window.location.href);
1073
+ }
1074
+ }
1075
+
1076
+ /**
1077
+ * process options parameter
1078
+ * Apart from top level keys merge everything under context
1079
+ * context.page's default properties are overridden by same keys of
1080
+ * provided properties in case of page call
1081
+ *
1082
+ * @param {*} htElement
1083
+ * @param {*} options
1084
+ * @memberof Analytics
1085
+ */
1086
+ processOptionsParam(htElement, options) {
1087
+ const { type, properties } = htElement.message;
1088
+
1089
+ this.addCampaignInfo(htElement);
1090
+
1091
+ // assign page properties to context.page
1092
+ // eslint-disable-next-line unicorn/consistent-destructuring
1093
+ htElement.message.context.page = this.getContextPageProperties(
1094
+ type === 'page' ? properties : undefined,
1095
+ );
1096
+ mergeTopLevelElementsMutator(htElement.message, options);
1097
+ htElement.message.context = mergeContext(htElement.message, options);
1098
+ }
1099
+
1100
+ getPageProperties(properties, options) {
1101
+ const defaultPageProperties = getDefaultPageProperties();
1102
+ const optionPageProperties = (options && options.page) || {};
1103
+ for (const key in defaultPageProperties) {
1104
+ if (properties[key] === undefined) {
1105
+ properties[key] = optionPageProperties[key] || defaultPageProperties[key];
1106
+ }
1107
+ }
1108
+ return properties;
1109
+ }
1110
+
1111
+ // Assign page properties to context.page if the same property is not provided under context.page
1112
+ getContextPageProperties(properties) {
1113
+ const defaultPageProperties = getDefaultPageProperties();
1114
+ const contextPageProperties = {};
1115
+ for (const key in defaultPageProperties) {
1116
+ contextPageProperties[key] =
1117
+ properties && properties[key] ? properties[key] : defaultPageProperties[key];
1118
+ }
1119
+ return contextPageProperties;
1120
+ }
1121
+
1122
+ /**
1123
+ * Clear user information
1124
+ *
1125
+ * @memberof Analytics
1126
+ */
1127
+ reset(flag) {
1128
+ this.errorReporting.leaveBreadcrumb(`reset API :: flag: ${flag}`);
1129
+
1130
+ if (!this.loaded) {
1131
+ this.toBeProcessedArray.push(['reset', flag]);
1132
+ return;
1133
+ }
1134
+ if (flag) {
1135
+ this.anonymousId = '';
1136
+ }
1137
+ this.userId = '';
1138
+ this.userTraits = {};
1139
+ this.groupId = '';
1140
+ this.groupTraits = {};
1141
+ this.uSession.reset();
1142
+ this.storage.clear(flag);
1143
+ }
1144
+
1145
+ getAnonymousId(anonymousIdOptions) {
1146
+ // if (!this.loaded) return;
1147
+ this.anonymousId = this.storage.getAnonymousId(anonymousIdOptions);
1148
+ if (!this.anonymousId) {
1149
+ this.setAnonymousId();
1150
+ }
1151
+ return this.anonymousId;
1152
+ }
1153
+
1154
+ getUserId() {
1155
+ return this.userId;
1156
+ }
1157
+
1158
+ getSessionId() {
1159
+ return this.uSession.getSessionId();
1160
+ }
1161
+
1162
+ getUserTraits() {
1163
+ return this.userTraits;
1164
+ }
1165
+
1166
+ getGroupId() {
1167
+ return this.groupId;
1168
+ }
1169
+
1170
+ getGroupTraits() {
1171
+ return this.groupTraits;
1172
+ }
1173
+
1174
+ /**
1175
+ * Sets anonymous id in the following precedence:
1176
+ * 1. anonymousId: Id directly provided to the function.
1177
+ * 2. rudderAmpLinkerParm: value generated from linker query parm (rudderstack)
1178
+ * using parseLinker util.
1179
+ * 3. generateUUID: A new unique id is generated and assigned.
1180
+ *
1181
+ * @param {string} anonymousId
1182
+ * @param {string} rudderAmpLinkerParm
1183
+ */
1184
+ setAnonymousId(anonymousId, rudderAmpLinkerParm) {
1185
+ // if (!this.loaded) return;
1186
+ const parsedAnonymousIdObj = rudderAmpLinkerParm ? parseLinker(rudderAmpLinkerParm) : null;
1187
+ const parsedAnonymousId = parsedAnonymousIdObj ? parsedAnonymousIdObj.rs_amp_id : null;
1188
+ this.anonymousId = anonymousId || parsedAnonymousId || generateUUID();
1189
+ this.storage.setAnonymousId(this.anonymousId);
1190
+ }
1191
+
1192
+ isValidWriteKey(writeKey) {
1193
+ return writeKey && typeof writeKey === 'string' && writeKey.trim().length > 0;
1194
+ }
1195
+
1196
+ isValidServerUrl(serverUrl) {
1197
+ return serverUrl && typeof serverUrl === 'string' && serverUrl.trim().length > 0;
1198
+ }
1199
+
1200
+ isDatasetAvailable() {
1201
+ const t = document.createElement('div');
1202
+ return t.setAttribute('data-a-b', 'c'), t.dataset ? t.dataset.aB === 'c' : false;
1203
+ }
1204
+
1205
+ /**
1206
+ * Load after polyfills are loaded
1207
+ * @param {*} writeKey
1208
+ * @param {*} serverUrl
1209
+ * @param {*} options
1210
+ * @returns
1211
+ */
1212
+ loadAfterPolyfill(writeKey, serverUrl, options) {
1213
+ if (typeof serverUrl === 'object' && serverUrl !== null) {
1214
+ options = serverUrl;
1215
+ serverUrl = null;
1216
+ }
1217
+ if (options && options.logLevel) {
1218
+ this.logLevel = options.logLevel;
1219
+ logger.setLogLevel(options.logLevel);
1220
+ }
1221
+ if (!this.isValidWriteKey(writeKey)) {
1222
+ throw Error('Unable to load the SDK due to invalid writeKey');
1223
+ }
1224
+ if (!this.storage || Object.keys(this.storage).length === 0) {
1225
+ throw Error('Cannot proceed as no storage is available');
1226
+ }
1227
+ if (options && options.cookieConsentManager)
1228
+ this.cookieConsentOptions = options.cookieConsentManager;
1229
+
1230
+ this.writeKey = writeKey;
1231
+ this.serverUrl = serverUrl;
1232
+ this.options = options;
1233
+
1234
+ let storageOptions = {};
1235
+
1236
+ if (options && options.setCookieDomain) {
1237
+ storageOptions = { ...storageOptions, domain: options.setCookieDomain };
1238
+ }
1239
+
1240
+ if (options && typeof options.secureCookie === 'boolean') {
1241
+ storageOptions = { ...storageOptions, secure: options.secureCookie };
1242
+ }
1243
+
1244
+ if (options && SAMESITE_COOKIE_OPTS.indexOf(options.sameSiteCookie) !== -1) {
1245
+ storageOptions = { ...storageOptions, samesite: options.sameSiteCookie };
1246
+ }
1247
+ this.storage.options(storageOptions);
1248
+
1249
+ const isUACHOptionAvailable =
1250
+ options &&
1251
+ typeof options.uaChTrackLevel === 'string' &&
1252
+ UA_CH_LEVELS.includes(options.uaChTrackLevel);
1253
+
1254
+ if (isUACHOptionAvailable) {
1255
+ this.uaChTrackLevel = options.uaChTrackLevel;
1256
+ }
1257
+
1258
+ if (navigator.userAgentData) {
1259
+ getUserAgentClientHint((uach) => {
1260
+ this.uach = uach;
1261
+ }, this.uaChTrackLevel);
1262
+ }
1263
+
1264
+ if (options && options.integrations) {
1265
+ Object.assign(this.loadOnlyIntegrations, options.integrations);
1266
+ transformToRudderNames(this.loadOnlyIntegrations);
1267
+ }
1268
+
1269
+ this.useGlobalIntegrationsConfigInEvents =
1270
+ options && options.useGlobalIntegrationsConfigInEvents === true;
1271
+
1272
+ if (options && options.sendAdblockPage) {
1273
+ this.sendAdblockPage = true;
1274
+ }
1275
+ if (
1276
+ options &&
1277
+ options.sendAdblockPageOptions &&
1278
+ typeof options.sendAdblockPageOptions === 'object'
1279
+ ) {
1280
+ this.sendAdblockPageOptions = options.sendAdblockPageOptions;
1281
+ }
1282
+ // Session initialization
1283
+ this.uSession.initialize(options);
1284
+
1285
+ if (options && options.clientSuppliedCallbacks) {
1286
+ // convert to ht events recognized method names
1287
+ const transformedCallbackMapping = {};
1288
+ Object.keys(this.methodToCallbackMapping).forEach((methodName) => {
1289
+ if (
1290
+ this.methodToCallbackMapping.hasOwnProperty(methodName) &&
1291
+ options.clientSuppliedCallbacks[this.methodToCallbackMapping[methodName]]
1292
+ ) {
1293
+ transformedCallbackMapping[methodName] =
1294
+ options.clientSuppliedCallbacks[this.methodToCallbackMapping[methodName]];
1295
+ }
1296
+ });
1297
+ Object.assign(this.clientSuppliedCallbacks, transformedCallbackMapping);
1298
+ this.registerCallbacks(true);
1299
+ }
1300
+
1301
+ if (options && options.loadIntegration != undefined) {
1302
+ this.loadIntegration = !!options.loadIntegration;
1303
+ }
1304
+
1305
+ if (options && typeof options.bufferDataPlaneEventsUntilReady === 'boolean') {
1306
+ this.bufferDataPlaneEventsUntilReady = options.bufferDataPlaneEventsUntilReady === true;
1307
+ if (this.bufferDataPlaneEventsUntilReady) {
1308
+ this.preProcessQueue.init(this.options, this.queueEventForDataPlane.bind(this));
1309
+ }
1310
+ }
1311
+
1312
+ if (options && typeof options.dataPlaneEventsBufferTimeout === 'number') {
1313
+ this.dataPlaneEventsBufferTimeout = options.dataPlaneEventsBufferTimeout;
1314
+ }
1315
+
1316
+ if (options && options.lockIntegrationsVersion !== undefined) {
1317
+ this.lockIntegrationsVersion = options.lockIntegrationsVersion === true;
1318
+ }
1319
+
1320
+ this.initializeUser(
1321
+ options ? options.anonymousIdOptions : undefined,
1322
+ options ? options.userIdOptions : undefined,
1323
+ );
1324
+ this.setInitialPageProperties();
1325
+
1326
+ this.destSDKBaseURL = getIntegrationsCDNPath(
1327
+ this.version,
1328
+ this.lockIntegrationsVersion,
1329
+ options && options.destSDKBaseURL,
1330
+ );
1331
+
1332
+ if (options && options.getSourceConfig) {
1333
+ if (typeof options.getSourceConfig !== 'function') {
1334
+ handleError(new Error('option "getSourceConfig" must be a function'));
1335
+ } else {
1336
+ const res = options.getSourceConfig();
1337
+
1338
+ if (res instanceof Promise) {
1339
+ res.then((pRes) => this.processResponse(200, pRes)).catch(handleError);
1340
+ } else {
1341
+ this.processResponse(200, res);
1342
+ }
1343
+ }
1344
+ return;
1345
+ }
1346
+
1347
+ let configUrl = getConfigUrl(writeKey);
1348
+ if (options && options.configUrl) {
1349
+ configUrl = getUserProvidedConfigUrl(options.configUrl, configUrl);
1350
+ }
1351
+
1352
+ try {
1353
+ getJSONTrimmed(this, configUrl, writeKey, this.processResponse);
1354
+ } catch (error) {
1355
+ handleError(error);
1356
+ }
1357
+ }
1358
+
1359
+ arePolyfillsRequired(options) {
1360
+ // check if the below features are available in the browser or not
1361
+ // If not present dynamically load from the polyfill cdn, unless
1362
+ // the options are configured not to.
1363
+ const polyfillIfRequired =
1364
+ options && typeof options.polyfillIfRequired === 'boolean'
1365
+ ? options.polyfillIfRequired
1366
+ : true;
1367
+ return (
1368
+ polyfillIfRequired &&
1369
+ (!String.prototype.endsWith ||
1370
+ !String.prototype.startsWith ||
1371
+ !String.prototype.includes ||
1372
+ !Array.prototype.find ||
1373
+ !Array.prototype.includes ||
1374
+ typeof window.URL !== 'function' ||
1375
+ typeof Promise === 'undefined' ||
1376
+ !Object.entries ||
1377
+ !Object.values ||
1378
+ !String.prototype.replaceAll ||
1379
+ !this.isDatasetAvailable() ||
1380
+ typeof TextDecoder !== 'function' ||
1381
+ typeof Uint8Array !== 'function')
1382
+ );
1383
+ }
1384
+
1385
+ /**
1386
+ * Call control pane to get client configs
1387
+ *
1388
+ * @param {*} writeKey
1389
+ * @memberof Analytics
1390
+ */
1391
+ load(writeKey, serverUrl, options) {
1392
+ // logger.debug("inside load ");
1393
+ if (this.loaded) return;
1394
+
1395
+ // clone options
1396
+ const clonedOptions = R.clone(options);
1397
+ if (this.arePolyfillsRequired(clonedOptions)) {
1398
+ const id = 'polyfill';
1399
+ ScriptLoader(id, POLYFILL_URL, { skipDatasetAttributes: true });
1400
+ const self = this;
1401
+ const interval = setInterval(() => {
1402
+ // check if the polyfill is loaded
1403
+ // In chrome 83 and below versions ID of a script is not part of window's scope
1404
+ // even though it is loaded and returns false for <window.hasOwnProperty("polyfill")> this.
1405
+ // So, added another checking to fulfill that purpose.
1406
+ if (
1407
+ (window.hasOwnProperty(id) || document.getElementById(id) !== null) &&
1408
+ typeof Promise !== 'undefined'
1409
+ ) {
1410
+ clearInterval(interval);
1411
+ self.loadAfterPolyfill(writeKey, serverUrl, clonedOptions);
1412
+ }
1413
+ }, 100);
1414
+
1415
+ setTimeout(() => {
1416
+ clearInterval(interval);
1417
+ }, MAX_WAIT_FOR_INTEGRATION_LOAD);
1418
+ } else {
1419
+ this.loadAfterPolyfill(writeKey, serverUrl, clonedOptions);
1420
+ }
1421
+ }
1422
+
1423
+ ready(callback) {
1424
+ if (!this.loaded) {
1425
+ this.toBeProcessedArray.push(['ready', callback]);
1426
+ return;
1427
+ }
1428
+ if (typeof callback === 'function') {
1429
+ /**
1430
+ * If integrations are loaded or no integration is available for loading
1431
+ * execute the callback immediately
1432
+ * else push the callbacks to a queue that will be executed after loading completes
1433
+ */
1434
+ if (this.clientIntegrationsReady) {
1435
+ callback();
1436
+ } else {
1437
+ this.readyCallbacks.push(callback);
1438
+ }
1439
+ return;
1440
+ }
1441
+ logger.error('ready callback is not a function');
1442
+ }
1443
+
1444
+ initializeCallbacks() {
1445
+ Object.keys(this.methodToCallbackMapping).forEach((methodName) => {
1446
+ if (this.methodToCallbackMapping.hasOwnProperty(methodName)) {
1447
+ this.on(methodName, () => {});
1448
+ }
1449
+ });
1450
+ }
1451
+
1452
+ registerCallbacks(calledFromLoad) {
1453
+ if (!calledFromLoad) {
1454
+ Object.keys(this.methodToCallbackMapping).forEach((methodName) => {
1455
+ if (
1456
+ this.methodToCallbackMapping.hasOwnProperty(methodName) &&
1457
+ window.hightouchevents &&
1458
+ typeof window.hightouchevents[this.methodToCallbackMapping[methodName]] === 'function'
1459
+ ) {
1460
+ this.clientSuppliedCallbacks[methodName] =
1461
+ window.hightouchevents[this.methodToCallbackMapping[methodName]];
1462
+ }
1463
+ // let callback =
1464
+ // ? typeof window.hightouchevents[
1465
+ // this.methodToCallbackMapping[methodName]
1466
+ // ] == "function"
1467
+ // ? window.hightouchevents[this.methodToCallbackMapping[methodName]]
1468
+ // : () => {}
1469
+ // : () => {};
1470
+
1471
+ // logger.debug("registerCallbacks", methodName, callback);
1472
+
1473
+ // this.on(methodName, callback);
1474
+ });
1475
+ }
1476
+
1477
+ Object.keys(this.clientSuppliedCallbacks).forEach((methodName) => {
1478
+ if (this.clientSuppliedCallbacks.hasOwnProperty(methodName)) {
1479
+ // logger.debug(
1480
+ // "registerCallbacks",
1481
+ // methodName,
1482
+ // this.clientSuppliedCallbacks[methodName]
1483
+ // );
1484
+ this.on(methodName, this.clientSuppliedCallbacks[methodName]);
1485
+ }
1486
+ });
1487
+ }
1488
+
1489
+ sendSampleRequest() {
1490
+ ScriptLoader('ad-block', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', {
1491
+ isNonNativeSDK: true,
1492
+ });
1493
+ }
1494
+
1495
+ /**
1496
+ * A public method to start a session
1497
+ * @param {string} sessionId session identifier
1498
+ * @returns
1499
+ */
1500
+ startSession(sessionId) {
1501
+ this.uSession.start(sessionId);
1502
+ }
1503
+
1504
+ /**
1505
+ * A public method to end an ongoing session.
1506
+ */
1507
+ endSession() {
1508
+ this.uSession.end();
1509
+ }
1510
+
1511
+ setAuthToken(token) {
1512
+ if (typeof token !== 'string') {
1513
+ logger.error('Provided input should be in string format');
1514
+ return;
1515
+ }
1516
+ this.storage.setAuthToken(token);
1517
+ this.transformationHandler.setAuthToken(token);
1518
+ }
1519
+ }
1520
+
1521
+ const instance = new Analytics();
1522
+
1523
+ function processDataInAnalyticsArray(analytics) {
1524
+ if (analytics.toBeProcessedArray.length > 0) {
1525
+ while (analytics.toBeProcessedArray.length > 0) {
1526
+ const event = [...analytics.toBeProcessedArray[0]];
1527
+
1528
+ // remove the element from the queue
1529
+ analytics.toBeProcessedArray.shift();
1530
+
1531
+ const method = event[0];
1532
+ event.shift();
1533
+ // logger.debug("=====from analytics array, calling method:: ", method)
1534
+ analytics[method](...event);
1535
+ }
1536
+ }
1537
+ }
1538
+
1539
+ /**
1540
+ * parse the given url into usable Rudder object
1541
+ * @param {*} url
1542
+ */
1543
+ function retrieveEventsFromQueryString(url) {
1544
+ const queryDefaults = {
1545
+ trait: 'ajs_trait_',
1546
+ prop: 'ajs_prop_',
1547
+ };
1548
+
1549
+ function getDataFromQueryObj(qObj, dataType) {
1550
+ const data = {};
1551
+ Object.keys(qObj).forEach((key) => {
1552
+ if (key.startsWith(dataType)) {
1553
+ data[key.substr(dataType.length)] = qObj[key];
1554
+ }
1555
+ });
1556
+ return data;
1557
+ }
1558
+
1559
+ const queryObject = parseQueryString(url);
1560
+ if (queryObject.ajs_aid) {
1561
+ instance.toBeProcessedArray.push(['setAnonymousId', queryObject.ajs_aid]);
1562
+ }
1563
+
1564
+ if (queryObject.ajs_uid) {
1565
+ instance.toBeProcessedArray.push([
1566
+ 'identify',
1567
+ queryObject.ajs_uid,
1568
+ getDataFromQueryObj(queryObject, queryDefaults.trait),
1569
+ ]);
1570
+ }
1571
+
1572
+ if (queryObject.ajs_event) {
1573
+ instance.toBeProcessedArray.push([
1574
+ 'track',
1575
+ queryObject.ajs_event,
1576
+ getDataFromQueryObj(queryObject, queryDefaults.prop),
1577
+ ]);
1578
+ }
1579
+ }
1580
+
1581
+ Emitter(instance);
1582
+
1583
+ window.addEventListener(
1584
+ 'error',
1585
+ (e) => {
1586
+ handleError(e, undefined, instance);
1587
+ },
1588
+ true,
1589
+ );
1590
+
1591
+ // initialize supported callbacks
1592
+ instance.initializeCallbacks();
1593
+
1594
+ // register supported callbacks
1595
+ instance.registerCallbacks(false);
1596
+
1597
+ const defaultMethod = 'load';
1598
+ const argumentsArray = window.hightouchevents;
1599
+ const isValidArgsArray = Array.isArray(argumentsArray);
1600
+ let defaultEvent;
1601
+ if (isValidArgsArray) {
1602
+ /**
1603
+ * Iterate the buffered API calls until we find load call and
1604
+ * queue it first for processing
1605
+ */
1606
+ let i = 0;
1607
+ while (i < argumentsArray.length) {
1608
+ if (argumentsArray[i] && argumentsArray[i][0] === defaultMethod) {
1609
+ defaultEvent = argumentsArray[i];
1610
+ argumentsArray.splice(i, 1);
1611
+ break;
1612
+ }
1613
+ i += 1;
1614
+ }
1615
+ }
1616
+
1617
+ // parse querystring of the page url to send events
1618
+ retrieveEventsFromQueryString(window.location.href);
1619
+
1620
+ if (isValidArgsArray) argumentsArray.forEach((x) => instance.toBeProcessedArray.push(x));
1621
+
1622
+ // Process load method if present in the buffered requests
1623
+ if (defaultEvent && defaultEvent.length > 0) {
1624
+ defaultEvent.shift();
1625
+ instance[defaultMethod](...defaultEvent);
1626
+ }
1627
+
1628
+ const ready = instance.ready.bind(instance);
1629
+ const identify = instance.identify.bind(instance);
1630
+ const page = instance.page.bind(instance);
1631
+ const track = instance.track.bind(instance);
1632
+ const alias = instance.alias.bind(instance);
1633
+ const group = instance.group.bind(instance);
1634
+ const reset = instance.reset.bind(instance);
1635
+ const load = instance.load.bind(instance);
1636
+ const initialized = (instance.initialized = true);
1637
+ const getUserId = instance.getUserId.bind(instance);
1638
+ const getSessionId = instance.getSessionId.bind(instance);
1639
+ const getUserTraits = instance.getUserTraits.bind(instance);
1640
+ const getAnonymousId = instance.getAnonymousId.bind(instance);
1641
+ const setAnonymousId = instance.setAnonymousId.bind(instance);
1642
+ const getGroupId = instance.getGroupId.bind(instance);
1643
+ const getGroupTraits = instance.getGroupTraits.bind(instance);
1644
+ const startSession = instance.startSession.bind(instance);
1645
+ const endSession = instance.endSession.bind(instance);
1646
+ const setAuthToken = instance.setAuthToken.bind(instance);
1647
+
1648
+ export {
1649
+ initialized,
1650
+ ready,
1651
+ page,
1652
+ track,
1653
+ load,
1654
+ identify,
1655
+ reset,
1656
+ alias,
1657
+ group,
1658
+ getUserId,
1659
+ getSessionId,
1660
+ getUserTraits,
1661
+ getAnonymousId,
1662
+ setAnonymousId,
1663
+ getGroupId,
1664
+ getGroupTraits,
1665
+ startSession,
1666
+ endSession,
1667
+ setAuthToken,
1668
+ };