@deriv-com/analytics 1.38.7 → 1.38.9

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 (77) hide show
  1. package/README.md +38 -8
  2. package/dist/browser/analytics.bundle.global.js +12 -12
  3. package/dist/browser/analytics.bundle.global.js.map +1 -1
  4. package/dist/browser/analytics.esm.mjs +1 -7
  5. package/dist/browser/analytics.esm.mjs.map +1 -1
  6. package/dist/chunk-7CT4XR74.mjs +3 -0
  7. package/dist/chunk-7CT4XR74.mjs.map +1 -0
  8. package/dist/chunk-BVGYK54Z.js +4 -0
  9. package/dist/chunk-BVGYK54Z.js.map +1 -0
  10. package/dist/chunk-D2MKQCJB.mjs +3 -0
  11. package/dist/chunk-D2MKQCJB.mjs.map +1 -0
  12. package/dist/chunk-FE5YWK6A.js +3 -0
  13. package/dist/chunk-FE5YWK6A.js.map +1 -0
  14. package/dist/chunk-ID2GN2PS.mjs +4 -0
  15. package/dist/chunk-ID2GN2PS.mjs.map +1 -0
  16. package/dist/chunk-ILN7DKKL.js +3 -0
  17. package/dist/chunk-ILN7DKKL.js.map +1 -0
  18. package/dist/chunk-OB6HH25Z.mjs +9 -0
  19. package/dist/chunk-OB6HH25Z.mjs.map +1 -0
  20. package/dist/chunk-YGU4ZMIH.mjs +14 -0
  21. package/dist/chunk-YGU4ZMIH.mjs.map +1 -0
  22. package/dist/growthbook-3K6VUME4.mjs +3 -0
  23. package/dist/growthbook-3K6VUME4.mjs.map +1 -0
  24. package/dist/index.d.mts +9 -5
  25. package/dist/index.d.ts +9 -5
  26. package/dist/index.js +2 -3
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +2 -3
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/metafile-cjs.json +1 -1
  31. package/dist/metafile-esm.json +1 -1
  32. package/dist/metafile-iife.json +1 -1
  33. package/dist/posthog-ANAV4RFJ.mjs +6 -0
  34. package/dist/posthog-ANAV4RFJ.mjs.map +1 -0
  35. package/dist/{posthog-lAeI7PhD.d.mts → posthog-Ds4g1sJf.d.mts} +21 -6
  36. package/dist/{posthog-DV6iayrn.d.ts → posthog-DvDj4azD.d.ts} +21 -6
  37. package/dist/providers/growthbook/index.d.mts +5 -3
  38. package/dist/providers/growthbook/index.d.ts +5 -3
  39. package/dist/providers/growthbook/index.js +2 -2
  40. package/dist/providers/growthbook/index.js.map +1 -1
  41. package/dist/providers/growthbook/index.mjs +2 -2
  42. package/dist/providers/growthbook/index.mjs.map +1 -1
  43. package/dist/providers/posthog/index.d.mts +1 -1
  44. package/dist/providers/posthog/index.d.ts +1 -1
  45. package/dist/providers/posthog/index.js +2 -2
  46. package/dist/providers/posthog/index.js.map +1 -1
  47. package/dist/providers/posthog/index.mjs +2 -2
  48. package/dist/providers/posthog/index.mjs.map +1 -1
  49. package/dist/providers/rudderstack/index.d.mts +5 -2
  50. package/dist/providers/rudderstack/index.d.ts +5 -2
  51. package/dist/providers/rudderstack/index.js +1 -1
  52. package/dist/providers/rudderstack/index.mjs +1 -1
  53. package/dist/utils/analytics-cache/index.d.mts +14 -5
  54. package/dist/utils/analytics-cache/index.d.ts +14 -5
  55. package/dist/utils/analytics-cache/index.js +1 -1
  56. package/dist/utils/analytics-cache/index.mjs +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunk-3LFZFQL4.mjs +0 -3
  59. package/dist/chunk-3LFZFQL4.mjs.map +0 -1
  60. package/dist/chunk-CAKVOFLO.js +0 -3
  61. package/dist/chunk-CAKVOFLO.js.map +0 -1
  62. package/dist/chunk-DNCZM4KN.mjs +0 -4
  63. package/dist/chunk-DNCZM4KN.mjs.map +0 -1
  64. package/dist/chunk-EMF3RT6E.mjs +0 -14
  65. package/dist/chunk-EMF3RT6E.mjs.map +0 -1
  66. package/dist/chunk-HQX3Z7PF.mjs +0 -3
  67. package/dist/chunk-HQX3Z7PF.mjs.map +0 -1
  68. package/dist/chunk-LKLVBL24.js +0 -3
  69. package/dist/chunk-LKLVBL24.js.map +0 -1
  70. package/dist/chunk-NOEKD4DT.js +0 -4
  71. package/dist/chunk-NOEKD4DT.js.map +0 -1
  72. package/dist/chunk-UDVSKE3Y.mjs +0 -3
  73. package/dist/chunk-UDVSKE3Y.mjs.map +0 -1
  74. package/dist/growthbook-NJGOOJH4.mjs +0 -3
  75. package/dist/growthbook-NJGOOJH4.mjs.map +0 -1
  76. package/dist/posthog-ZJSIYY5Q.mjs +0 -6
  77. package/dist/posthog-ZJSIYY5Q.mjs.map +0 -1
@@ -1,7 +1,3 @@
1
- /**
2
- * Analytics Cache Manager - Version 1.1.0
3
- * Enhanced TypeScript implementation with better type safety and SSR support
4
- */
5
1
  type CachedEvent = {
6
2
  name: string;
7
3
  properties: Record<string, any>;
@@ -42,6 +38,9 @@ declare class AnalyticsCacheManager {
42
38
  private responses;
43
39
  private isTrackingResponses;
44
40
  private delegatedSelectors;
41
+ private debug;
42
+ private log;
43
+ setDebug(debug: boolean): void;
45
44
  /**
46
45
  * FNV-1a hash algorithm for creating consistent hashes
47
46
  */
@@ -58,12 +57,22 @@ declare class AnalyticsCacheManager {
58
57
  * Track XMLHttpRequest responses to monitor analytics calls
59
58
  */
60
59
  trackResponses(): void;
60
+ /**
61
+ * Resolve the analytics instance from the window object.
62
+ * Supports three usage patterns:
63
+ * - NPM import: analytics.ts sets window.AnalyticsInstance directly
64
+ * - IIFE bundle: tsup sets window.DerivAnalytics = { Analytics, cacheTrackEvents }
65
+ * - Legacy: consumers that explicitly set window.Analytics = window.DerivAnalytics
66
+ */
67
+ private getAnalyticsInstance;
61
68
  /**
62
69
  * Check if Analytics instance is ready
63
70
  */
64
71
  isReady(): boolean;
65
72
  /**
66
- * Parse cookies into an object
73
+ * Parse cookies to find a specific cookie by name.
74
+ * Uses an early-exit linear scan instead of building a full map,
75
+ * which is significantly faster when there are many cookies.
67
76
  */
68
77
  private parseCookies;
69
78
  /**
@@ -1,7 +1,3 @@
1
- /**
2
- * Analytics Cache Manager - Version 1.1.0
3
- * Enhanced TypeScript implementation with better type safety and SSR support
4
- */
5
1
  type CachedEvent = {
6
2
  name: string;
7
3
  properties: Record<string, any>;
@@ -42,6 +38,9 @@ declare class AnalyticsCacheManager {
42
38
  private responses;
43
39
  private isTrackingResponses;
44
40
  private delegatedSelectors;
41
+ private debug;
42
+ private log;
43
+ setDebug(debug: boolean): void;
45
44
  /**
46
45
  * FNV-1a hash algorithm for creating consistent hashes
47
46
  */
@@ -58,12 +57,22 @@ declare class AnalyticsCacheManager {
58
57
  * Track XMLHttpRequest responses to monitor analytics calls
59
58
  */
60
59
  trackResponses(): void;
60
+ /**
61
+ * Resolve the analytics instance from the window object.
62
+ * Supports three usage patterns:
63
+ * - NPM import: analytics.ts sets window.AnalyticsInstance directly
64
+ * - IIFE bundle: tsup sets window.DerivAnalytics = { Analytics, cacheTrackEvents }
65
+ * - Legacy: consumers that explicitly set window.Analytics = window.DerivAnalytics
66
+ */
67
+ private getAnalyticsInstance;
61
68
  /**
62
69
  * Check if Analytics instance is ready
63
70
  */
64
71
  isReady(): boolean;
65
72
  /**
66
- * Parse cookies into an object
73
+ * Parse cookies to find a specific cookie by name.
74
+ * Uses an early-exit linear scan instead of building a full map,
75
+ * which is significantly faster when there are many cookies.
67
76
  */
68
77
  private parseCookies;
69
78
  /**
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkLKLVBL24_js=require('../../chunk-LKLVBL24.js');Object.defineProperty(exports,"cacheTrackEvents",{enumerable:true,get:function(){return chunkLKLVBL24_js.a}});//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunkFE5YWK6A_js=require('../../chunk-FE5YWK6A.js');require('../../chunk-BVGYK54Z.js');Object.defineProperty(exports,"cacheTrackEvents",{enumerable:true,get:function(){return chunkFE5YWK6A_js.a}});//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{a as cacheTrackEvents}from'../../chunk-3LFZFQL4.mjs';//# sourceMappingURL=index.mjs.map
1
+ export{a as cacheTrackEvents}from'../../chunk-7CT4XR74.mjs';import'../../chunk-ID2GN2PS.mjs';//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deriv-com/analytics",
3
- "version": "1.38.7",
3
+ "version": "1.38.9",
4
4
  "description": "Comprehensive analytics package for Deriv applications. Provides unified event tracking, A/B testing, and user analytics through RudderStack, PostHog and GrowthBook integrations with built-in caching and offline support.",
5
5
  "keywords": [
6
6
  "rudderstack",
@@ -1,3 +0,0 @@
1
- /* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var p=class{constructor(){this.interval=null;this.responses=[];this.isTrackingResponses=false;this.delegatedSelectors=new Set;this.addEventhandler=this.addEventHandler.bind(this);}hash(e,n=32){let t=r=>{let o=2166136261;for(let c=0;c<r.length;c++)o^=r.charCodeAt(c),o=o*16777619>>>0;return o.toString(16)},s=r=>btoa(r),a=t(e),i=s(a);for(;i.length<n;)i+=s(t(i));return i.substring(0,n)}getCookies(e){let t=`; ${document.cookie}`.split(`; ${e}=`);if(t.length===2){let s=decodeURIComponent(t.pop().split(";").shift());try{return JSON.parse(s)}catch{return s}}return null}trackPageUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.isPageViewSent()||this.push("cached_analytics_page_views",{name:window.location.href,properties:{url:window.location.href}});});}trackResponses(){if(typeof window>"u"||typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,s){return this._url=s,this._method=t,e.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){return this.addEventListener("load",function(){let s=null;if(typeof t=="string")try{s=JSON.parse(t);}catch{s=t;}let a={url:this._url,method:this._method,status:this.status,headers:this.getAllResponseHeaders(),data:this.responseText,payload:s};f.responses.push(a);}),n.apply(this,arguments)},this.isTrackingResponses=true;}isReady(){if(typeof window>"u")return false;let e=window.Analytics;return typeof e>"u"||e===null?false:!!e.Analytics?.getInstances?.()?.tracking}parseCookies(e){if(typeof document>"u")return null;let n=document.cookie.split("; ").reduce((t,s)=>{let[a,i]=s.split("=");return a&&i&&(t[decodeURIComponent(a)]=decodeURIComponent(i)),t},{});try{return n[e]?JSON.parse(n[e]):null}catch{return null}}isPageViewSent(){return !!this.responses.find(e=>e.payload?.type==="page"&&e.payload?.anonymousId)}set(e){this.push("cached_analytics_events",e);}push(e,n){if(typeof document>"u")return;let t=[],s=this.parseCookies(e);s&&Array.isArray(s)&&(t=s),t.push(n);let a=this.getAllowedDomain(),i=365*24*60*60,r=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; Domain=${a}; max-age=${i}; SameSite=Lax`;document.cookie=r;}getAllowedDomain(){if(typeof window>"u")return "";let e=window.location.hostname;if(e==="localhost"||/^\d+\.\d+\.\d+\.\d+$/.test(e))return e;let n=e.split(".");return n.length===1?e:`.${n.slice(-2).join(".")}`}processEvent(e){let n=this.getCookies("client_information");if(n){let{email:t=null}=n;t&&(e.properties.email_hash=this.hash(t));}if(e?.properties?.email){let t=e.properties.email;delete e.properties.email,e.properties.email_hash=this.hash(t);}return e}track(e,n=false){if(typeof window>"u")return;let t=this.processEvent(e),s=window.Analytics;this.isReady()&&!n?s.Analytics.trackEvent(t.name,t.properties):this.set(t);}pageView(){typeof window>"u"||(this.isTrackingResponses||(this.trackResponses(),this.trackPageUnload()),this.interval=setInterval(()=>{let e=window.Analytics;typeof e<"u"&&typeof e.Analytics?.pageView=="function"&&this.isReady()&&e.Analytics.pageView(window.location.href,"Trader's hub"),this.isPageViewSent()&&this.interval&&clearInterval(this.interval);},1e3));}listen(e,{name:n="",properties:t={}},s=false,a=null){let i=o=>{o.dataset?.clickEventTracking||(o.addEventListener("click",c=>{let l={name:n,properties:t,cache:s};if(typeof a=="function"){let d=a(c);l={...d,cache:d.cache??s};}this.track(l,l.cache??false);}),o.dataset.clickEventTracking="true");};(e instanceof NodeList?Array.from(e):[e]).forEach(i);}addEventHandler(e){return typeof window>"u"?this:(e.forEach(({element:n,event:t={name:"",properties:{}},cache:s=false,callback:a=null})=>{if(typeof n=="string"){let i=n;if(!this.delegatedSelectors.has(i)){let r=o=>{let c=o.target;if(!c)return;let l=c.closest(i);if(l&&!l.dataset?.clickEventTracking){let d={name:t.name,properties:t.properties,cache:s};if(typeof a=="function"){let h=a(o);d={...h,cache:h.cache??s};}l.dataset.clickEventTracking="true",this.track(d,d.cache??false);}};document.addEventListener("click",r),this.delegatedSelectors.add(i);}}else (n instanceof NodeList?Array.from(n):[n]).forEach(r=>{r&&!r.dataset?.clickEventTracking&&this.listen(r,t,s,a);});}),this)}loadEvent(e){return e.forEach(({event:n})=>{let{name:t,properties:s}=n;this.track({name:t,properties:s});}),this}pageLoadEvent(e){if(typeof window>"u")return this;let n=window.location.pathname.slice(1);return e.forEach(({pages:t=[],excludedPages:s=[],event:a,callback:i=null})=>{let r=false;if(t.length?t.includes(n)&&(r=true):s.length&&s.includes(n)||(r=true),r){let o=i?i():a;this.loadEvent([{event:o}]);}}),this}clearInterval(){this.interval&&(clearInterval(this.interval),this.interval=null);}cleanup(){this.clearInterval(),this.responses=[],this.isTrackingResponses=false;}},f=new p;typeof window<"u"&&(window.cacheTrackEvents=f);export{f as a};//# sourceMappingURL=chunk-3LFZFQL4.mjs.map
3
- //# sourceMappingURL=chunk-3LFZFQL4.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/analytics-cache.ts"],"names":["AnalyticsCacheManager","inputString","desiredLength","fnv1aHash","string","hash","i","base64Encode","combined","name","parts","cookieValue","originalXhrOpen","originalXhrSend","method","url","body","parsedPayload","responseData","cacheTrackEvents","Analytics","cookieName","cookies","acc","cookie","key","value","event","data","storedCookies","cacheCookie","domain","maxAge","cookieString","hostname","clientInfo","email","originalEvent","cache","element","properties","callback","addClickListener","el","e","callbackResult","items","selector","delegatedHandler","target","matched","evt","pathname","pages","excludedPages","dispatch","eventData"],"mappings":";AA8CA,IAAMA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AAAA,CAAW,MAAA,CAAO,QAAA,CAAS,QAAA,CAAS,KAAA,CAAM,CAAC,CAAA,CACjD,OAAAN,CAAAA,CAAM,OAAA,CAAQ,CAAC,CAAE,KAAA,CAAAO,CAAAA,CAAQ,EAAC,CAAG,aAAA,CAAAC,CAAAA,CAAgB,EAAC,CAAG,KAAA,CAAA3B,CAAAA,CAAO,QAAA,CAAAc,CAAAA,CAAW,IAAK,CAAA,GAAM,CAC1E,IAAIc,CAAAA,CAAW,KAAA,CAaf,GAZIF,CAAAA,CAAM,MAAA,CACFA,CAAAA,CAAM,QAAA,CAASD,CAAQ,IACvBG,CAAAA,CAAW,IAAA,CAAA,CAERD,CAAAA,CAAc,MAAA,EAChBA,CAAAA,CAAc,QAAA,CAASF,CAAQ,CAAA,GAChCG,CAAAA,CAAW,IAAA,CAAA,CAMfA,CAAAA,CAAU,CACV,IAAMC,CAAAA,CAAYf,CAAAA,CAAWA,CAAAA,EAAS,CAAId,CAAAA,CAC1C,IAAA,CAAK,SAAA,CAAU,CAAC,CAAE,KAAA,CAAO6B,CAAU,CAAC,CAAC,EACzC,CACJ,CAAC,CAAA,CAEM,IACX,CAKA,aAAA,EAAsB,CACd,IAAA,CAAK,QAAA,GACL,aAAA,CAAc,IAAA,CAAK,QAAQ,CAAA,CAC3B,IAAA,CAAK,QAAA,CAAW,IAAA,EAExB,CAKA,OAAA,EAAgB,CACZ,IAAA,CAAK,aAAA,EAAc,CACnB,IAAA,CAAK,SAAA,CAAY,EAAC,CAClB,IAAA,CAAK,mBAAA,CAAsB,MAC/B,CACJ,CAAA,CAGarC,CAAAA,CAAmB,IAAInB,EAGhC,OAAO,MAAA,CAAW,GAAA,GAChB,OAAe,gBAAA,CAAmBmB,CAAAA,CAAAA","file":"chunk-3LFZFQL4.mjs","sourcesContent":["/**\n * Analytics Cache Manager - Version 1.1.0\n * Enhanced TypeScript implementation with better type safety and SSR support\n */\n\ntype CachedEvent = {\n name: string\n properties: Record<string, any>\n}\n\ntype ResponseData = {\n url: string\n method: string\n status: number\n headers: string\n data: string\n payload: any\n}\n\ntype EventListenerConfig = {\n element: Element | NodeList | string\n event: {\n name: string\n properties: Record<string, any>\n }\n cache?: boolean\n callback?: (e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }\n}\n\ntype LoadEventConfig = {\n event: {\n name: string\n properties: Record<string, any>\n }\n}\n\ntype PageLoadEventConfig = {\n pages?: string[]\n excludedPages?: string[]\n event: {\n name: string\n properties: Record<string, any>\n }\n callback?: () => { name: string; properties: Record<string, any> }\n}\n\nclass AnalyticsCacheManager {\n private interval: NodeJS.Timeout | null = null\n private responses: ResponseData[] = []\n private isTrackingResponses = false\n private delegatedSelectors: Set<string> = new Set()\n\n /**\n * FNV-1a hash algorithm for creating consistent hashes\n */\n private hash(inputString: string, desiredLength = 32): string {\n const fnv1aHash = (string: string): string => {\n let hash = 0x811c9dc5\n for (let i = 0; i < string.length; i++) {\n hash ^= string.charCodeAt(i)\n hash = (hash * 0x01000193) >>> 0\n }\n return hash.toString(16)\n }\n\n const base64Encode = (string: string): string => btoa(string)\n\n let hash = fnv1aHash(inputString)\n let combined = base64Encode(hash)\n\n while (combined.length < desiredLength) {\n combined += base64Encode(fnv1aHash(combined))\n }\n\n return combined.substring(0, desiredLength)\n }\n\n /**\n * Get cookie value by name\n */\n getCookies(name: string): any {\n const value = `; ${document.cookie}`\n const parts = value.split(`; ${name}=`)\n if (parts.length === 2) {\n const cookieValue = decodeURIComponent(parts.pop()!.split(';').shift()!)\n\n try {\n return JSON.parse(cookieValue)\n } catch (e) {\n return cookieValue\n }\n }\n return null\n }\n\n /**\n * Track page unload events to cache pageviews before leaving\n */\n trackPageUnload(): void {\n if (typeof window === 'undefined') return\n\n window.addEventListener('beforeunload', () => {\n if (!this.isPageViewSent()) {\n this.push('cached_analytics_page_views', {\n name: window.location.href,\n properties: {\n url: window.location.href,\n },\n })\n }\n })\n }\n\n /**\n * Track XMLHttpRequest responses to monitor analytics calls\n */\n trackResponses(): void {\n if (typeof window === 'undefined' || typeof XMLHttpRequest === 'undefined') return\n\n const originalXhrOpen = XMLHttpRequest.prototype.open\n const originalXhrSend = XMLHttpRequest.prototype.send\n\n XMLHttpRequest.prototype.open = function (method: string, url: string | URL) {\n ;(this as any)._url = url\n ;(this as any)._method = method\n return originalXhrOpen.apply(this, arguments as any)\n }\n\n XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null) {\n this.addEventListener('load', function () {\n let parsedPayload = null\n\n if (typeof body === 'string') {\n try {\n parsedPayload = JSON.parse(body)\n } catch (e) {\n parsedPayload = body\n }\n }\n\n const responseData: ResponseData = {\n url: (this as any)._url,\n method: (this as any)._method,\n status: this.status,\n headers: this.getAllResponseHeaders(),\n data: this.responseText,\n payload: parsedPayload,\n }\n cacheTrackEvents.responses.push(responseData)\n })\n\n return originalXhrSend.apply(this, arguments as any)\n }\n\n this.isTrackingResponses = true\n }\n\n /**\n * Check if Analytics instance is ready\n */\n isReady(): boolean {\n if (typeof window === 'undefined') return false\n\n const Analytics = (window as any).Analytics\n if (typeof Analytics === 'undefined' || Analytics === null) {\n return false\n }\n\n const instances = Analytics.Analytics?.getInstances?.()\n return !!instances?.tracking\n }\n\n /**\n * Parse cookies into an object\n */\n private parseCookies(cookieName: string): any {\n if (typeof document === 'undefined') return null\n\n const cookies = document.cookie.split('; ').reduce((acc: Record<string, string>, cookie) => {\n const [key, value] = cookie.split('=')\n if (key && value) {\n acc[decodeURIComponent(key)] = decodeURIComponent(value)\n }\n return acc\n }, {})\n\n try {\n return cookies[cookieName] ? JSON.parse(cookies[cookieName]) : null\n } catch (error) {\n return null\n }\n }\n\n /**\n * Check if pageview has been sent\n */\n isPageViewSent(): boolean {\n return !!this.responses.find(e => e.payload?.type === 'page' && e.payload?.anonymousId)\n }\n\n /**\n * Set a cached event\n */\n set(event: CachedEvent): void {\n this.push('cached_analytics_events', event)\n }\n\n /**\n * Push data to cookie cache\n */\n push(cookieName: string, data: any): void {\n if (typeof document === 'undefined') return\n\n let storedCookies: any[] = []\n const cacheCookie = this.parseCookies(cookieName)\n if (cacheCookie && Array.isArray(cacheCookie)) {\n storedCookies = cacheCookie\n }\n\n storedCookies.push(data)\n\n const domain = this.getAllowedDomain()\n const maxAge = 365 * 24 * 60 * 60 // 1 year\n const cookieString = `${cookieName}=${encodeURIComponent(JSON.stringify(storedCookies))}; path=/; Domain=${domain}; max-age=${maxAge}; SameSite=Lax`\n\n document.cookie = cookieString\n }\n\n /**\n * Get the allowed domain for cookies\n * For localhost/single-part domains: use as-is\n * For multi-part domains: use top-level domain (e.g., .deriv.com)\n */\n private getAllowedDomain(): string {\n if (typeof window === 'undefined') return ''\n\n const hostname = window.location.hostname\n\n // Handle IP addresses and localhost\n if (hostname === 'localhost' || /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(hostname)) {\n return hostname\n }\n\n const parts = hostname.split('.')\n\n // Single part domain (e.g., \"localhost\")\n if (parts.length === 1) {\n return hostname\n }\n\n // Use top-level domain for proper subdomain sharing\n return `.${parts.slice(-2).join('.')}`\n }\n\n /**\n * Process event to hash email and add client info\n */\n processEvent(event: CachedEvent): CachedEvent {\n const clientInfo = this.getCookies('client_information')\n\n if (clientInfo) {\n const { email = null } = clientInfo\n\n if (email) {\n event.properties.email_hash = this.hash(email)\n }\n }\n\n if (event?.properties?.email) {\n const email = event.properties.email\n delete event.properties.email\n event.properties.email_hash = this.hash(email)\n }\n\n return event\n }\n\n /**\n * Track an event (either immediately or cache it)\n */\n track(originalEvent: CachedEvent, cache = false): void {\n if (typeof window === 'undefined') return\n\n const event = this.processEvent(originalEvent)\n const Analytics = (window as any).Analytics\n\n if (this.isReady() && !cache) {\n Analytics.Analytics.trackEvent(event.name, event.properties)\n } else {\n this.set(event)\n }\n }\n\n /**\n * Track pageview with auto-retry until sent\n */\n pageView(): void {\n if (typeof window === 'undefined') return\n\n if (!this.isTrackingResponses) {\n this.trackResponses()\n this.trackPageUnload()\n }\n\n this.interval = setInterval(() => {\n const Analytics = (window as any).Analytics\n\n if (\n typeof Analytics !== 'undefined' &&\n typeof Analytics.Analytics?.pageView === 'function' &&\n this.isReady()\n ) {\n Analytics.Analytics.pageView(window.location.href, \"Trader's hub\")\n }\n\n if (this.isPageViewSent()) {\n if (this.interval) clearInterval(this.interval)\n }\n }, 1000)\n }\n\n /**\n * Add click event listener to element(s)\n */\n listen(\n element: Element | NodeList,\n { name = '', properties = {} }: { name: string; properties: Record<string, any> },\n cache = false,\n callback: ((e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }) | null = null\n ): void {\n const addClickListener = (el: Element) => {\n if (!(el as any).dataset?.clickEventTracking) {\n el.addEventListener('click', (e: Event) => {\n let event = {\n name,\n properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n event = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n this.track(event, event.cache ?? false)\n })\n ;(el as any).dataset.clickEventTracking = 'true'\n }\n }\n\n const elements = element instanceof NodeList ? Array.from(element as NodeListOf<Element>) : [element]\n elements.forEach(addClickListener)\n }\n\n /**\n * Add event handlers to multiple elements with auto-retry\n * Alias for backward compatibility with typo\n */\n addEventHandler(items: EventListenerConfig[]): this {\n if (typeof window === 'undefined') return this\n\n items.forEach(({ element, event = { name: '', properties: {} }, cache = false, callback = null }) => {\n // If a selector string is provided, use event delegation on document\n if (typeof element === 'string') {\n const selector = element\n\n if (!this.delegatedSelectors.has(selector)) {\n const delegatedHandler = (e: Event) => {\n const target = e.target as Element | null\n if (!target) return\n\n const matched = target.closest(selector)\n if (matched && !(matched as any).dataset?.clickEventTracking) {\n let evt: any = {\n name: event.name,\n properties: event.properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n evt = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n ;(matched as any).dataset.clickEventTracking = 'true'\n this.track(evt, evt.cache ?? false)\n }\n }\n\n document.addEventListener('click', delegatedHandler)\n this.delegatedSelectors.add(selector)\n }\n } else {\n // Element or NodeList: attach directly to existing elements\n const elements = element instanceof NodeList ? Array.from(element) : [element]\n\n elements.forEach(el => {\n if (el && !(el as any).dataset?.clickEventTracking) {\n this.listen(el as Element, event, cache, callback)\n }\n })\n }\n })\n\n return this\n }\n\n /**\n * Backward compatibility alias (with typo from original)\n */\n addEventhandler = this.addEventHandler.bind(this)\n\n /**\n * Load events immediately\n */\n loadEvent(items: LoadEventConfig[]): this {\n items.forEach(({ event }) => {\n const { name, properties } = event\n this.track({\n name,\n properties,\n })\n })\n\n return this\n }\n\n /**\n * Load events on specific pages\n */\n pageLoadEvent(items: PageLoadEventConfig[]): this {\n if (typeof window === 'undefined') return this\n\n const pathname = window.location.pathname.slice(1)\n items.forEach(({ pages = [], excludedPages = [], event, callback = null }) => {\n let dispatch = false\n if (pages.length) {\n if (pages.includes(pathname)) {\n dispatch = true\n }\n } else if (excludedPages.length) {\n if (!excludedPages.includes(pathname)) {\n dispatch = true\n }\n } else {\n dispatch = true\n }\n\n if (dispatch) {\n const eventData = callback ? callback() : event\n this.loadEvent([{ event: eventData }])\n }\n })\n\n return this\n }\n\n /**\n * Clear the interval and cleanup\n */\n clearInterval(): void {\n if (this.interval) {\n clearInterval(this.interval)\n this.interval = null\n }\n }\n\n /**\n * Cleanup method for removing event listeners and intervals\n */\n cleanup(): void {\n this.clearInterval()\n this.responses = []\n this.isTrackingResponses = false\n }\n}\n\n// Create singleton instance\nexport const cacheTrackEvents = new AnalyticsCacheManager()\n\n// Export to global scope for backward compatibility\nif (typeof window !== 'undefined') {\n ;(window as any).cacheTrackEvents = cacheTrackEvents\n}\n"]}
@@ -1,3 +0,0 @@
1
- 'use strict';var chunkNOEKD4DT_js=require('./chunk-NOEKD4DT.js'),analyticsJs=require('@rudderstack/analytics-js');/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var k=2*365*24*60*60,n=class n{constructor(t,e){this.analytics=new analyticsJs.RudderAnalytics;this.has_identified=false;this.has_initialized=false;this.current_page="";this.rudderstack_anonymous_cookie_key="rudder_anonymous_id";this.getAnonymousId=()=>document.cookie.match("(^|;)\\s*"+this.rudderstack_anonymous_cookie_key+"\\s*=\\s*([^;]+)")?.pop();this.setCookieIfNotExists=()=>{if(!this.getAnonymousId())try{let e=window.location.hostname,s=["webflow.io"].some(o=>e.endsWith(o))?e:e.split(".").slice(-2).join("."),d;if(crypto?.randomUUID)d=crypto.randomUUID();else if(crypto?.getRandomValues){let o=new Uint8Array(16);crypto.getRandomValues(o),o[6]=o[6]&15|64,o[8]=o[8]&63|128;let r=Array.from(o,h=>h.toString(16).padStart(2,"0")).join("");d=`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`;}else throw new Error("Crypto API not available for secure random UUID generation");let u=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${this.rudderstack_anonymous_cookie_key}=${d}; path=/; Domain=${s}; max-age=${k}; SameSite=Lax${u}`;}catch(e){console.warn("RudderStack: Failed to set anonymous ID cookie",e);}};this.getUserId=()=>this.analytics.getUserId();this.init=t=>{if(!t){console.warn("RudderStack: Initialization skipped - no key provided");return}try{this.setCookieIfNotExists(),this.analytics.load(t,chunkNOEKD4DT_js.c,{externalAnonymousIdCookieName:this.rudderstack_anonymous_cookie_key,lockIntegrationsVersion:!0,onLoaded:()=>{this.has_initialized=!0,this.has_identified=!!this.getUserId(),this.onLoadedCallback?.();}});}catch(e){console.error("RudderStack: Failed to initialize",e);}};this.identifyEvent=(t,e)=>{if(!this.has_initialized){console.warn("RudderStack: Cannot identify - not initialized");return}let i=this.getUserId();if(!i||i!==t)try{this.analytics.identify(t,e||{}),this.has_identified=!0;}catch(a){console.error("RudderStack: Failed to identify user",a);}else this.has_identified=true;};this.pageView=(t,e="Deriv App",i,a)=>{if(!(!this.has_initialized||t===this.current_page))try{let s={...i&&{user_id:i},...a};this.analytics.page(e,t,s),this.current_page=t;}catch(s){console.error("RudderStack: Failed to track page view",s);}};this.reset=()=>{if(this.has_initialized)try{this.analytics.reset(),this.has_identified=!1;}catch(t){console.error("RudderStack: Failed to reset",t);}};this.track=(t,e)=>{if(this.has_initialized)try{this.analytics.track(t,e);}catch(i){console.warn("RudderStack: Failed to track event",i);}};this.onLoadedCallback=e,this.init(t);}};n.getRudderStackInstance=(t,e)=>(n._instance||(n._instance=new n(t,e)),n._instance);var l=n;exports.a=l;//# sourceMappingURL=chunk-CAKVOFLO.js.map
3
- //# sourceMappingURL=chunk-CAKVOFLO.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/rudderstack.ts"],"names":["COOKIE_MAX_AGE_SECONDS","_RudderStack","RUDDERSTACK_KEY","onLoaded","RudderAnalytics","hostname","domain_name","domain","uuid","bytes","hex","byte","secureFlag","error","rudderstackDataplane","user_id","payload","currentUserId","current_page","platform","properties","pageProperties","event","err","RudderStack"],"mappings":";AAKA,IAAMA,CAAAA,CAAyB,EAAI,GAAA,CAAM,EAAA,CAAK,EAAA,CAAK,EAAA,CAMtCC,CAAAA,CAAN,MAAMA,CAAY,CASrB,WAAA,CAAYC,CAAAA,CAAyBC,CAAAA,CAAuB,CAR5D,IAAA,CAAA,SAAA,CAAY,IAAIC,2BAAAA,CAChB,IAAA,CAAA,cAAA,CAAiB,KAAA,CACjB,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,YAAA,CAAe,GACf,IAAA,CAAA,gCAAA,CAAmC,qBAAA,CA0BnC,IAAA,CAAA,cAAA,CAAiB,IACN,QAAA,CAAS,MAAA,CAAO,MAAM,WAAA,CAAc,IAAA,CAAK,gCAAA,CAAmC,kBAAkB,CAAA,EAAG,GAAA,GAO5G,IAAA,CAAA,oBAAA,CAAuB,IAAY,CAG/B,GAAI,CAFiB,IAAA,CAAK,gBAAe,CAGrC,GAAI,CACA,IAAMC,CAAAA,CAAW,MAAA,CAAO,SAAS,QAAA,CAG3BC,CAAAA,CAFmB,CAAC,YAAY,CAAA,CACM,IAAA,CA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IAAA,CAAKD,CAAe,EAC7B,CA0LJ,CAAA,CAtMaD,CAAAA,CAoBK,sBAAA,CAAyB,CAACC,CAAAA,CAAyBC,CAAAA,IACxDF,EAAY,SAAA,GACbA,CAAAA,CAAY,SAAA,CAAY,IAAIA,CAAAA,CAAYC,CAAAA,CAAiBC,CAAQ,CAAA,CAAA,CAE9DF,CAAAA,CAAY,SAAA,CAAA,CAxBpB,IAAMuB,CAAAA,CAANvB","file":"chunk-CAKVOFLO.js","sourcesContent":["import { RudderAnalytics } from '@rudderstack/analytics-js'\nimport type { TCoreAttributes, TAllEvents } from '../types'\nimport { rudderstackDataplane } from '../utils/urls'\n\n// Constants\nconst COOKIE_MAX_AGE_SECONDS = 2 * 365 * 24 * 60 * 60 // 2 years\n\n/**\n * RudderStack analytics wrapper with singleton pattern.\n * Handles user tracking, page views, and event analytics.\n */\nexport class RudderStack {\n analytics = new RudderAnalytics()\n has_identified = false\n has_initialized = false\n current_page = ''\n rudderstack_anonymous_cookie_key = 'rudder_anonymous_id'\n private static _instance: RudderStack\n private onLoadedCallback?: () => void\n\n constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void) {\n this.onLoadedCallback = onLoaded\n this.init(RUDDERSTACK_KEY)\n }\n\n /**\n * Get or create the singleton instance of RudderStack\n * @param RUDDERSTACK_KEY - RudderStack write key\n * @param onLoaded - Optional callback when RudderStack is loaded\n * @returns The RudderStack singleton instance\n */\n public static getRudderStackInstance = (RUDDERSTACK_KEY: string, onLoaded?: () => void): RudderStack => {\n if (!RudderStack._instance) {\n RudderStack._instance = new RudderStack(RUDDERSTACK_KEY, onLoaded)\n }\n return RudderStack._instance\n }\n\n /**\n * Get the anonymous ID from cookies\n * @returns The anonymous ID or undefined if not found\n */\n getAnonymousId = (): string | undefined => {\n return document.cookie.match('(^|;)\\\\s*' + this.rudderstack_anonymous_cookie_key + '\\\\s*=\\\\s*([^;]+)')?.pop()\n }\n\n /**\n * Set anonymous ID cookie if it doesn't exist\n * Creates a secure cookie with proper domain and security attributes\n */\n setCookieIfNotExists = (): void => {\n const anonymous_id = this.getAnonymousId()\n\n if (!anonymous_id) {\n try {\n const hostname = window.location.hostname\n const external_domains = ['webflow.io']\n const is_external_domain = external_domains.some(domain => hostname.endsWith(domain))\n const domain_name = is_external_domain ? hostname : hostname.split('.').slice(-2).join('.')\n\n // Generate cryptographically secure UUID\n let uuid: string\n if (crypto?.randomUUID) {\n uuid = crypto.randomUUID()\n } else if (crypto?.getRandomValues) {\n // Fallback: Generate UUID v4 using crypto.getRandomValues\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n // Set version (4) and variant bits\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n // Convert to UUID string format\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n } else {\n // Crypto API not available - this should not happen in modern browsers\n throw new Error('Crypto API not available for secure random UUID generation')\n }\n\n const isSecure = window.location.protocol === 'https:'\n const secureFlag = isSecure ? '; Secure' : ''\n\n document.cookie = `${this.rudderstack_anonymous_cookie_key}=${uuid}; path=/; Domain=${domain_name}; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secureFlag}`\n } catch (error) {\n console.warn('RudderStack: Failed to set anonymous ID cookie', error)\n }\n }\n }\n\n /**\n * Get the current user ID\n * @returns The user ID, null, or undefined if not identified\n */\n getUserId = () => this.analytics.getUserId()\n\n /**\n * Initialize RudderStack with the provided key\n * @param RUDDERSTACK_KEY - RudderStack write key\n */\n init = (RUDDERSTACK_KEY: string): void => {\n if (!RUDDERSTACK_KEY) {\n console.warn('RudderStack: Initialization skipped - no key provided')\n return\n }\n\n try {\n this.setCookieIfNotExists()\n\n this.analytics.load(RUDDERSTACK_KEY, rudderstackDataplane, {\n externalAnonymousIdCookieName: this.rudderstack_anonymous_cookie_key,\n // Performance optimizations\n lockIntegrationsVersion: true,\n onLoaded: () => {\n this.has_initialized = true\n this.has_identified = !!this.getUserId()\n this.onLoadedCallback?.()\n },\n })\n } catch (error) {\n console.error('RudderStack: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with RudderStack\n * Only identifies if user hasn't been identified yet\n * @param user_id - The user ID to identify\n * @param payload - Optional user traits (e.g., language, custom properties)\n */\n identifyEvent = (user_id: string, payload?: Record<string, any>): void => {\n if (!this.has_initialized) {\n console.warn('RudderStack: Cannot identify - not initialized')\n return\n }\n\n const currentUserId = this.getUserId()\n if (!currentUserId || currentUserId !== user_id) {\n try {\n this.analytics.identify(user_id, payload || {})\n this.has_identified = true\n } catch (error) {\n console.error('RudderStack: Failed to identify user', error)\n }\n } else {\n this.has_identified = true\n }\n }\n\n /**\n * Track a page view event\n * @param current_page - The page name/path\n * @param platform - The platform name (default: 'Deriv App')\n * @param user_id - The user ID\n * @param properties - Additional page properties\n */\n pageView = (\n current_page: string,\n platform = 'Deriv App',\n user_id: string,\n properties?: Record<string, unknown>\n ): void => {\n if (!this.has_initialized || current_page === this.current_page) return\n\n try {\n const pageProperties = {\n ...(user_id && { user_id }),\n ...properties,\n }\n\n // Type assertion needed due to RudderStack's type definitions\n this.analytics.page(platform, current_page, pageProperties as any)\n this.current_page = current_page\n } catch (error) {\n console.error('RudderStack: Failed to track page view', error)\n }\n }\n\n /**\n * Reset the RudderStack instance\n * Clears user identification and resets tracking state\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.analytics.reset()\n this.has_identified = false\n } catch (error) {\n console.error('RudderStack: Failed to reset', error)\n }\n }\n\n /**\n * Track a custom event with payload\n * Payload is pre-cleaned by analytics.ts using cleanObject before being passed here\n * @param event - The event name\n * @param payload - The event payload with core attributes\n */\n track = <T extends keyof TAllEvents>(event: T, payload: TAllEvents[T] & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n // Type assertion needed to match RudderStack's ApiObject type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.analytics.track(event as string, payload as any)\n } catch (err) {\n console.warn('RudderStack: Failed to track event', err)\n }\n }\n}\n"]}
@@ -1,4 +0,0 @@
1
- /* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var s="https://deriv.com/cdn-cgi/trace",c="https://cdn.growthbook.io",n="https://deriv-dataplane.rudderstack.com",d="https://ph.deriv.com",i="https://us.posthog.com",r=["deriv.com","deriv.be","deriv.me","deriv.team","deriv.ae"],a=()=>{if(typeof window>"u")return ".deriv.com";let o=window.location.hostname;if(o==="localhost")return "";let t=r.find(e=>o.includes(e));return t?`.${t}`:".deriv.com"};
3
- export{s as a,c as b,n as c,d,i as e,r as f,a as g};//# sourceMappingURL=chunk-DNCZM4KN.mjs.map
4
- //# sourceMappingURL=chunk-DNCZM4KN.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/urls.ts"],"names":["cloudflareTrace","growthbookApi","rudderstackDataplane","posthogApiHost","posthogUiHost","allowedDomains","getAllowedDomain","hostname","matched","d"],"mappings":";AAAO,IAAMA,CAAAA,CAAkB,iCAAA,CAClBC,CAAAA,CAAgB,2BAAA,CAChBC,CAAAA,CAAuB,0CACvBC,CAAAA,CAAiB,sBAAA,CACjBC,CAAAA,CAAgB,wBAAA,CAEhBC,CAAAA,CAAiB,CAAC,YAAa,UAAA,CAAY,UAAA,CAAY,YAAA,CAAc,UAAU,CAAA,CAE/EC,CAAAA,CAAmB,IAAc,CAC1C,GAAI,OAAO,MAAA,CAAW,GAAA,CAAa,OAAO,aAC1C,IAAMC,CAAAA,CAAW,MAAA,CAAO,QAAA,CAAS,QAAA,CAEjC,GAAIA,IAAa,WAAA,CAAa,OAAO,EAAA,CAErC,IAAMC,CAAAA,CAAUH,CAAAA,CAAe,KAAKI,CAAAA,EAAKF,CAAAA,CAAS,QAAA,CAASE,CAAC,CAAC,CAAA,CAC7D,OAAOD,CAAAA,CAAU,CAAA,CAAA,EAAIA,CAAO,CAAA,CAAA,CAAK,YACrC","file":"chunk-DNCZM4KN.mjs","sourcesContent":["export const cloudflareTrace = 'https://deriv.com/cdn-cgi/trace'\nexport const growthbookApi = 'https://cdn.growthbook.io'\nexport const rudderstackDataplane = 'https://deriv-dataplane.rudderstack.com'\nexport const posthogApiHost = 'https://ph.deriv.com'\nexport const posthogUiHost = 'https://us.posthog.com'\n\nexport const allowedDomains = ['deriv.com', 'deriv.be', 'deriv.me', 'deriv.team', 'deriv.ae'] as const\n\nexport const getAllowedDomain = (): string => {\n if (typeof window === 'undefined') return '.deriv.com'\n const hostname = window.location.hostname\n\n if (hostname === 'localhost') return ''\n\n const matched = allowedDomains.find(d => hostname.includes(d))\n return matched ? `.${matched}` : '.deriv.com'\n}\n"]}
@@ -1,14 +0,0 @@
1
- /* @deriv-com/analytics - Browser ESM Bundle (RudderStack + PostHog) - Built with tsup */
2
- import{a as k}from"./chunk-HQX3Z7PF.mjs";function C(t){return t!=null&&typeof t=="object"&&t["@@functional/placeholder"]===!0}function Z(t){return function e(n){return arguments.length===0||C(n)?e:t.apply(this,arguments)}}function ne(t){return function e(n,s){switch(arguments.length){case 0:return e;case 1:return C(n)?e:Z(function(r){return t(n,r)});default:return C(n)&&C(s)?e:C(n)?Z(function(r){return t(r,s)}):C(s)?Z(function(r){return t(n,r)}):t(n,s)}}}function jt(t){return function e(n,s,r){switch(arguments.length){case 0:return e;case 1:return C(n)?e:ne(function(i,a){return t(n,i,a)});case 2:return C(n)&&C(s)?e:C(n)?ne(function(i,a){return t(i,s,a)}):C(s)?ne(function(i,a){return t(n,i,a)}):Z(function(i){return t(n,s,i)});default:return C(n)&&C(s)&&C(r)?e:C(n)&&C(s)?ne(function(i,a){return t(i,a,r)}):C(n)&&C(r)?ne(function(i,a){return t(i,s,a)}):C(s)&&C(r)?ne(function(i,a){return t(n,i,a)}):C(n)?Z(function(i){return t(i,s,r)}):C(s)?Z(function(i){return t(n,i,r)}):C(r)?Z(function(i){return t(n,s,i)}):t(n,s,r)}}}function De(t,e){return Object.prototype.hasOwnProperty.call(e,t)}var xs=Z(function(e){return e===null?"Null":e===void 0?"Undefined":Object.prototype.toString.call(e).slice(8,-1)});function en(t){return Object.prototype.toString.call(t)==="[object Object]"}var Gs=Number.isInteger||function(e){return e<<0===e};function Fs(t,e){var n=t<0?e.length+t:t;return e[n]}function Vs(t){return new RegExp(t.source,t.flags?t.flags:(t.global?"g":"")+(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.sticky?"y":"")+(t.unicode?"u":"")+(t.dotAll?"s":""))}function xn(t,e,n){if(n||(n=new Hs),js(t))return t;var s=function(i){var a=n.get(t);if(a)return a;n.set(t,i);for(var l in t)Object.prototype.hasOwnProperty.call(t,l)&&(i[l]=xn(t[l],!0,n));return i};switch(xs(t)){case"Object":return s(Object.create(Object.getPrototypeOf(t)));case"Array":return s(Array(t.length));case"Date":return new Date(t.valueOf());case"RegExp":return Vs(t);case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"BigInt64Array":case"BigUint64Array":return t.slice();default:return t}}function js(t){var e=typeof t;return t==null||e!="object"&&e!="function"}var Hs=(function(){function t(){this.map={},this.length=0}return t.prototype.set=function(e,n){var s=this.hash(e),r=this.map[s];r||(this.map[s]=r=[]),r.push([e,n]),this.length+=1},t.prototype.hash=function(e){var n=[];for(var s in e)n.push(Object.prototype.toString.call(e[s]));return n.join()},t.prototype.get=function(e){if(this.length<=180){for(var n in this.map)for(var a=this.map[n],s=0;s<a.length;s+=1){var r=a[s];if(r[0]===e)return r[1]}return}var i=this.hash(e),a=this.map[i];if(a)for(var s=0;s<a.length;s+=1){var r=a[s];if(r[0]===e)return r[1]}},t})(),b=Z(function(e){return e!=null&&typeof e.clone=="function"?e.clone():xn(e)});function Ks(t,e){for(var n=e,s=0;s<t.length;s+=1){if(n==null)return;var r=t[s];Gs(r)?n=Fs(r,n):n=n[r]}return n}var Qs=jt(function(e,n,s){var r={},i;n=n||{},s=s||{};for(i in n)De(i,n)&&(r[i]=De(i,s)?e(i,n[i],s[i]):n[i]);for(i in s)De(i,s)&&!De(i,r)&&(r[i]=s[i]);return r}),zs=jt(function t(e,n,s){return Qs(function(r,i,a){return en(i)&&en(a)?t(e,i,a):e(r,i,a)},n,s)}),Ws=jt(function(e,n,s){return zs(function(r,i,a){return e(i,a)},n,s)}),Xs=ne(Ks),Gn=ne(function(e,n){var s={};for(var r in n)e(n[r],r,n)&&(s[r]=n[r]);return s}),m=t=>typeof t=="function"&&!!(t.constructor&&t.call&&t.apply),_=t=>typeof t=="string",G=t=>t===null,w=t=>typeof t>"u",Q=t=>G(t)||w(t),Ys=t=>typeof t=="bigint",O=t=>!w(t),ve=t=>!Q(t),qs=t=>ve(t)&&t!=="",Ht=t=>{switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return t instanceof Error}},Js=t=>typeof t=="boolean",ht=(t,e)=>{let n=e.split(".");return Xs(n,t)},Zs=(t,e)=>!!ht(t,e),er=t=>typeof t=="object",tr=t=>!G(t)&&er(t)&&!Array.isArray(t),N=t=>!G(t)&&Object.prototype.toString.call(t)==="[object Object]",nr=(t,e)=>{if(!Array.isArray(t)||!Array.isArray(e))return b(e);let n=b(t);return e.forEach((s,r)=>{n[r]=Array.isArray(s)||tr(s)?L(n[r],s):s}),n},L=(t,e)=>Ws(nr,t,e),ee=t=>N(t)&&Object.keys(t).length>0,Te=t=>{let e=Gn(O,t);return Object.keys(e).forEach(n=>{let s=e[n];N(s)&&(e[n]=Te(s))}),e},Qe=t=>{let e=Gn(ve,t);return Object.keys(e).forEach(n=>{let s=e[n];N(s)&&(e[n]=Qe(s))}),e},Y=t=>{if(ee(t))return Qe(t)},z=(t,e)=>typeof t=="boolean"?t:e,Kt=t=>(Object.getOwnPropertyNames(t).forEach(function(e){t[e]&&typeof t[e]=="object"&&Kt(t[e])}),Object.freeze(t)),sr=t=>t.replace(/^\s+|\s+$/gm,""),tn=t=>t.replace(/^\.+/,""),ze=t=>{let e=t;if(!_(t)&&!Q(t))try{e=JSON.stringify(t)}catch{e=null}return e},rr=t=>{let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return globalThis.btoa(e)},ir=t=>rr(new TextEncoder().encode(t)),We=(t,e,n,s,r)=>{let i={category:t,name:e,properties:n,options:s,callback:void 0};m(r)&&(i.callback=r),m(s)&&(i.category=t,i.name=e,i.properties=n,i.options=void 0,i.callback=s),m(n)&&(i.category=t,i.name=e,i.properties=void 0,i.options=void 0,i.callback=n),m(e)&&(i.category=t,i.name=void 0,i.properties=void 0,i.options=void 0,i.callback=e),m(t)&&(i.category=void 0,i.name=void 0,i.properties=void 0,i.options=void 0,i.callback=t),N(t)?(i.name=void 0,i.category=void 0,i.properties=t,m(e)?i.options=void 0:i.options=e):N(e)&&(i.name=void 0,i.properties=e,m(n)?i.options=void 0:i.options=n),_(t)&&!_(e)&&(i.category=void 0,i.name=t),O(i.category)||(i.category=void 0),O(i.name)||(i.name=void 0),i.properties=i.properties?b(i.properties):{},O(i.options)?i.options=b(i.options):i.options=void 0;let a=_(i.name)?i.name:i.properties.name,l=_(i.category)?i.category:i.properties.category;return i.properties=L(N(i.properties)?i.properties:{},{...a&&{name:a},...l&&{category:l}}),i},Qt=(t,e,n,s)=>{let r={name:t,properties:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.properties=e,r.options=void 0,r.callback=n),m(e)&&(r.properties=void 0,r.options=void 0,r.callback=e),r.properties=ve(r.properties)?b(r.properties):{},O(r.options)?r.options=b(r.options):r.options=void 0,r},Fn=(t,e,n,s)=>{let r={userId:t,traits:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.userId=t,r.traits=e,r.options=void 0,r.callback=n),m(e)&&(r.userId=t,r.traits=void 0,r.options=void 0,r.callback=e),(N(t)||G(t))&&(r.userId=null,r.traits=t,m(e)?r.options=void 0:r.options=e),r.userId=ze(r.userId),N(r.traits)?r.traits=b(r.traits):r.traits=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},Vn=(t,e,n,s)=>{let r={to:t,from:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.to=t,r.from=e,r.options=void 0,r.callback=n),m(e)?(r.to=t,r.from=void 0,r.options=void 0,r.callback=e):(N(e)||G(e))&&(r.to=t,r.from=void 0,r.options=e),O(r.to)&&(r.to=ze(r.to)),O(r.from)?r.from=ze(r.from):r.from=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},jn=(t,e,n,s)=>{let r={groupId:t,traits:e,options:n,callback:void 0};return m(s)&&(r.callback=s),m(n)&&(r.groupId=t,r.traits=e,r.options=void 0,r.callback=n),m(e)&&(r.groupId=t,r.traits=void 0,r.options=void 0,r.callback=e),(N(t)||G(t))&&(r.groupId=null,r.traits=t,m(e)?r.options=void 0:r.options=e),r.groupId=ze(r.groupId),N(r.traits)?r.traits=b(r.traits):r.traits=void 0,O(r.options)?r.options=b(r.options):r.options=void 0,r},it=(function(t){return t.UNLOADED="Page Unloaded",t})({}),zt="API",pt="CapabilitiesManager",j="ConfigManager",Hn="EventManager",Le="PluginsManager",ae="UserSessionManager",Ae="ErrorHandler",ge="PluginEngine",or="StoreManager",ot=`Ready${zt}`,ar=`Load${zt}`,lr="HttpClient",cr="RudderStackAnalytics",we="AnalyticsCore";function ur(t){return crypto.getRandomValues(new Uint8Array(t))}var nn=4096,Me=[],se=0,at;for(;se<256;se++)Me[se]=(se+256).toString(16).substring(1);function dr(){(!at||se+16>nn)&&(at=ur(nn),se=0);for(var t=0,e,n="";t<16;t++)e=at[se+t],t==6?n+=Me[e&15|64]:t==8?n+=Me[e&63|128]:n+=Me[e],t&1&&t>1&&t<11&&(n+="-");return se+=16,n}var ue=256,Be=[],Ue;for(;ue--;)Be[ue]=(ue+256).toString(16).substring(1);function gr(){var t=0,e,n="";if(!Ue||ue+16>256){for(Ue=Array(t=256);t--;)Ue[t]=256*Math.random()|0;t=ue=0}for(;t<16;t++)e=Ue[ue+t],t==6?n+=Be[e&15|64]:t==8?n+=Be[e&63|128]:n+=Be[e],t&1&&t>1&&t<11&&(n+="-");return ue++,n}var fr=()=>!Q(globalThis.crypto)&&m(globalThis.crypto.getRandomValues),Ze=()=>fr()?dr():gr(),hr=()=>!!window.chrome?.runtime?.id,Kn=()=>_(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent),pr=(t,e=!1)=>{let n=!1,s=!1;function r(){n||(n=!0,t(s),setTimeout(()=>{n=!1},0))}(e||Kn())&&globalThis.addEventListener("beforeunload",()=>{s=!1,r()}),globalThis.addEventListener("blur",()=>{s=!0,r()}),globalThis.addEventListener("focus",()=>{n=!1}),document.addEventListener("pagehide",()=>{s=document.visibilityState==="hidden",r()}),document.addEventListener("visibilitychange",()=>{s=!0,document.visibilityState==="hidden"?r():n=!1})},Qn=t=>t.toISOString(),vr=()=>Qn(new Date),S=":: ",mr=t=>`A script with the id "${t}" is already loaded. Skipping the loading of this script to prevent conflicts`,sn=(t,e,n)=>`Unable to load (${_(n)?n:n.type}) the script with the id "${t}" from URL "${e}"`,Er=(t,e,n)=>`A timeout of ${n} ms occurred while trying to load the script with id "${t}" from URL "${e}"`,yr=(t,e)=>`${t}${S}A circular reference has been detected in the object and the property "${e}" has been dropped from the output.`,Sr="Failed to convert the value to a JSON string.",br="Failed to encode the cookie data.",Ir=(t,e)=>`${t}${S}The "${e}" storage type is `,Tr="JSONStringify",Ar="[BigInt]",zn="[Circular Reference]",Rr=(t,e,n)=>{let s=[];return function(r,i){if(!e?.includes(r)&&!(t&&Q(i))){if(typeof i!="object"||G(i))return i;for(;s.length>0&&s[s.length-1]!==this;)s.pop();return s.includes(i)?(n?.warn(yr(Tr,r)),zn):(s.push(i),i)}}},K=(t,e,n,s)=>{try{return JSON.stringify(t,Rr(e,n,s))}catch(r){return s?.warn(Sr,r),null}},Or=t=>{let e=[];return function(s,r){if(Ys(r))return Ar;for(;e.length>0&&e[e.length-1]!==this;)e.pop();return e.includes(r)?zn:(e.push(r),r)}},Wn=(t,e)=>{let n=Array.isArray(t)?[]:{};for(let s in t)if(Object.hasOwnProperty.call(t,s)){let r=t[s],i=e.call(t,s,r);N(i)||Array.isArray(i)?n[s]=Wn(i,e):n[s]=i}return n},I=(t,e)=>{let n=Or(),s=n.call(t,"",t);return N(t)||Array.isArray(t)?Wn(t,n):s},xe="[SDK DISPATCHED ERROR]",et=t=>{let{stack:e,stacktrace:n,"opera#sourceloc":s}=t,r=e??n??s;if(r&&typeof r=="string")return r},Wt=(t,e)=>{if(!Ht(t))return new Error(`${e}: ${K(t)}`);try{let n=t.constructor,s=new n(`${e}: ${t.message}`),r=et(t);return r&&(s.stack=r),Object.getOwnPropertyNames(t).forEach(i=>{if(i!=="message"&&i!=="stack"&&i!=="name")try{s[i]=t[i]}catch{}}),s}catch{return new Error(`${e}: ${K(t)}`)}},D=t=>{if(Ht(t)){let e=et(t);if(e){let{stack:n,stacktrace:s,"opera#sourceloc":r}=t;switch(e){case n:t.stack=`${n}
3
- ${xe}`;break;case s:t.stacktrace=`${s}
4
- ${xe}`;break;case r:default:t["opera#sourceloc"]=`${r}
5
- ${xe}`;break}}}globalThis.dispatchEvent(new ErrorEvent("error",{error:t,bubbles:!0,cancelable:!0,composed:!0}))},rn="RudderLabs JavaScript SDK",Ne="3.28.1",_r="com.rudderlabs.javascript",Xn="npm",on="RudderJS-Initiated",Nr="ad-block page request",Pr="/ad-blocked",Oe="preloadedEventsBuffer",kr="Consent Management Interaction",Cr="ajs_trait_",Dr="ajs_prop_",an="ajs_aid",Lr="ajs_uid",ln="ajs_event",wr=10*1e3,Ur=31536e3*1e3,cn=720*60*1e3,vt=1800*1e3,un=10*1e3,$r=10*1e3,Mr=250,Yn=(t="app")=>{globalThis.RudderStackGlobals||(globalThis.RudderStackGlobals={}),globalThis.RudderStackGlobals[t]||(globalThis.RudderStackGlobals[t]={})},Pe=(t,e,n="app")=>{Yn(n),globalThis.RudderStackGlobals[n][t]=e},qn=(t,e="app")=>(Yn(e),globalThis.RudderStackGlobals[e][t]);function Br(t,e,n=Mr){let s;return(...r)=>{globalThis.clearTimeout(s),s=globalThis.setTimeout(()=>{t.apply(e,r)},n)}}var dn=(t,e)=>{let n={};return t.forEach((s,r)=>{if(r.startsWith(e)){let i=r.substring(e.length);n[i]=t.get(r)}}),n},xr=(t=[])=>{let e={trait:Cr,properties:Dr},n=new URLSearchParams(globalThis.location.search);n.get(ln)&&t.unshift(["track",n.get(ln),dn(n,e.properties)]);let s=n.get(Lr),r=dn(n,e.trait);if(s||ee(r)){let i=[...s?[s]:[],r];t.unshift(["identify",...i])}n.get(an)&&t.unshift(["setAnonymousId",n.get(an)])},Gr=t=>{let e="load",n=[],s=0;for(;s<t.length;){if(t[s]&&t[s][0]===e){n=b(t[s]),t.splice(s,1);break}s+=1}return n},Fr=t=>{let e="consent",n=t.filter(r=>r[0]===e),s=t.filter(r=>r[0]!==e);t.splice(0,t.length,...n,...s)},Vr=t=>{let e=qn(Oe)||[];xr(e),e.length>0&&(t.enqueuePreloadBufferEvents(e),Pe(Oe,[]))},jr=(t,e)=>{let n=t.shift(),s;if(m(e[n])){switch(n){case"page":s=We(...t);break;case"track":s=Qt(...t);break;case"identify":s=Fn(...t);break;case"alias":s=Vn(...t);break;case"group":s=jn(...t);break;default:e[n](...t);break}s&&e[n](s)}},Hr=10*1e3,Kr="RS_JS_SDK",Qr=(t,e,n=!0,s=null,r=null,i={})=>{let a=document.createElement("script");return a.type="text/javascript",a.onload=s,a.onerror=r,a.src=t,a.id=e,a.async=n,Object.keys(i).forEach(l=>{a.setAttribute(l,i[l])}),a.setAttribute("data-loader",Kr),a},zr=t=>{let e=document.getElementsByTagName("head");if(e.length>0){e[0]?.insertBefore(t,e[0]?.firstChild);return}let n=document.getElementsByTagName("script");if(n.length>0&&n[0]?.parentNode){n[0]?.parentNode.insertBefore(t,n[0]);return}let s=document.createElement("head");s.appendChild(t);let r=document.getElementsByTagName("html")[0];r?.insertBefore(s,r.firstChild)},Wr=(t,e,n,s=!0,r)=>new Promise((i,a)=>{document.getElementById(e)&&a(new Error(mr(e)));try{let c;zr(Qr(t,e,s,()=>{globalThis.clearTimeout(c),i(e)},v=>{globalThis.clearTimeout(c),a(new Error(sn(e,t,v)))},r)),c=globalThis.setTimeout(()=>{a(new Error(Er(e,t,n)))},n)}catch(c){a(Wt(c,sn(e,t,"unknown")))}}),Xe=class{constructor(e,n=Hr){this.logger=e,this.timeout=n}loadJSFile(e){let{url:n,id:s,timeout:r,async:i,callback:a,extraAttributes:l}=e,c=!m(a);Wr(n,s,r||this.timeout,i,l).then(d=>{c||a(d)}).catch(d=>{c||a(s,d)})}},Xr=Symbol.for("preact-signals");function tt(){if(re>1)re--;else{for(var t,e=!1;_e!==void 0;){var n=_e;for(_e=void 0,mt++;n!==void 0;){var s=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&es(n))try{n.c()}catch(r){e||(t=r,e=!0)}n=s}}if(mt=0,re--,e)throw t}}function U(t){if(re>0)return t();re++;try{return t()}finally{tt()}}var T=void 0;function Jn(t){var e=T;T=void 0;try{return t()}finally{T=e}}var _e=void 0,re=0,mt=0,Ye=0;function Zn(t){if(T!==void 0){var e=t.n;if(e===void 0||e.t!==T)return e={i:0,S:t,p:T.s,n:void 0,t:T,e:void 0,x:void 0,r:e},T.s!==void 0&&(T.s.n=e),T.s=e,t.n=e,32&T.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=T.s,e.n=void 0,T.s.n=e,T.s=e),e}}function $(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}$.prototype.brand=Xr;$.prototype.h=function(){return!0};$.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:Jn(function(){var s;(s=e.W)==null||s.call(e)}))};$.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,s=t.x;n!==void 0&&(n.x=s,t.e=void 0),s!==void 0&&(s.e=n,t.x=void 0),t===this.t&&(this.t=s,s===void 0&&Jn(function(){var r;(r=e.Z)==null||r.call(e)}))}};$.prototype.subscribe=function(t){var e=this;return X(function(){var n=e.value,s=T;T=void 0;try{t(n)}finally{T=s}},{name:"sub"})};$.prototype.valueOf=function(){return this.value};$.prototype.toString=function(){return this.value+""};$.prototype.toJSON=function(){return this.value};$.prototype.peek=function(){var t=T;T=void 0;try{return this.value}finally{T=t}};Object.defineProperty($.prototype,"value",{get:function(){var t=Zn(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(mt>100)throw new Error("Cycle detected");this.v=t,this.i++,Ye++,re++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{tt()}}}});function u(t,e){return new $(t,e)}function es(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function ts(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function ns(t){for(var e=t.s,n=void 0;e!==void 0;){var s=e.p;e.i===-1?(e.S.U(e),s!==void 0&&(s.n=e.n),e.n!==void 0&&(e.n.p=s)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=s}t.s=n}function ye(t,e){$.call(this,void 0),this.x=t,this.s=void 0,this.g=Ye-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ye.prototype=new $;ye.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Ye))return!0;if(this.g=Ye,this.f|=1,this.i>0&&!es(this))return this.f&=-2,!0;var t=T;try{ts(this),T=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return T=t,ns(this),this.f&=-2,!0};ye.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}$.prototype.S.call(this,t)};ye.prototype.U=function(t){if(this.t!==void 0&&($.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}};ye.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}};Object.defineProperty(ye.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Zn(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function ss(t){var e=t.u;if(t.u=void 0,typeof e=="function"){re++;var n=T;T=void 0;try{e()}catch(s){throw t.f&=-2,t.f|=8,Xt(t),s}finally{T=n,tt()}}}function Xt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,ss(t)}function Yr(t){if(T!==this)throw new Error("Out-of-order effect");ns(this),T=t,this.f&=-2,8&this.f&&Xt(this),tt()}function Se(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Se.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}};Se.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ss(this),ts(this),re++;var t=T;return T=this,Yr.bind(this,t)};Se.prototype.N=function(){2&this.f||(this.f|=2,this.o=_e,_e=this)};Se.prototype.d=function(){this.f|=8,1&this.f||Xt(this)};Se.prototype.dispose=function(){this.d()};function X(t,e){var n=new Se(t,e);try{n.c()}catch(r){throw n.d(),r}var s=n.d.bind(n);return s[Symbol.dispose]=s,s}var Et=class{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return this.items.length===0?null:this.items.shift()}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}},$e={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5},gn="LOG",rs="ERROR",qr="RS SDK",Jr="font-weight: bold; background: black; color: white;",Zr="font-weight: normal;",yt=class{constructor(e=gn,n="",s=console){this.minLogLevel=$e[e],this.scope=n,this.logProvider=s}log(...e){this.outputLog("LOG",e)}info(...e){this.outputLog("INFO",e)}debug(...e){this.outputLog("DEBUG",e)}warn(...e){this.outputLog("WARN",e)}error(...e){this.outputLog("ERROR",e)}outputLog(e,n){this.minLogLevel<=$e[e]&&this.logProvider[e.toLowerCase()]?.(...this.formatLogData(n))}setScope(e){this.scope=e||this.scope}setMinLogLevel(e){this.minLogLevel=$e[e],w(this.minLogLevel)&&(this.minLogLevel=$e[gn])}formatLogData(e){if(Array.isArray(e)&&e.length>0){let n=`%c ${qr}`;this.scope&&(n=`${n} - ${this.scope}`);let s=_(e[0])?e[0].trim():"";n=`${n} %c ${s}`;let r=[n,Jr,Zr];return _(e[0])||r.push(e[0]),r.push(...e.slice(1)),r}return e}},te=new yt,q=(function(t){return t.HANDLEDEXCEPTION="handledException",t.UNHANDLEDEXCEPTION="unhandledException",t.UNHANDLEDREJECTION="unhandledPromiseRejection",t})({}),is=["localStorage","memoryStorage","cookieStorage","sessionStorage","none"],St="cookieStorage",fn="Unable to process/parse source configuration response",ei="The source is disabled. Please enable the source in the dashboard to send events.",ti="Failed to prepare data for the request.",ni="Failed to invoke plugin because the extension point name is missing.",si="Failed to invoke plugin because the extension point name is invalid.",ri=t=>`${t}${S}The "getSourceConfig" load API option must be a function that returns valid source configuration data.`,ii=(t,e,n)=>`${t}${S}The base URL "${n}" for ${e} is not valid.`,oi=(t,e,n)=>`${t}${S}The consent manager "${e}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(n)}".`,ai=(t,e)=>`${t}${S}Ignoring a non-error: ${e}.`,hn="Failed to log breadcrumb",li=t=>`${t}${S}Failed to handle the error.`,ci=t=>`${t}${S}Plugin name is missing.`,ui=(t,e)=>`${t}${S}Plugin "${e}" already exists.`,di=(t,e)=>`${t}${S}Plugin "${e}" not found.`,gi=(t,e)=>`${t}${S}Plugin "${e}" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.`,fi=(t,e,n)=>`${t}${S}Plugin "${e}" could not be loaded because some of its dependencies "${n}" do not exist.`,hi=(t,e,n)=>`${t}${S}Failed to invoke the "${e}" extension point of plugin "${n}".`,pn="Failed to fetch the source config",pi=(t,e)=>`${t}${S}The write key "${e}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`,vi=(t,e)=>`${t}${S}The data plane URL "${e}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`,os=t=>`${t}${S}The provided callback parameter is not a function.`,mi=(t,e,n,s,r)=>`${t} with status ${e} (${n}) for URL: ${s}. Response: ${r.trim()}`,Ei=(t,e,n)=>`${t} due to timeout or no connection (${e?e.type:""}) at the client side for URL: ${n}`,yi=(t,e)=>`${t} for URL: ${e}`,Si=t=>`Failed to save the value for "${t}" to storage`,bi=t=>`Failed to retrieve or parse data for "${t}" from storage`,Ii=t=>`The server responded with status ${t} while setting the cookies. As a fallback, the cookies will be set client side.`,Ti=t=>`The server failed to set the ${t} cookie. As a fallback, the cookies will be set client side.`,vn="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.",Ai=(t,e,n)=>`${t}${S}The storage type "${e}" is not supported. Please choose one of the following supported types: "${is}". The default type "${n}" will be used instead.`,Ri=(t,e,n,s)=>`${t}${S}The storage encryption version "${e}" is not supported. Please choose one of the following supported versions: "${Object.keys(n)}". The default version "${s}" will be used instead.`,Oi=(t,e,n)=>`${t}${S}The storage data migration has been disabled because the configured storage encryption version (${e}) is not the latest (${n}). To enable storage data migration, please update the storage encryption version to the latest version.`,_i=(t,e,n)=>`${t}${S}The provided cookie domain (${e}) does not match the current webpage's domain (${n}). Hence, the cookies will be set client-side.`,Ni=(t,e,n,s)=>`${t}${S}The "${e}" property defined under "${n}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${s}).`,Pi=t=>`${t}${S}Please make sure that the "context" property in the event API's "options" argument is a valid object literal with key-value pairs.`,ki=t=>`${t}${S}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`,Ci=(t,e,n)=>`${t}${S}The session timeout value "${e}" is not a number. The default timeout of ${n} ms will be used instead.`,Di=(t,e,n)=>`${t}${S}The session cut off duration value "${e}" is not a number. The default cut off duration of ${n} ms will be used instead.`,Li=(t,e,n)=>`${t}${S}The session cut off duration value "${e}" ms is less than the session timeout value "${n}" ms. The cut off functionality will be disabled.`,wi=t=>`${t}${S}The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.`,Ui=(t,e,n)=>`${t}${S}The session timeout value ${e} ms is less than the recommended minimum of ${n} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`,$i=(t,e,n)=>`${t}${S}The provided session ID (${e}) is either invalid, not a positive integer, or not at least "${n}" digits long. A new session ID will be auto-generated instead.`,Mi=t=>`${t}${S}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`,Bi=(t,e,n,s)=>`${t}${S}The storage type "${n}" is not available for entry "${e}". The SDK will initialize the entry with "${s}" storage type instead.`,xi=t=>`${t}${S}The callback threw an exception`,Gi=(t,e)=>`${t}${S}The provided source config URL "${e}" is invalid. Using the default source config URL instead.`,Fi=(t,e)=>`Failed to load the polyfill script with ID "${t}" from URL ${e}.`,Vi=(t,e,n)=>`${t}${S}The pre-consent storage strategy "${e}" is not supported. Please choose one of the following supported strategies: "none, session, anonymousId". The default strategy "${n}" will be used instead.`,ji=(t,e,n)=>`${t}${S}The pre-consent events delivery type "${e}" is not supported. Please choose one of the following supported types: "immediate, buffer". The default type "${n}" will be used instead.`,Hi=(t,e)=>`${t}${S}${e} plugin is deprecated. Please exclude it from the load API options.`,Ki=(t,e,n,s)=>{let r=n.length===1,i=r?` '${n[0]}' plugin was`:` ['${n.join("', '")}'] plugins were`,a=`${t}${S}${e}, but${i} not configured to load.`;return s?`${a} So, ${r?"the plugin":"those plugins"} will be loaded automatically.`:`${a} Ignore if this was intentional. Otherwise, consider adding ${r?"it":"them"} to the 'plugins' load API option.`},Qi=(t,e)=>`${t}${S}The provided polyfill URL "${e}" is invalid. The default polyfill URL will be used instead.`,zi=t=>`${t}${S}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`,Wi=(t,e)=>`${t}${S}Ignoring unknown plugins: ${e.join(", ")}.`,Xi=(t,e)=>`${t}${S}Cannot add custom integration for destination ID "${e}" after the SDK is loaded.`,as={All:!0},nt="js-integrations",ls="plugins",Yi=new RegExp("^(https?:\\/\\/)(((([a-zA-Z\\d]([a-zA-Z\\d-]*[a-zA-Z\\d])*)\\.)+[a-zA-Z]{2,}|localhost|((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)))(\\:\\d+)?(\\/[-a-zA-Z\\d%_.~+]*)*(\\?[;&a-zA-Z\\d%_.~+=-]*)?(\\#[-a-zA-Z\\d_]*)?$"),ke="modern",st="https://cdn.rudderlabs.com",Yt="v3",cs=`${st}/${Yt}/${ke}/${nt}`,us=`${st}/${Yt}/${ke}/${ls}`,ds="https://api.rudderstack.com",le="v3",qi="xhr",bt={iubenda:"IubendaConsentManager",oneTrust:"OneTrustConsentManager",ketch:"KetchConsentManager",custom:"CustomConsentManager"},Ge={[le]:"StorageEncryption",legacy:"StorageEncryptionLegacy"},Ji={[qi]:"XhrQueue",beacon:"BeaconQueue"},Zi="rsaRequest",eo="rsaMetrics",to="Custom Device Mode",no={configUrl:ds,loadIntegration:!0,sessions:{autoTrack:!0,timeout:vt,cutOff:{enabled:!1}},sameSiteCookie:"Lax",polyfillIfRequired:!0,integrations:as,useBeacon:!1,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:!0,lockPluginsVersion:!0,uaChTrackLevel:"none",plugins:[],useGlobalIntegrationsConfigInEvents:!1,bufferDataPlaneEventsUntilReady:!1,dataPlaneEventsBufferTimeout:$r,storage:{encryption:{version:le},migrate:!0,cookie:{}},sendAdblockPage:!1,sameDomainCookiesOnly:!1,secureCookie:!1,sendAdblockPageOptions:{},useServerSideCookies:!1},so=u(b(no)),A=Kt({userId:"",userTraits:{},anonymousId:"",groupId:"",groupTraits:{},initialReferrer:"",initialReferringDomain:"",sessionInfo:{},authToken:null}),lt=Kt({entries:{userId:!0,userTraits:!0,groupId:!0,groupTraits:!0,sessionInfo:!0,authToken:!0,anonymousId:!1,initialReferrer:!1,initialReferringDomain:!1}}),ro=10,io={userId:u(A.userId),userTraits:u(A.userTraits),anonymousId:u(A.anonymousId),groupId:u(A.groupId),groupTraits:u(A.groupTraits),initialReferrer:u(A.initialReferrer),initialReferringDomain:u(A.initialReferringDomain),sessionInfo:u(A.sessionInfo),authToken:u(A.authToken)},oo={isOnline:u(!0),storage:{isLocalStorageAvailable:u(!1),isCookieStorageAvailable:u(!1),isSessionStorageAvailable:u(!1)},isBeaconAvailable:u(!1),isLegacyDOM:u(!1),isUaCHAvailable:u(!1),isCryptoAvailable:u(!1),isIE11:u(!1),isAdBlockerDetectionInProgress:u(!1),isAdBlocked:u(void 0),cspBlockedURLs:u([])},ao={isErrorReportingEnabled:u(!1),isMetricsReportingEnabled:u(!1),breadcrumbs:u([])},lo=u(void 0),co={activeDataplaneUrl:u(void 0),integrationsCDNPath:u(cs),pluginsCDNPath:u(us),sourceConfigUrl:u(void 0),status:u(void 0),initialized:u(!1),logLevel:u(rs),loaded:u(!1),readyCallbacks:u([]),writeKey:u(void 0),dataPlaneUrl:u(void 0),safeAnalyticsInstance:u(void 0)},uo={enabled:u(!1),initialized:u(!1),data:u({}),activeConsentManagerPluginName:u(void 0),preConsent:u({enabled:!1}),postConsent:u({}),resolutionStrategy:u("and"),provider:u(void 0),metadata:u(void 0)},go={retries:u(0),dropped:u(0),sent:u(0),queued:u(0),triggered:u(0),metricsServiceUrl:u(void 0)},fo={app:u({name:rn,namespace:_r,version:Ne,installType:Xn}),traits:u(null),library:u({name:rn,version:Ne,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:u(null),device:u(null),network:u(null),os:u({name:"",version:""}),locale:u(null),screen:u({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),"ua-ch":u(void 0),timezone:u(void 0)},ho={configuredDestinations:u([]),activeDestinations:u([]),loadOnlyIntegrations:u({}),failedDestinations:u([]),loadIntegration:u(!0),initializedDestinations:u([]),clientDestinationsReady:u(!1),integrationsConfig:u({})},po={toBeProcessedArray:u([]),readyCallbacksArray:u([])},vo={ready:u(!1),loadedPlugins:u([]),failedPlugins:u([]),pluginsToLoadFromConfig:u([]),activePlugins:u([]),totalPluginsToLoad:u(0)},mo={encryptionPluginName:u(void 0),migrate:u(!1),type:u(void 0),cookie:u(void 0),entries:u({}),trulyAnonymousTracking:u(!1)},Eo={isEnabledServerSideCookies:u(!1),dataServiceUrl:u(void 0)},yo={eventsQueuePluginName:u(void 0),deliveryEnabled:u(!0)},So={enabled:u(!1),pageLifecycle:{enabled:u(!1),pageViewId:u(void 0),pageLoadedTimestamp:u(void 0)}},bo={capabilities:oo,consents:uo,context:fo,eventBuffer:po,lifecycle:co,loadOptions:so,metrics:go,nativeDestinations:ho,plugins:vo,reporting:ao,session:io,source:lo,storage:mo,serverCookies:Eo,dataPlaneEvents:yo,autoTrack:So},o={...b(bo)};function gs(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Fe={exports:{}},Ve={exports:{}},Io=Ve.exports,mn;function To(){return mn||(mn=1,(function(t,e){(function(n,s){t.exports=s()})(Io,function(){function n(h){return!isNaN(parseFloat(h))&&isFinite(h)}function s(h){return h.charAt(0).toUpperCase()+h.substring(1)}function r(h){return function(){return this[h]}}var i=["isConstructor","isEval","isNative","isToplevel"],a=["columnNumber","lineNumber"],l=["fileName","functionName","source"],c=["args"],d=["evalOrigin"],g=i.concat(a,l,c,d);function v(h){if(h)for(var E=0;E<g.length;E++)h[g[E]]!==void 0&&this["set"+s(g[E])](h[g[E]])}v.prototype={getArgs:function(){return this.args},setArgs:function(h){if(Object.prototype.toString.call(h)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=h},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(h){if(h instanceof v)this.evalOrigin=h;else if(h instanceof Object)this.evalOrigin=new v(h);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var h=this.getFileName()||"",E=this.getLineNumber()||"",R=this.getColumnNumber()||"",P=this.getFunctionName()||"";return this.getIsEval()?h?"[eval] ("+h+":"+E+":"+R+")":"[eval]:"+E+":"+R:P?P+" ("+h+":"+E+":"+R+")":h+":"+E+":"+R}},v.fromString=function(E){var R=E.indexOf("("),P=E.lastIndexOf(")"),ie=E.substring(0,R),rt=E.substring(R+1,P).split(","),Ce=E.substring(P+1);if(Ce.indexOf("@")===0)var be=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(Ce,""),$s=be[1],Ms=be[2],Bs=be[3];return new v({functionName:ie,args:rt||void 0,fileName:$s,lineNumber:Ms||void 0,columnNumber:Bs||void 0})};for(var y=0;y<i.length;y++)v.prototype["get"+s(i[y])]=r(i[y]),v.prototype["set"+s(i[y])]=(function(h){return function(E){this[h]=!!E}})(i[y]);for(var f=0;f<a.length;f++)v.prototype["get"+s(a[f])]=r(a[f]),v.prototype["set"+s(a[f])]=(function(h){return function(E){if(!n(E))throw new TypeError(h+" must be a Number");this[h]=Number(E)}})(a[f]);for(var p=0;p<l.length;p++)v.prototype["get"+s(l[p])]=r(l[p]),v.prototype["set"+s(l[p])]=(function(h){return function(E){this[h]=String(E)}})(l[p]);return v})})(Ve)),Ve.exports}var Ao=Fe.exports,En;function Ro(){return En||(En=1,(function(t,e){(function(n,s){t.exports=s(To())})(Ao,function(s){var r=/(^|@)\S+:\d+/,i=/^\s*at .*(\S+:\d+|\(native\))/m,a=/^(eval@)?(\[native code])?$/;return{parse:function(c){if(typeof c.stacktrace<"u"||typeof c["opera#sourceloc"]<"u")return this.parseOpera(c);if(c.stack&&c.stack.match(i))return this.parseV8OrIE(c);if(c.stack)return this.parseFFOrSafari(c);throw new Error("Cannot parse given Error object")},extractLocation:function(c){if(c.indexOf(":")===-1)return[c];var d=/(.+?)(?::(\d+))?(?::(\d+))?$/,g=d.exec(c.replace(/[()]/g,""));return[g[1],g[2]||void 0,g[3]||void 0]},parseV8OrIE:function(c){var d=c.stack.split(`
6
- `).filter(function(g){return!!g.match(i)},this);return d.map(function(g){g.indexOf("(eval ")>-1&&(g=g.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var v=g.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),y=v.match(/ (\(.+\)$)/);v=y?v.replace(y[0],""):v;var f=this.extractLocation(y?y[1]:v),p=y&&v||void 0,h=["eval","<anonymous>"].indexOf(f[0])>-1?void 0:f[0];return new s({functionName:p,fileName:h,lineNumber:f[1],columnNumber:f[2],source:g})},this)},parseFFOrSafari:function(c){var d=c.stack.split(`
7
- `).filter(function(g){return!g.match(a)},this);return d.map(function(g){if(g.indexOf(" > eval")>-1&&(g=g.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),g.indexOf("@")===-1&&g.indexOf(":")===-1)return new s({functionName:g});var v=/((.*".+"[^@]*)?[^@]*)(?:@)/,y=g.match(v),f=y&&y[1]?y[1]:void 0,p=this.extractLocation(g.replace(v,""));return new s({functionName:f,fileName:p[0],lineNumber:p[1],columnNumber:p[2],source:g})},this)},parseOpera:function(c){return!c.stacktrace||c.message.indexOf(`
8
- `)>-1&&c.message.split(`
9
- `).length>c.stacktrace.split(`
10
- `).length?this.parseOpera9(c):c.stack?this.parseOpera11(c):this.parseOpera10(c)},parseOpera9:function(c){for(var d=/Line (\d+).*script (?:in )?(\S+)/i,g=c.message.split(`
11
- `),v=[],y=2,f=g.length;y<f;y+=2){var p=d.exec(g[y]);p&&v.push(new s({fileName:p[2],lineNumber:p[1],source:g[y]}))}return v},parseOpera10:function(c){for(var d=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,g=c.stacktrace.split(`
12
- `),v=[],y=0,f=g.length;y<f;y+=2){var p=d.exec(g[y]);p&&v.push(new s({functionName:p[3]||void 0,fileName:p[2],lineNumber:p[1],source:g[y]}))}return v},parseOpera11:function(c){var d=c.stack.split(`
13
- `).filter(function(g){return!!g.match(r)&&!g.match(/^Error created at/)},this);return d.map(function(g){var v=g.split("@"),y=this.extractLocation(v.pop()),f=v.shift()||"",p=f.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0,h;f.match(/\(([^)]*)\)/)&&(h=f.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var E=h===void 0||h==="[arguments not available]"?void 0:h.split(",");return new s({functionName:p,args:E,fileName:y[0],lineNumber:y[1],columnNumber:y[2],source:g})},this)}}})})(Fe)),Fe.exports}var Oo=Ro(),_o=gs(Oo),fs="global code",No=t=>O(t)&&/^global code$/i.test(t)?fs:t,Po=t=>{let e={file:t.fileName,method:No(t.functionName),lineNumber:t.lineNumber,columnNumber:t.columnNumber};return e.lineNumber&&e.lineNumber>-1&&!e.file&&!e.method&&(e.file=fs),e},yn=t=>_(t)?t:"";function Sn(t,e,n,s){return{errorClass:yn(t),message:`${n}${yn(e)}`,type:"browserjs",stacktrace:s.reduce((r,i)=>{let a=Po(i);try{return JSON.stringify(a)==="{}"?r:r.concat(a)}catch{return r}},[])}}var hs=(t,e)=>{let n;return Ht(t)&&_(et(t))?n=t:(e.warn(ai(Ae,K(t))),n=void 0),n},ko=(t,e)=>{try{let n=_o.parse(t);return Sn(t.name,t.message,e,n)}catch{return Sn(t.name,t.message,e,[])}},bn=(t,e)=>{try{return JSON.parse(t||"")}catch(n){let s=Wt(n,"Failed to parse response data");e(s)}},je="The request failed",Co=[/Failed to fetch dynamically imported module: .*/],Do=[/Unable to load \(.*\) the script with the id .*/,/A timeout of \d+ ms occurred while trying to load the script with id .*/],Lo=[new RegExp(`${je}.*`),/A script with the id .* is already loaded\./],wo=[...Co,...Do],Uo="integrations",$o="sdk",Mo=$o,Bo={headers:{Accept:"application/json","Content-Type":"application/json;charset=UTF-8"},method:"GET"},In=(t,e,n)=>{let s=L(Bo,e||{});return n&&(s.headers=L(s.headers,{Authorization:n})),s.url=t,s},Tn=(t,e=wr,n)=>new Promise((s,r)=>{let i;if(t.sendRawData===!0)i=t.data;else if(i=K(t.data,!1,[],n),G(i)){r({error:new Error(ti),undefined:void 0,options:t});return}let a=new XMLHttpRequest,l=d=>{r({error:new Error(mi(je,a.status,a.statusText,t.url,a.responseText)),xhr:a,options:t})},c=d=>{r({error:new Error(Ei(je,d,t.url)),xhr:a,options:t,...d?.type==="timeout"?{timedOut:!0}:{}})};a.ontimeout=c,a.onerror=c,a.onload=()=>{a.status>=200&&a.status<400?s({response:a.responseText,xhr:a,options:t}):l()},a.open(t.method,t.url,!0),t.withCredentials===!0&&(a.withCredentials=!0),a.timeout=e,Object.keys(t.headers).forEach(d=>{t.headers[d]&&a.setRequestHeader(d,t.headers[d])});try{a.send(i)}catch(d){r({error:Wt(d,yi(je,t.url)),xhr:a,options:t})}}),It=class{constructor(e){this.logger=e,this.onError=this.onError.bind(this)}init(e){this.errorHandler=e}async getData(e){let{url:n,options:s,timeout:r,isRawResponse:i}=e;try{let a=await Tn(In(n,s,this.basicAuthHeader),r,this.logger);return{data:i?a.response:bn(a.response,this.onError),details:a}}catch(a){return{data:void 0,details:a}}}getAsyncData(e){let{callback:n,url:s,options:r,timeout:i,isRawResponse:a}=e,l=!m(n);Tn(In(s,r,this.basicAuthHeader),i,this.logger).then(c=>{l||n(a?c.response:bn(c.response,this.onError),c)}).catch(c=>{l||n(void 0,c)})}onError(e,n){this.errorHandler?.onError({error:e,context:lr,groupingHash:n})}setAuthHeader(e,n=!1){let s=n?e:ir(`${e}:`);this.basicAuthHeader=`Basic ${s}`}resetAuthHeader(){this.basicAuthHeader=void 0}},ps=new It(te),xo="1",Go=()=>["rsa"],Fo=["www.test-host.com","localhost","127.0.0.1","[::1]"],Vo=["userId","userTraits","groupId","groupTraits","anonymousId","config","integration","eventBuffer","traits","authToken"],jo="RudderStack JavaScript SDK",Ho="git+https://github.com/rudderlabs/rudder-sdk-js.git",Ko="js",vs=t=>{o.capabilities.isAdBlockerDetectionInProgress.value=!0;try{let e=new URL(o.lifecycle.sourceConfigUrl.value),n=`${e.origin}${e.pathname}?view=ad`;t.getAsyncData({url:n,options:{method:"HEAD",headers:{"Content-Type":void 0}},isRawResponse:!0,callback:(s,r)=>{o.capabilities.isAdBlockerDetectionInProgress.value=!1,o.capabilities.isAdBlocked.value=r?.error!==void 0||r?.xhr?.responseURL!==n}})}catch(e){throw o.capabilities.isAdBlockerDetectionInProgress.value=!1,e}},Qo=(t,e)=>{switch(e){case q.UNHANDLEDEXCEPTION:{let{error:n}=t;return n||t}case q.UNHANDLEDREJECTION:return t.reason;case q.HANDLEDEXCEPTION:default:return t}},zo=t=>({type:"manual",name:t,timestamp:new Date,metaData:{}}),Wo=(t=()=>window.location.hostname)=>{let e=t();return!e||e&&Fo.includes(e)?"development":"production"},Xo=t=>{let e=K(t,!1,Vo);return e!==null?JSON.parse(e):{}},Yo=()=>globalThis.location.href.split("?")[0],qo=(t,e,n,s)=>({id:`${t.value?.id??n.writeKey.value}..${e.sessionInfo.value.id??"NA"}..${s.pageLifecycle.pageViewId.value??"NA"}`,name:t.value?.name??"NA"}),Jo=(t,e)=>({locale:t.value??"NA",userAgent:e.value??"NA",time:new Date}),Zo=(t,e,n,s)=>{let{context:r,lifecycle:i,session:a,source:l,reporting:c,autoTrack:d}=n,{app:g,locale:v,userAgent:y,timezone:f,screen:p,library:h}=r;return{payloadVersion:"5",notifier:{name:jo,version:g.value.version,url:Ho},events:[{exceptions:[b(t)],severity:e.severity,unhandled:e.unhandled,severityReason:e.severityReason,app:{version:g.value.version,releaseStage:Wo(),type:g.value.installType},device:Jo(v,y),request:{url:Yo(),clientIp:"[NOT COLLECTED]"},breadcrumbs:b(c.breadcrumbs.value),context:t.message,groupingHash:s,metaData:{app:{snippetVersion:h.value.snippetVersion},device:{...p.value,timezone:f.value},...Xo(n)},user:qo(l,a,i,d)}]}},ea=(t,e,n)=>{if(w(t.capabilities.isAdBlocked.value)){t.capabilities.isAdBlockerDetectionInProgress.value===!1&&vs(e);let s=X(()=>{O(t.capabilities.isAdBlocked.value)&&(n(t.capabilities.isAdBlocked.value===!1),s())})}else n(t.capabilities.isAdBlocked.value===!1)},ta=(t,e,n)=>{let s=t.message;return new Promise(r=>{if(wo.some(i=>i.test(s))){let i=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(s)?.[0];_(i)?i.startsWith(st)?e.capabilities.cspBlockedURLs.value.includes(i)?r(!1):ea(e,n,r):r(!1):r(!0)}else r(!Lo.some(i=>i.test(s)))})},ms=t=>t?t.split("/").at(-2):void 0,Es=t=>{let e=t.stacktrace[0]?.file;if(!(!e||typeof e!="string"))return e},na=t=>{let e=Es(t);if(!e)return!1;let n=e.substring(e.lastIndexOf("/")+1);return ms(e)===nt||Go().some(r=>n.startsWith(r)&&n.endsWith(".js"))},sa=(t,e)=>{if(e)return e;let n=Es(t);return ms(n)===nt?Uo:Mo},ra=(t,e,n)=>{let s={version:xo,message_id:Ze(),source:{name:Ko,sdk_version:e.context.app.value.version,write_key:e.lifecycle.writeKey.value,install_type:e.context.app.value.installType,category:n},errors:t};return K(s)},ia=(t,e,n)=>{let s;if(!O(t))s=e;else if(_(t))s=t;else{let r=hs(t,n);O(r)?s=r.message:s=e}return s},Tt=class{constructor(e,n){k(this,"initialized",!1);this.httpClient=e,this.logger=n}init(){this.initialized||(this.attachErrorListeners(),this.initialized=!0)}attachErrorListeners(){globalThis.addEventListener("error",e=>{this.onError({error:e,context:Ae,errorType:q.UNHANDLEDEXCEPTION})}),globalThis.addEventListener("unhandledrejection",e=>{this.onError({error:e,context:Ae,errorType:q.UNHANDLEDREJECTION})}),document.addEventListener("securitypolicyviolation",e=>{let n=_(e.blockedURI)?e.blockedURI:"";e.disposition==="enforce"&&n.startsWith(st)&&!o.capabilities.cspBlockedURLs.value.includes(n)&&(o.capabilities.cspBlockedURLs.value=[...o.capabilities.cspBlockedURLs.value,n])})}async onError(e){try{let{error:n,context:s,customMessage:r,groupingHash:i,category:a}=e,l=e.errorType??q.HANDLEDEXCEPTION,c=Qo(n,l),d=hs(c,this.logger);if(w(d))return;let g=r?`${r} - `:"",v=`${s}${S}${g}`,y=ko(d,v),p=et(d).includes(xe);if(!p&&!na(y)&&l!==q.HANDLEDEXCEPTION)return;if(o.reporting.isErrorReportingEnabled.value&&await ta(y,o,this.httpClient)){let E={severity:"error",unhandled:l!==q.HANDLEDEXCEPTION,severityReason:{type:l}},R=ia(i,y.message,this.logger),P=Zo(y,E,o,R),ie=sa(y,a);this.httpClient.getAsyncData({url:o.metrics.metricsServiceUrl.value,options:{method:"POST",data:ra(P,o,ie),sendRawData:!0},isRawResponse:!0})}(l===q.HANDLEDEXCEPTION||p)&&this.logger.error(y.message)}catch(n){this.logger.error(li(Ae),n)}}leaveBreadcrumb(e){try{o.reporting.breadcrumbs.value=[...o.reporting.breadcrumbs.value,zo(e)]}catch(n){this.onError({error:n,context:Ae,customMessage:hn,groupingHash:hn})}}},ys=new Tt(ps,te),At=class{constructor(e,n={}){k(this,"plugins",[]);k(this,"byName",{});k(this,"cache",{});k(this,"config",{throws:!0});this.config={throws:!0,...n},this.logger=e}register(e,n){if(!e.name){let r=ci(ge);if(this.config.throws)throw new Error(r);this.logger.error(r,e);return}if(this.byName[e.name]){let r=ui(ge,e.name);if(this.config.throws)throw new Error(r);this.logger.error(r);return}this.cache={},this.plugins=this.plugins.slice();let s=this.plugins.length;this.plugins.forEach((r,i)=>{r.deps?.includes(e.name)&&(s=Math.min(s,i))}),this.plugins.splice(s,0,e),this.byName[e.name]=e,m(e.initialize)&&e.initialize(n)}unregister(e){let n=this.byName[e];if(!n){let r=di(ge,e);if(this.config.throws)throw new Error(r);this.logger.error(r);return}let s=this.plugins.indexOf(n);if(s===-1){let r=gi(ge,e);if(this.config.throws)throw new Error(r);this.logger.error(r);return}this.cache={},delete this.byName[e],this.plugins=this.plugins.slice(),this.plugins.splice(s,1)}getPlugin(e){return this.byName[e]}getPlugins(e){let n=e??".";return this.cache[n]||(this.cache[n]=this.plugins.filter(s=>{if(s.deps?.some(r=>!this.byName[r])){let r=s.deps.filter(i=>!this.byName[i]);return this.logger.error(fi(ge,s.name,r)),!1}return n==="."?!0:Zs(s,n)})),this.cache[n]}processRawPlugins(e){e(this.plugins),this.cache={}}invoke(e,n=!0,...s){let r=e;if(!r)throw new Error(ni);let i=r.startsWith("!"),a=this.config.throws??r.endsWith("!");if(r=r.replace(/(^!|!$)/g,""),!r)throw new Error(si);let l=r.split(".");l.pop();let c=l.join(".");return(n?this.getPlugins(r):[this.getPlugins(r)[0]]).map(g=>{let v=ht(g,r);if(!m(v)||i)return v;try{return v.apply(ht(g,c),s)}catch(y){if(a)throw y;this.logger.error(hi(ge,r,g.name),y)}return null})}invokeSingle(e,...n){return this.invoke(e,!1,...n)[0]}invokeMultiple(e,...n){return this.invoke(e,!0,...n)}},oa=new At(te,{throws:!0}),aa=t=>t.config.connectionMode!=="cloud"||t.config.useNativeSDKToSend===!0||t.config.useNativeSDK===!0,la=t=>t.config.connectionMode==="hybrid"||t.config.useNativeSDKToSend===!0,An=t=>t.filter(aa),ca=(t,e)=>`${t.replaceAll(" ","-")}___${e}`,Ss=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],ua=["Bugsnag","ErrorReporting"],da={rudderAnalyticsRemotePlugins:{url:()=>Promise.resolve(window.RudderStackGlobals&&window.RudderStackGlobals.app&&window.RudderStackGlobals.app.pluginsCDNPath?`${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js`:"https://cdn.rudderlabs.com/v3/modern/plugins//rsa-plugins.js"),format:"esm",from:"vite"}};function bs(t,e){let n=Object.assign(t,e);for(let s of Object.keys(n))typeof n[s]=="object"&&typeof e[s]=="object"&&(n[s]=bs(n[s],e[s]));return n}var ga=t=>bs({},(globalThis.__federation_shared__||{}).default||{});async function fa(t){let e=da[t];if(e.inited)return e.lib;if(["esm","systemjs"].includes(e.format))return new Promise((n,s)=>{(typeof e.url=="function"?e.url:()=>Promise.resolve(e.url))().then(i=>{import(i).then(a=>{if(!e.inited){let l=ga();a.init(l),e.lib=a,e.lib.init(l),e.inited=!0}n(e.lib)}).catch(s)})})}function M(t,e){if(!t?.default&&e){let n=Object.create(null);return n.default=t,n.__esModule=!0,n}return t}function B(t,e){return fa(t).then(n=>n.get(e).then(s=>s()))}var ha=t=>{switch(t){case"BeaconQueue":return()=>B("rudderAnalyticsRemotePlugins","./BeaconQueue").then(e=>M(e,!0));case"CustomConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./CustomConsentManager").then(e=>M(e,!0));case"DeviceModeDestinations":return()=>B("rudderAnalyticsRemotePlugins","./DeviceModeDestinations").then(e=>M(e,!0));case"DeviceModeTransformation":return()=>B("rudderAnalyticsRemotePlugins","./DeviceModeTransformation").then(e=>M(e,!0));case"ExternalAnonymousId":return()=>B("rudderAnalyticsRemotePlugins","./ExternalAnonymousId").then(e=>M(e,!0));case"GoogleLinker":return()=>B("rudderAnalyticsRemotePlugins","./GoogleLinker").then(e=>M(e,!0));case"KetchConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./KetchConsentManager").then(e=>M(e,!0));case"IubendaConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./IubendaConsentManager").then(e=>M(e,!0));case"NativeDestinationQueue":return()=>B("rudderAnalyticsRemotePlugins","./NativeDestinationQueue").then(e=>M(e,!0));case"OneTrustConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./OneTrustConsentManager").then(e=>M(e,!0));case"StorageEncryption":return()=>B("rudderAnalyticsRemotePlugins","./StorageEncryption").then(e=>M(e,!0));case"StorageEncryptionLegacy":return()=>B("rudderAnalyticsRemotePlugins","./StorageEncryptionLegacy").then(e=>M(e,!0));case"StorageMigrator":return()=>B("rudderAnalyticsRemotePlugins","./StorageMigrator").then(e=>M(e,!0));case"XhrQueue":return()=>B("rudderAnalyticsRemotePlugins","./XhrQueue").then(e=>M(e,!0));default:return}},pa=t=>{let e={};return t.forEach(n=>{if(Ss.includes(n)){let s=ha(n);s&&(e[n]=s)}}),e},Is=()=>({}),va=()=>({}),ma=t=>pa?.(t)||{},ct={...Is(),...va()},Ea=t=>({...ma(t)}),Rt=class{constructor(e,n,s){this.engine=e,this.errorHandler=n,this.logger=s,this.onError=this.onError.bind(this)}init(){o.lifecycle.status.value="pluginsLoading",Pe("pluginsCDNPath",o.lifecycle.pluginsCDNPath.value),this.setActivePlugins(),this.registerLocalPlugins(),this.registerRemotePlugins(),this.attachEffects()}attachEffects(){X(()=>{(o.plugins.activePlugins.value.length===0||o.plugins.loadedPlugins.value.length+o.plugins.failedPlugins.value.length===o.plugins.totalPluginsToLoad.value)&&U(()=>{o.plugins.ready.value=!0,o.lifecycle.status.value="pluginsReady"})})}getPluginsToLoadBasedOnConfig(){let e=o.plugins.pluginsToLoadFromConfig.value;if(!e)return[];e=e.filter(r=>ua.includes(r)?(this.logger.warn(Hi(Le,r)),!1):!0);let n=[{configurationStatus:()=>O(o.dataPlaneEvents.eventsQueuePluginName.value),configurationStatusStr:"Data plane events delivery is enabled",activePluginName:o.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(Ji),shouldAddMissingPlugins:!0},{configurationStatus:()=>An(o.nativeDestinations.configuredDestinations.value).length>0,configurationStatusStr:"Device mode destinations are connected to the source",supportedPlugins:["DeviceModeDestinations","NativeDestinationQueue"]},{configurationStatus:()=>An(o.nativeDestinations.configuredDestinations.value).some(r=>r.shouldApplyDeviceModeTransformation),configurationStatusStr:"Device mode transformations are enabled for at least one destination",supportedPlugins:["DeviceModeTransformation"]},{configurationStatus:()=>O(o.consents.activeConsentManagerPluginName.value),configurationStatusStr:"Consent management is enabled",activePluginName:o.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(bt)},{configurationStatus:()=>O(o.storage.encryptionPluginName.value),configurationStatusStr:"Storage encryption is enabled",activePluginName:o.storage.encryptionPluginName.value,supportedPlugins:Object.values(Ge)},{configurationStatus:()=>o.storage.migrate.value,configurationStatusStr:"Storage migration is enabled",supportedPlugins:["StorageMigrator"]}],s=!1;return n.forEach(r=>{r.configurationStatus()?(e=e.filter(r.activePluginName?i=>!(i!==r.activePluginName&&r.supportedPlugins.includes(i)):i=>O(i)),this.addMissingPlugins(r,s,e)):e=e.filter(r.basePlugins!==void 0?i=>!(r.basePlugins.includes(i)||r.supportedPlugins.includes(i)):i=>!r.supportedPlugins.includes(i))}),[...Object.keys(Is()),...e]}addMissingPlugins(e,n,s){let r=e.shouldAddMissingPlugins||n,i;e.activePluginName?i=[...e.basePlugins||[],e.activePluginName]:i=[...e.supportedPlugins];let a=i.filter(l=>!s.includes(l));a.length>0&&(r&&s.push(...a),this.logger.warn(Ki(Le,e.configurationStatusStr,a,r)))}setActivePlugins(){let e=this.getPluginsToLoadBasedOnConfig(),n=[...Object.keys(ct),...Ss],s=[],r=[];e.forEach(i=>{n.includes(i)?s.push(i):r.push(i)}),r.length>0&&this.logger.warn(Wi(Le,r)),U(()=>{o.plugins.totalPluginsToLoad.value=e.length,o.plugins.activePlugins.value=s,o.plugins.failedPlugins.value=r})}registerLocalPlugins(){Object.values(ct).forEach(e=>{m(e)&&o.plugins.activePlugins.value.includes(e().name)&&this.register([e()])})}registerRemotePlugins(){let e=Ea(o.plugins.activePlugins.value);Promise.all(Object.keys(e).map(async n=>{await e[n]().then(s=>this.register([s.default()])).catch(s=>{o.plugins.failedPlugins.value=[...o.plugins.failedPlugins.value,n],this.onError(s,`Failed to load plugin "${n}"`,s)})})).catch(n=>{this.onError(n)})}invokeMultiple(e,...n){try{return this.engine.invokeMultiple(e,...n)}catch(s){return this.onError(s,e),[]}}invokeSingle(e,...n){try{return this.engine.invokeSingle(e,...n)}catch(s){return this.onError(s,e),null}}register(e){e.forEach(n=>{try{this.engine.register(n,o)}catch(s){o.plugins.failedPlugins.value=[...o.plugins.failedPlugins.value,n.name],this.onError(s,`Failed to register plugin "${n.name}"`)}})}unregisterLocalPlugins(){Object.values(ct).forEach(e=>{try{this.engine.unregister(e().name)}catch(n){this.onError(n,`Failed to unregister plugin "${e().name}"`)}})}onError(e,n,s){this.errorHandler.onError({error:e,context:Le,customMessage:n,groupingHash:s})}},x="cookieStorage",F="localStorage",V="sessionStorage",W="memoryStorage",de="none",ya="test_rudder_cookie",Sa="test_rudder_ls",ba="test_rudder_ss",Ia="rl_user_id",Ta="rl_trait",Aa="rl_anonymous_id",Ra="rl_group_id",Oa="rl_group_trait",_a="rl_page_init_referrer",Na="rl_page_init_referring_domain",Pa="rl_session",ka="rl_auth_token",fe={userId:Ia,userTraits:Ta,anonymousId:Aa,groupId:Ra,groupTraits:Oa,initialReferrer:_a,initialReferringDomain:Na,sessionInfo:Pa,authToken:ka},Ca="__tld__",Ts="clientDataInCookie",As="clientDataInLocalStorage",Da="clientDataInMemory",Rs="clientDataInSessionStorage",Os=["userId","userTraits","anonymousId","groupId","groupTraits","initialReferrer","initialReferringDomain","sessionInfo","authToken"],he={[x]:Ts,[F]:As,[W]:Da,[V]:Rs},Rn=(t,e)=>{try{return encodeURIComponent(t)}catch(n){e?.error(br,n);return}},On=t=>{try{return decodeURIComponent(t)}catch{return}},La=t=>{let e={},n=t.split(/\s*;\s*/),s;return n[0]&&n.forEach(r=>{s=r.split("=");let i=s[0]?On(s[0]):void 0;i&&(e[i]=s[1]?On(s[1]):void 0)}),e},wa=(t,e,n,s)=>{let r={...n||{}},i=`${Rn(t,s)}=${Rn(e,s)}`;G(e)&&(r.maxage=-1),r.maxage&&(r.expires=new Date(+new Date+r.maxage)),r.path&&(i+=`; path=${r.path}`),r.domain&&(i+=`; domain=${r.domain}`),r.expires&&(i+=`; expires=${r.expires.toUTCString()}`),r.samesite&&(i+=`; samesite=${r.samesite}`),r.secure&&(i+="; secure"),globalThis.document.cookie=i},Ot=()=>{let t=globalThis.document.cookie;return La(t)},Ua=t=>Ot()[t],J=function(t,e,n,s){switch(arguments.length){case 4:case 3:case 2:return wa(t,e,n,s);case 1:return t?Ua(t):Ot();default:return Ot()}},$a=t=>{let e=document.createElement("a");return e.href=t,e.hostname},Ma=t=>{let n=(typeof globalThis.URL!="function"?$a(t):new URL(t).hostname)?.split(".")??[],s=n[n.length-1],r=[];if(n.length===4&&s&&s===parseInt(s,10).toString())return r;if(n.length<=1)return n[0]&&n[0].indexOf("localhost")!==-1?["localhost"]:r;for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r},Ba=t=>{let e=Ma(t);for(let n=0;n<e.length;n+=1){let s=e[n],r=Ca,i={domain:`${s.indexOf("localhost")!==-1?"":"."}${s}`};try{if(J(r,1,i),J(r))return J(r,null,i),s}catch{try{J(r,null,i)}catch{}}}return""},xa=()=>{let t=`.${Ba(globalThis.location.href)}`;return{maxage:Ur,path:"/",domain:!t||t==="."?void 0:t,samesite:"Lax",enabled:!0}},Ga=()=>({enabled:!0}),Fa=()=>({enabled:!0}),Va=()=>({enabled:!0}),_t=class{constructor(e){k(this,"isEnabled",!0);k(this,"length",0);k(this,"data",{});this.options=Va(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isEnabled=!!this.options.enabled,this.options}setItem(e,n){return this.data[e]=n,this.length=Object.keys(this.data).length,n}getItem(e){return e in this.data?this.data[e]:null}removeItem(e){return e in this.data&&delete this.data[e],this.length=Object.keys(this.data).length,null}clear(){this.data={},this.length=0}key(e){return this.keys()[e]??null}keys(){return Object.keys(this.data)}},qe=new _t(te),He={exports:{}},ja=He.exports,_n;function Ha(){return _n||(_n=1,(function(t,e){(function(n,s){t.exports=s()})(ja,function(){function n(f){return f=JSON.stringify(f),!!/^\{[\s\S]*\}$/.test(f)}function s(f){return f===void 0||typeof f=="function"?f+"":JSON.stringify(f)}function r(f){if(typeof f=="string")try{return JSON.parse(f)}catch{return f}}function i(f){return{}.toString.call(f)==="[object Function]"}function a(f){return Object.prototype.toString.call(f)==="[object Array]"}function l(f){var p="_Is_Incognit",h="yes";try{f||(f=window.localStorage),f.setItem(p,h),f.removeItem(p)}catch{var E={};E._data={},E.setItem=function(P,ie){return E._data[P]=String(ie)},E.getItem=function(P){return E._data.hasOwnProperty(P)?E._data[P]:void 0},E.removeItem=function(P){return delete E._data[P]},E.clear=function(){return E._data={}},f=E}finally{f.getItem(p)===h&&f.removeItem(p)}return f}var c=l();function d(){if(!(this instanceof d))return new d}d.prototype={set:function(p,h){if(p&&!n(p))c.setItem(p,s(h));else if(n(p))for(var E in p)this.set(E,p[E]);return this},get:function(p){if(p===void 0){var h={};return this.forEach(function(Ce,be){return h[Ce]=be}),h}if(p.charAt(0)==="?")return this.has(p.substr(1));var E=arguments;if(E.length>1){for(var R={},P=0,ie=E.length;P<ie;P++){var rt=r(c.getItem(E[P]));this.has(E[P])&&(R[E[P]]=rt)}return R}return r(c.getItem(p))},clear:function(){return c.clear(),this},remove:function(p){var h=this.get(p);return c.removeItem(p),h},has:function(p){return{}.hasOwnProperty.call(this.get(),p)},keys:function(){var p=[];return this.forEach(function(h){p.push(h)}),p},forEach:function(p){for(var h=0,E=c.length;h<E;h++){var R=c.key(h);p(R,this.get(R))}return this},search:function(p){for(var h=this.keys(),E={},R=0,P=h.length;R<P;R++)h[R].indexOf(p)>-1&&(E[h[R]]=this.get(h[R]));return E},len:function(){return c.length}};var g=null;function v(f,p){var h=arguments,E=null;if(g||(g=d()),h.length===0)return g.get();if(h.length===1){if(typeof f=="string")return g.get(f);if(n(f))return g.set(f)}if(h.length===2&&typeof f=="string"){if(!p)return g.remove(f);if(p&&typeof p=="string")return g.set(f,p);p&&i(p)&&(E=null,E=p(f,g.get(f)),v.set(f,E))}if(h.length===2&&a(f)&&i(p))for(var R=0,P=f.length;R<P;R++)E=p(f[R],g.get(f[R])),v.set(f[R],E);return v}for(var y in d.prototype)v[y]=d.prototype[y];return v})})(He)),He.exports}var Ka=Ha(),oe=gs(Ka),_s=t=>{let e=["QuotaExceededError","NS_ERROR_DOM_QUOTA_REACHED"],n=[22,1014];return t instanceof DOMException?e.includes(t.name)||n.includes(t.code):!1},pe=(t=F,e,n)=>{let s,r,i=Ir(pt,t),a="unavailable",l=!0,c;try{switch(t){case W:return!0;case x:s=e,r=ya;break;case F:s=e??globalThis.localStorage,r=Sa;break;case V:s=e??globalThis.sessionStorage,r=ba;break;default:return!1}if(s&&(s.setItem(r,"true"),s.getItem(r)))return s.removeItem(r),!0;l=!1}catch(d){l=!1,c=d,_s(d)&&(a="full")}return l||n?.warn(`${i}${a}.`,c),!1},Nt=class{constructor(e){k(this,"isSupportAvailable",!0);k(this,"isEnabled",!0);k(this,"length",0);this.options=Ga(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isSupportAvailable=pe(F),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,n){oe.set(e,n),this.length=oe.len()}getItem(e){let n=oe.get(e);return w(n)?null:n}removeItem(e){oe.remove(e),this.length=oe.len()}clear(){oe.clear(),this.length=0}key(e){return this.keys()[e]??null}keys(){return oe.keys()}},qt=new Nt(te),Pt=class{constructor(e){k(this,"isSupportAvailable",!0);k(this,"isEnabled",!0);k(this,"length",0);this.options=Fa(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isSupportAvailable=pe(V),this.isSupportAvailable&&(this.store=globalThis.sessionStorage),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,n){this.store&&(this.store.setItem(e,n),this.length=this.store.length)}getItem(e){if(!this.store)return null;let n=this.store.getItem(e);return w(n)?null:n}removeItem(e){this.store&&(this.store.removeItem(e),this.length=this.store.length)}clear(){this.store?.clear(),this.length=0}key(e){return this.store?.key(e)??null}keys(){let e=[];if(!this.store)return e;for(let n=0;n<this.store.length;n+=1){let s=this.store.key(n);s!==null&&e.push(s)}return e}},Jt=new Pt(te),kt=class{constructor(e){k(this,"isSupportAvailable",!0);k(this,"isEnabled",!0);k(this,"length",0);this.logger=e}configure(e){return this.options||(this.options=xa()),this.options=L(this.options,e??{}),this.options.sameDomainCookiesOnly&&delete this.options.domain,this.isSupportAvailable=pe(x,this),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,n){return J(e,n,this.options,this.logger),this.length=Object.keys(J()).length,!0}getItem(e){let n=J(e);return w(n)?null:n}removeItem(e){let n=this.setItem(e,null);return this.length=Object.keys(J()).length,n}clear(){}key(e){return this.keys()[e]??null}keys(){return Object.keys(J())}},Zt=new kt(te),H=t=>{switch(t){case F:return qt;case V:return Jt;case W:return qe;case x:return Zt;default:return qe}},Qa=t=>{let e=Zt.configure(t);o.storage.cookie.value={maxage:e.maxage,path:e.path,domain:e.domain,samesite:e.samesite,expires:e.expires,secure:e.secure}},za=t=>{qt.configure(t)},Wa=t=>{qe.configure(t)},Xa=t=>{Jt.configure(t)},Ya=(t={},e={},n={},s={})=>{Qa(t),za(e),Wa(n),Xa(s)},Ct=class{constructor(e,n,s){this.id=e.id,this.name=e.name,this.isEncrypted=e.isEncrypted??!1,this.validKeys=e.validKeys??{},this.engine=n,this.noKeyValidation=Object.keys(this.validKeys).length===0,this.noCompoundKey=e.noCompoundKey,this.originalEngine=this.engine,this.errorHandler=e.errorHandler,this.logger=e.logger,this.pluginsManager=s}createValidKey(e){let{name:n,id:s,validKeys:r,noKeyValidation:i,noCompoundKey:a}=this;if(i)return a?e:[n,s,e].join(".");let l;return Object.values(r).forEach(c=>{c===e&&(l=a?e:[n,s,e].join("."))}),l}swapQueueStoreToInMemoryEngine(){let{name:e,id:n,validKeys:s,noCompoundKey:r}=this,i=H(W);Object.keys(s).forEach(a=>{let l=this.get(s[a]),c=r?a:[e,n,a].join(".");i.setItem(c,l),this.remove(a)}),this.engine=i}set(e,n){let s=this.createValidKey(e);if(s)try{this.engine.setItem(s,this.encrypt(K(n,!1,[],this.logger)))}catch(r){if(_s(r))this.logger.warn(Mi(`Store ${this.id}`)),this.swapQueueStoreToInMemoryEngine(),this.set(e,n);else{let i=Si(e);this.onError(r,i,i)}}}get(e){let n=this.createValidKey(e),s;try{return!n||(s=this.decrypt(this.engine.getItem(n)),Q(s)||s==="")?null:JSON.parse(s)}catch(r){let i=o.storage.encryptionPluginName.value;if(!i||!o.plugins.failedPlugins.value.includes(i)){let l=bi(e);this.onError(r,l,l)}return null}}remove(e){let n=this.createValidKey(e);n&&this.engine.removeItem(n)}getOriginalEngine(){return this.originalEngine}decrypt(e){return Q(e)?null:this.crypto(e,"decrypt")}encrypt(e){return this.crypto(e,"encrypt")}crypto(e,n){if(!this.isEncrypted||!e||typeof e!="string"||sr(e)==="")return e;let r=`storage.${n}`,i=this.pluginsManager?this.pluginsManager.invokeSingle(r,e):e;return typeof i>"u"?e:i??""}onError(e,n,s){this.errorHandler.onError({error:e,context:`Store ${this.id}`,customMessage:n,groupingHash:s})}},qa=(t,e)=>{let n;if(t.consents.preConsent.value.enabled)switch(t.consents.preConsent.value.storage?.strategy){case"none":n=de;break;case"session":e!=="sessionInfo"&&(n=de);break;case"anonymousId":e!=="anonymousId"&&(n=de);break}return n},Dt=class{constructor(e,n,s){k(this,"stores",{});k(this,"isInitialized",!1);this.errorHandler=n,this.logger=s,this.pluginsManager=e}init(){if(this.isInitialized)return;let e=o.loadOptions.value,n={cookieStorageOptions:{samesite:e.sameSiteCookie,secure:e.secureCookie,domain:e.setCookieDomain,sameDomainCookiesOnly:e.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};Ya(Te(L(n.cookieStorageOptions??{},o.storage.cookie?.value??{})),Te(n.localStorageOptions),Te(n.inMemoryStorageOptions),Te(n.sessionStorageOptions)),this.initClientDataStores(),this.isInitialized=!0}initClientDataStores(){this.initializeStorageState(),[W,F,x,V].forEach(n=>{H(n)?.isEnabled&&this.setStore({id:he[n],name:he[n],isEncrypted:!0,noCompoundKey:!0,type:n,errorHandler:this.errorHandler,logger:this.logger})})}initializeStorageState(){let e=o.storage.type.value,n=o.loadOptions.value.storage?.entries,s=o.consents.postConsent.value.storage;(O(s?.type)||O(s?.entries))&&(e=s?.type,n=s?.entries);let r=!0,i={};Os.forEach(a=>{let l=a,c=a,d=n?.[l]?.type,v=qa(o,a)??d??e??St,y=this.getResolvedStorageTypeForEntry(v,a);y!==de&&(r=!1),i={...i,[a]:{type:y,key:fe[c]}}}),U(()=>{o.storage.type.value=e,o.storage.entries.value=i,o.storage.trulyAnonymousTracking.value=r})}getResolvedStorageTypeForEntry(e,n){let s=e;switch(e){case F:H(F)?.isEnabled||(s=W);break;case V:H(V)?.isEnabled||(s=W);break;case W:case de:break;case x:default:H(x)?.isEnabled?s=x:H(F)?.isEnabled?s=F:H(V)?.isEnabled?s=V:s=W;break}return s!==e&&this.logger.warn(Bi(or,n,e,s)),s}setStore(e){let n=H(e.type);return this.stores[e.id]=new Ct(e,n,this.pluginsManager),this.stores[e.id]}getStore(e){return this.stores[e]}},Ja=t=>N(t)&&N(t.source)&&!Q(t.source.id)&&N(t.source.config)&&Array.isArray(t.source.destinations),Za=t=>typeof t=="string"&&is.includes(t),Ns=t=>{let e=new URL(t),{host:n,protocol:s}=e,r=n.split("."),i;return r.length>2?i=`${r[r.length-2]}.${r[r.length-1]}`:i=n,{topDomain:i,protocol:s}},el=t=>{let{topDomain:e,protocol:n}=Ns(t);return`${n}//${e}`},tl=(t,e)=>{let n=e?window.location.origin:el(window.location.href),s=t.startsWith("/")?t.substring(1):t;return`${n}/${s}`},nl=t=>{let{topDomain:e}=Ns(window.location.href);return e===t},me=t=>t?.endsWith("/")?me(t.substring(0,t.length-1)):t,Lt=t=>{try{return new URL(t).host}catch{return null}},Ps=t=>Lt(t)??"",sl=t=>{let e={};try{let n=new URL(t),s="utm_";n.searchParams.forEach((r,i)=>{if(i.startsWith(s)){let a=i.substring(s.length);a==="campaign"&&(a="name"),e[a]=r}})}catch{}return e},rl=t=>{let e=t;try{let n=new URL(t);e=n.origin+n.pathname+n.search}catch{}return e},il=t=>t.replace(/\/{2,}/g,"/"),Ee=t=>{if(!_(t))return!1;try{return m(globalThis.URL)&&new URL(t),Yi.test(t)}catch{return!1}},ut="none",dt="immediate",ol=t=>t?.statsCollection?.errors?.enabled===!0,al=t=>t?.statsCollection?.metrics?.enabled===!0,ll=t=>{let e={sendPageEvent:!1,trackConsent:!1,discardPreConsentEvents:!1};if(N(t)){let n=b(t);e.storage=n.storage,ee(n.integrations)&&(e.integrations=n.integrations),e.discardPreConsentEvents=n.discardPreConsentEvents===!0,e.sendPageEvent=n.sendPageEvent===!0,e.trackConsent=n.trackConsent===!0,ee(n.consentManagement)&&(e.consentManagement=L(n.consentManagement,{enabled:o.consents.enabled.value}))}return e},Nn=t=>ee(t)||Array.isArray(t),cl=(t,e)=>{let{provider:n}=t,s=n?bt[n]:void 0;return n&&!s&&(e.error(oi(j,n,bt)),n=void 0),{provider:n,consentManagerPluginName:s}},ks=(t,e)=>{let n,s=[],r=[],i=!1,a,l=t?.enabled===!0;ee(t)&&l&&({provider:a,consentManagerPluginName:n}=cl(t,e),Nn(t.allowedConsentIds)&&(s=t.allowedConsentIds,i=!0),Nn(t.deniedConsentIds)&&(r=t.deniedConsentIds,i=!0));let c={allowedConsentIds:s,deniedConsentIds:r};return l=l&&!!n,{provider:a,consentManagerPluginName:n,initialized:i,enabled:l,consentsData:c}},ul=()=>{let t=document.querySelector("script[data-rsa-write-key]");if(t&&t.dataset.rsaWriteKey===o.lifecycle.writeKey.value)return t.src;let e=document.getElementsByTagName("script"),n=/(?:^|\/)rsa(\.min)?\.js$/;for(let s of e){let r=s.getAttribute("src");if(r&&n.test(r))return r}},dl=t=>{o.reporting.isErrorReportingEnabled.value=ol(t.source.config)&&!hr(),o.reporting.isMetricsReportingEnabled.value=al(t.source.config)},gl=t=>{let{useServerSideCookies:e,dataServiceEndpoint:n,storage:s,setCookieDomain:r,sameDomainCookiesOnly:i}=o.loadOptions.value,a=s?.cookie,l=!1,c;if(e){l=e;let d=a.domain??r,g=O(d)&&!nl(tn(d))||i,v=tl(n??Zi,g);if(Ee(v)){c=me(v);let y=Lt(window.location.href),f=Lt(v);y!==f&&(a={...a,samesite:"None",secure:!0}),!i&&g&&f!==tn(d)&&(l=!1,t.warn(_i(j,d,f)))}else l=!1}return{sscEnabled:l,cookieOptions:a,finalDataServiceUrl:c}},fl=t=>{let{storage:e}=o.loadOptions.value,n=e?.type;O(n)&&!Za(n)&&(t.warn(Ai(j,n,St)),n=St);let s=e?.encryption?.version,r=s&&Ge[s];!w(s)&&w(r)?(t.warn(Ri(j,s,Ge,le)),s=le):w(s)&&(s=le);let i=e?.migrate,a=i&&s===le;i===!0&&a!==i&&t.warn(Oi(j,s,le));let{sscEnabled:l,finalDataServiceUrl:c,cookieOptions:d}=gl(t);U(()=>{o.storage.type.value=n,o.storage.cookie.value=d,o.serverCookies.isEnabledServerSideCookies.value=l,o.serverCookies.dataServiceUrl.value=c,o.storage.encryptionPluginName.value=Ge[s],o.storage.migrate.value=a})},hl=t=>{let{provider:e,consentManagerPluginName:n,initialized:s,enabled:r,consentsData:i}=ks(o.loadOptions.value.consentManagement,t),a=o.loadOptions.value.preConsent,l=a?.storage?.strategy??ut,c=["none","session","anonymousId"];O(l)&&!c.includes(l)&&(l=ut,t.warn(Vi(j,a?.storage?.strategy,ut)));let d=a?.events?.delivery??dt,g=["immediate","buffer"];O(d)&&!g.includes(d)&&(d=dt,t.warn(ji(j,a?.events?.delivery,dt))),U(()=>{o.consents.activeConsentManagerPluginName.value=n,o.consents.initialized.value=s,o.consents.enabled.value=r,o.consents.data.value=i,o.consents.provider.value=e,o.consents.preConsent.value={enabled:o.loadOptions.value.preConsent?.enabled===!0&&s===!1&&r===!0,storage:{strategy:l},events:{delivery:d}}})},pl=t=>{let e=o.consents.resolutionStrategy.value,n;N(t.consentManagementMetadata)&&(o.consents.provider.value&&(e=t.consentManagementMetadata.providers.find(s=>s.provider===o.consents.provider.value)?.resolutionStrategy??o.consents.resolutionStrategy.value),n=t.consentManagementMetadata),o.consents.provider.value==="custom"&&(e=void 0),U(()=>{o.consents.metadata.value=b(n),o.consents.resolutionStrategy.value=e})},vl=t=>{if(o.dataPlaneEvents.deliveryEnabled.value){let e="XhrQueue",n=e;o.loadOptions.value.useBeacon&&(o.capabilities.isBeaconAvailable.value?n="BeaconQueue":(n=e,t.warn(ki(j)))),U(()=>{o.dataPlaneEvents.eventsQueuePluginName.value=n})}},ml=(t,e,n,s,r)=>{let i=new URLSearchParams({p:Xn,v:Ne,build:ke,writeKey:e,lockIntegrationsVersion:n.toString(),lockPluginsVersion:s.toString()}),a=ds,l=i,c="/sourceConfig/",d="";if(Ee(t)){let g=new URL(t);me(g.pathname).endsWith("/sourceConfig")||(g.pathname=`${me(g.pathname)}/sourceConfig/`),g.pathname=il(g.pathname),i.forEach((v,y)=>{g.searchParams.get(y)===null&&g.searchParams.set(y,v)}),a=g.origin,c=g.pathname,l=g.searchParams,d=g.hash}else r.warn(Gi(j,t));return`${a}${c}?${l}${d}`},El=t=>t.map(e=>({id:e.id,displayName:e.destinationDefinition.displayName,enabled:e.enabled,config:e.config,shouldApplyDeviceModeTransformation:e.shouldApplyDeviceModeTransformation??!1,propagateEventsUntransformedOnError:e.propagateEventsUntransformedOnError??!1,userFriendlyId:ca(e.destinationDefinition.displayName,e.id),isCustomIntegration:e.destinationDefinition.displayName===to})),Cs=(t,e,n,s,r,i,a)=>{let l;if(i){if(!Ee(i))return a.error(ii(j,t,i)),null;l=me(i)}else if(l=n,o.context.app.value.installType==="cdn"){let c=ul();c&&(l=c.split("/").slice(0,-1).concat(e).join("/"))}return r&&(l=l.replace(new RegExp(`/${Yt}/${ke}/${e}$`),`/${s}/${ke}/${e}`)),l},yl=(t,e,n,s)=>Cs("integrations",nt,cs,t,e,n,s),Sl=(t,e,n,s)=>Cs("plugins",ls,us,t,e,n,s),wt=class{constructor(e,n,s){this.errorHandler=n,this.logger=s,this.httpClient=e,this.onError=this.onError.bind(this),this.processConfig=this.processConfig.bind(this)}attachEffects(){X(()=>{this.logger.setMinLogLevel(o.lifecycle.logLevel.value)})}init(){let{logLevel:e,configUrl:n,lockIntegrationsVersion:s,lockPluginsVersion:r,destSDKBaseURL:i,pluginsSDKBaseURL:a,integrations:l}=o.loadOptions.value,c=yl(Ne,s,i,this.logger);if(G(c))return;let d;d=Sl(Ne,r,a,this.logger),d!==null&&(this.attachEffects(),o.lifecycle.activeDataplaneUrl.value=me(o.lifecycle.dataPlaneUrl.value),fl(this.logger),hl(this.logger),vl(this.logger),U(()=>{o.lifecycle.integrationsCDNPath.value=c,o.lifecycle.pluginsCDNPath.value=d,e&&(o.lifecycle.logLevel.value=e),o.lifecycle.sourceConfigUrl.value=ml(n,o.lifecycle.writeKey.value,s,r,this.logger),o.metrics.metricsServiceUrl.value=`${o.lifecycle.activeDataplaneUrl.value}/${eo}`,o.nativeDestinations.loadOnlyIntegrations.value=l}),this.getConfig())}onError(e,n,s){this.errorHandler.onError({error:e,context:j,customMessage:n,groupingHash:s})}processConfig(e,n){if(!O(e)){O(n)?this.onError(n.error,pn):this.onError(new Error(pn));return}let s;try{_(e)?s=JSON.parse(e):s=e}catch(i){this.onError(i,fn);return}if(!Ja(s)){this.onError(new Error(fn));return}if(s.source.enabled===!1){this.logger.error(ei);return}dl(s);let r=s.source.destinations.length>0?El(s.source.destinations):[];U(()=>{o.source.value={config:s.source.config,name:s.source.name,id:s.source.id,workspaceId:s.source.workspaceId},o.nativeDestinations.configuredDestinations.value=r,o.plugins.pluginsToLoadFromConfig.value=o.loadOptions.value.plugins??[],pl(s),o.lifecycle.status.value="configured"})}getConfig(){let e=o.loadOptions.value.getSourceConfig;if(e){if(!m(e)){this.logger.error(ri(j));return}let n=e();n instanceof Promise?n.then(s=>this.processConfig(s)).catch(s=>{this.onError(s,"SourceConfig")}):this.processConfig(n)}else this.httpClient.getAsyncData({url:o.lifecycle.sourceConfigUrl.value,options:{headers:{"Content-Type":void 0}},callback:this.processConfig})}},bl=()=>{let t=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return t?.[1]?t[1]:"NA"},Ds=(t=()=>document)=>t()?.referrer||"$direct",Il=(t=()=>document)=>{let n=t().getElementsByTagName("link"),s="";for(let r=0;n[r];r+=1){let i=n[r];if(i.getAttribute("rel")==="canonical"&&!s){s=i.getAttribute("href")??"";break}}return s},Tl=(t=()=>globalThis.navigator)=>{let e=t();if(w(e))return null;let{userAgent:n}=e,{brave:s}=e;if(s&&Object.getPrototypeOf(s).isBrave){let r=n.match(/(chrome)\/([\w.]+)/i);r&&(n=`${n} Brave/${r[2]}`)}return n},Al=(t=()=>globalThis.navigator)=>{let e=t();return w(e)?null:e.language??e.browserLanguage},Ls=(t=()=>globalThis.location,e=()=>document)=>{let n=t(),s=Il(e),r=n.pathname,{href:i}=n,a=i,{search:l}=n;if(s)try{let v=new URL(s);v.search===""?a=s+l:a=s,r=v.pathname}catch{}let c=rl(a),{title:d}=e(),g=Ds(e);return{path:r,referrer:g,referring_domain:Ps(g),search:l,title:d,url:c,tab_url:i}},Rl=(t,e="none")=>{e==="none"&&t(void 0),e==="default"&&t(navigator.userAgentData),e==="full"&&navigator.userAgentData?.getHighEntropyValues(["architecture","bitness","brands","mobile","model","platform","platformVersion","uaFullVersion","fullVersionList","wow64"]).then(n=>{t(n)}).catch(()=>{t()})},Ol=()=>{let t=globalThis.document.createElement("div");return t.setAttribute("data-a-b","c"),t.dataset?t.dataset.aB==="c":!1},Ut={URL:()=>!m(globalThis.URL)||!m(globalThis.URLSearchParams),Promise:()=>!m(globalThis.Promise),"Number.isNaN":()=>!m(globalThis.Number.isNaN),"Number.isInteger":()=>!m(globalThis.Number.isInteger),"Array.from":()=>!m(globalThis.Array.from),"Array.prototype.find":()=>!m(globalThis.Array.prototype.find),"Array.prototype.includes":()=>!m(globalThis.Array.prototype.includes),"String.prototype.endsWith":()=>!m(globalThis.String.prototype.endsWith),"String.prototype.startsWith":()=>!m(globalThis.String.prototype.startsWith),"String.prototype.includes":()=>!m(globalThis.String.prototype.includes),"String.prototype.replaceAll":()=>!m(globalThis.String.prototype.replaceAll),"String.fromCodePoint":()=>!m(globalThis.String.fromCodePoint),"Object.entries":()=>!m(globalThis.Object.entries),"Object.values":()=>!m(globalThis.Object.values),"Object.assign":()=>!m(globalThis.Object.assign),"Object.fromEntries":()=>!m(globalThis.Object.fromEntries),"Element.prototype.dataset":()=>!Ol(),TextEncoder:()=>!m(globalThis.TextEncoder)||!m(globalThis.TextDecoder),requestAnimationFrame:()=>!m(globalThis.requestAnimationFrame)||!m(globalThis.cancelAnimationFrame),CustomEvent:()=>!m(globalThis.CustomEvent),"navigator.sendBeacon":()=>!m(globalThis.navigator.sendBeacon),ArrayBuffer:()=>!m(globalThis.Uint8Array),Set:()=>!m(globalThis.Set),atob:()=>!m(globalThis.atob)},_l=()=>{let t=Object.keys(Ut),e=!1;for(let n=0;n<t.length;n++){let s=Ut[t[n]];if(m(s)&&s()){e=!0;break}}return e},Nl="https://polyfill-fastly.io/v3/polyfill.min.js",Pl=`${Nl}?version=3.111.0&features=${Object.keys(Ut).join("%2C")}`,kl=10*1e3,Pn="rudderstackPolyfill",Cl=()=>!Q(globalThis.crypto)&&m(globalThis.crypto.getRandomValues),kn=()=>!Q(globalThis.navigator.userAgentData),Dl=()=>!Q(globalThis.navigator.sendBeacon)&&m(globalThis.navigator.sendBeacon),Cn=()=>{let t={density:0,width:0,height:0,innerWidth:0,innerHeight:0};return t={width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight},t},$t=class{constructor(e,n,s){this.httpClient=e,this.errorHandler=n,this.logger=s,this.externalSrcLoader=new Xe(this.logger),this.onError=this.onError.bind(this),this.onReady=this.onReady.bind(this)}init(){this.prepareBrowserCapabilities(),this.attachWindowListeners()}detectBrowserCapabilities(){U(()=>{o.capabilities.storage.isCookieStorageAvailable.value=pe(x,H(x),this.logger),o.capabilities.storage.isLocalStorageAvailable.value=pe(F,void 0,this.logger),o.capabilities.storage.isSessionStorageAvailable.value=pe(V,void 0,this.logger),o.capabilities.isBeaconAvailable.value=Dl(),o.capabilities.isUaCHAvailable.value=kn(),o.capabilities.isCryptoAvailable.value=Cl(),o.capabilities.isIE11.value=Kn(),o.capabilities.isOnline.value=globalThis.navigator.onLine,o.context.userAgent.value=Tl(),o.context.locale.value=Al(),o.context.screen.value=Cn(),o.context.timezone.value=bl(),kn()&&Rl(e=>{o.context["ua-ch"].value=e},o.loadOptions.value.uaChTrackLevel)}),X(()=>{o.loadOptions.value.sendAdblockPage===!0&&o.lifecycle.sourceConfigUrl.value!==void 0&&vs(this.httpClient)})}prepareBrowserCapabilities(){o.capabilities.isLegacyDOM.value=_l();let e=o.loadOptions.value.polyfillURL,n=Pl;if(ve(e)&&(Ee(e)?n=e:this.logger.warn(Qi(pt,e))),o.loadOptions.value.polyfillIfRequired&&o.capabilities.isLegacyDOM.value&&Ee(n)){let r=n!==o.loadOptions.value.polyfillURL;if(r){let i=`RS_polyfillCallback_${o.lifecycle.writeKey.value}`,a=()=>{this.onReady(),delete globalThis[i]};globalThis[i]=a,n=`${n}&callback=${i}`}this.externalSrcLoader.loadJSFile({url:n,id:Pn,async:!0,timeout:kl,callback:i=>{i?r||this.onReady():this.onError(new Error(Fi(Pn,n)))}})}else this.onReady()}attachWindowListeners(){globalThis.addEventListener("offline",()=>{o.capabilities.isOnline.value=!1}),globalThis.addEventListener("online",()=>{o.capabilities.isOnline.value=!0}),globalThis.addEventListener("resize",Br(()=>{o.context.screen.value=Cn()},this))}onReady(){this.detectBrowserCapabilities(),o.lifecycle.status.value="browserCapabilitiesReady"}onError(e,n){this.errorHandler.onError({error:e,context:pt,groupingHash:n})}},Ll="web",wl=["integrations","anonymousId","originalTimestamp"],Dn=["library","consentManagement","userAgent","ua-ch","screen"],gt=["id","anonymous_id","user_id","sent_at","timestamp","received_at","original_timestamp","event","event_text","channel","context_ip","context_request_ip","context_passed_ip","group_id","previous_id"],ws=t=>typeof t=="number"&&!Number.isNaN(t),Ul=(t,e)=>e.toString().length>=t,Je=t=>ws(t)&&t>=0&&Number.isInteger(t),Ln=10,Us=t=>{let{cutOff:e}=t,n=Date.now();return!!(e?.enabled&&e.expiresAt&&n>e.expiresAt)},wn=t=>!t.expiresAt||Date.now()>t.expiresAt||Us(t),$l=()=>Date.now(),Ml=(t,e)=>!t||!Je(t)||!Ul(Ln,t)?(e.warn($i(ae,t,Ln)),!1):!0,Bl=t=>{if(t?.enabled)return t.expiresAt??(Je(t.duration)?Date.now()+t.duration:void 0)},xl=t=>{let{timeout:e,cutOff:n}=t,s=Date.now();return{id:s,expiresAt:s+e,timeout:e,autoTrack:!0,...n&&{cutOff:n}}},Gl=(t,e)=>({id:Ml(t,e)?t:$l(),sessionStart:void 0,manualTrack:!0}),Re=t=>t===x||t===F||t===V||t===W,Mt=()=>Ze(),Fl=t=>{if(Js(t)){let{entries:e,...n}=lt;return{...n,entries:{...e,anonymousId:t}}}return N(t)&&N(t.entries)?L(lt,t):{...lt}},Vl=t=>{let e=Ls(),n={};return Object.keys(e).forEach(s=>{n[s]=t?.[s]||e[s]}),n.initial_referrer=t?.initial_referrer||o.session.initialReferrer.value,n.initial_referring_domain=t?.initial_referring_domain||o.session.initialReferringDomain.value,n},jl=(t,e)=>{let n=e?.page||{},s=t,r=Ls();return Object.keys(r).forEach(i=>{w(s[i])&&(s[i]=n[i]||r[i])}),w(s.initial_referrer)&&(s.initial_referrer=n.initial_referrer||o.session.initialReferrer.value),w(s.initial_referring_domain)&&(s.initial_referring_domain=n.initial_referring_domain||o.session.initialReferringDomain.value),s},ft=(t,e,n)=>{N(t)&&Object.keys(t).forEach(s=>{(gt.includes(s)||gt.includes(s.toLowerCase()))&&n.warn(Ni(Hn,s,e,gt))})},Hl=(t,e)=>{let{properties:n,traits:s,context:r}=t,{traits:i}=r;ft(n,"properties",e),ft(s,"traits",e),ft(i,"context.traits",e)},Kl=(t,e)=>{e.anonymousId&&_(e.anonymousId)&&(t.anonymousId=e.anonymousId),ee(e.integrations)&&(t.integrations=e.integrations),e.originalTimestamp&&_(e.originalTimestamp)&&(t.originalTimestamp=e.originalTimestamp)},Ql=(t,e,n)=>{let s=t;return Object.keys(e).forEach(r=>{if(!wl.includes(r)&&!Dn.includes(r))if(r!=="context")s=L(s,{[r]:e[r]});else if(!w(e[r])&&N(e[r])){let i={};Object.keys(e[r]).forEach(a=>{Dn.includes(a)||(i[a]=e[r][a])}),s=L(s,{...i})}else n.warn(Pi(Hn))}),s},zl=(t,e,n)=>{N(e)&&(Kl(t,e),t.context=Ql(t.context,e,n))},Wl=t=>{let e;return o.loadOptions.value.useGlobalIntegrationsConfigInEvents?e=o.consents.postConsent.value.integrations??o.nativeDestinations.loadOnlyIntegrations.value:t?e=t:e=as,b(e)},Ie=(t,e,n,s)=>{let r={channel:Ll,context:{traits:b(o.session.userTraits.value),sessionId:o.session.sessionInfo.value.id||void 0,sessionStart:o.session.sessionInfo.value.sessionStart||void 0,...o.consents.enabled.value&&{consentManagement:{deniedConsentIds:b(o.consents.data.value.deniedConsentIds),allowedConsentIds:b(o.consents.data.value.allowedConsentIds),provider:o.consents.provider.value,resolutionStrategy:o.consents.resolutionStrategy.value}},"ua-ch":o.context["ua-ch"].value,app:o.context.app.value,library:o.context.library.value,userAgent:o.context.userAgent.value,os:o.context.os.value,locale:o.context.locale.value,screen:o.context.screen.value,campaign:sl(globalThis.location.href),page:Vl(n),timezone:o.context.timezone.value,...o.autoTrack.enabled.value&&{autoTrack:{...o.autoTrack.pageLifecycle.enabled.value&&{page:{pageViewId:o.autoTrack.pageLifecycle.pageViewId.value}}}}},originalTimestamp:vr(),messageId:Ze(),userId:t.userId||o.session.userId.value};Re(o.storage.entries.value.anonymousId?.type)?r.anonymousId=o.session.anonymousId.value:r.anonymousId=Mt(),o.storage.trulyAnonymousTracking.value&&(r.context.trulyAnonymousTracking=!0),t.type==="identify"&&(r.context.traits=o.storage.entries.value.userTraits?.type!==de?b(o.session.userTraits.value):t.context.traits),t.type==="group"&&((t.groupId||o.session.groupId.value)&&(r.groupId=t.groupId||o.session.groupId.value),(t.traits||o.session.groupTraits.value)&&(r.traits=o.storage.entries.value.groupTraits?.type!==de?b(o.session.groupTraits.value):t.traits));let i=L(t,r);return i.event===void 0&&(i.event=null),i.properties===void 0&&(i.properties=null),zl(i,e,s),Hl(i,s),i.integrations=Wl(i.integrations),i},Bt=class{constructor(e){this.logger=e}generatePageEvent(e,n,s,r){let i=s??{};return i=jl(i,r),Ie({properties:i,name:n,category:e,type:"page"},r,i,this.logger)}generateTrackEvent(e,n,s){return Ie({properties:n,event:e,type:"track"},s,void 0,this.logger)}generateIdentifyEvent(e,n,s){return Ie({userId:e,type:"identify",context:{traits:n}},s,void 0,this.logger)}generateAliasEvent(e,n,s){let i=Ie({previousId:n,type:"alias"},s,void 0,this.logger);return i.userId=e??i.userId,i}generateGroupEvent(e,n,s){let r={type:"group"};return e&&(r.groupId=e),n&&(r.traits=n),Ie(r,s,void 0,this.logger)}create(e){let n;switch(e.type){case"page":n=this.generatePageEvent(e.category,e.name,e.properties,e.options);break;case"track":n=this.generateTrackEvent(e.name,e.properties,e.options);break;case"identify":n=this.generateIdentifyEvent(e.userId,e.traits,e.options);break;case"alias":n=this.generateAliasEvent(e.to,e.from,e.options);break;default:n=this.generateGroupEvent(e.groupId,e.traits,e.options);break}return n}},xt=class{constructor(e,n,s,r){this.eventRepository=e,this.userSessionManager=n,this.errorHandler=s,this.logger=r,this.eventFactory=new Bt(this.logger)}init(){this.eventRepository.init()}resume(){this.eventRepository.resume()}addEvent(e){this.userSessionManager.refreshSession();let n=this.eventFactory.create(e);this.eventRepository.enqueue(n,e.callback)}},Gt=class{constructor(e,n,s,r,i){this.storeManager=n,this.pluginsManager=e,this.logger=i,this.errorHandler=r,this.httpClient=s,this.onError=this.onError.bind(this),this.serverSideCookieDebounceFuncs={},this.serverSideCookiesRequestInProgress={}}init(){this.syncStorageDataToState(),this.registerEffects()}syncStorageDataToState(){this.migrateStorageIfNeeded(),this.migrateDataFromPreviousStorage(),this.setUserId(this.getUserId()),this.setUserTraits(this.getUserTraits()),this.setGroupId(this.getGroupId()),this.setGroupTraits(this.getGroupTraits());let{externalAnonymousIdCookieName:e,anonymousIdOptions:n}=o.loadOptions.value,s;ve(e)&&typeof e=="string"&&(s=this.getExternalAnonymousIdByCookieName(e)),this.setAnonymousId(s??this.getAnonymousId(n)),this.setAuthToken(this.getAuthToken()),this.setInitialReferrerInfo(),this.configureSessionTracking()}configureSessionTracking(){let e;if(this.isPersistenceEnabledForStorageEntry("sessionInfo")){let n=this.getConfiguredSessionTrackingInfo(),s=this.getSessionInfo()??A.sessionInfo;e={autoTrack:n.autoTrack&&s.manualTrack!==!0,timeout:n.timeout,manualTrack:s.manualTrack,expiresAt:s.expiresAt,id:s.id,sessionStart:s.sessionStart},!e.autoTrack&&e.manualTrack!==!0?e=A.sessionInfo:n.cutOff?.enabled===!0&&(e.cutOff={enabled:!0,duration:n.cutOff.duration,expiresAt:s.cutOff?.expiresAt})}else e=A.sessionInfo;o.session.sessionInfo.value=e,o.session.sessionInfo.value.autoTrack&&this.startOrRenewAutoTracking(o.session.sessionInfo.value)}setInitialReferrerInfo(){let e=this.getInitialReferrer(),n=this.getInitialReferringDomain();if(e&&n)this.setInitialReferrer(e),this.setInitialReferringDomain(n);else{let s=e||Ds();this.setInitialReferrer(s),this.setInitialReferringDomain(Ps(s))}}isPersistenceEnabledForStorageEntry(e){return Re(o.storage.entries.value[e]?.type)}migrateDataFromPreviousStorage(){let e=o.storage.entries.value,n=[x,F,V];Object.keys(e).forEach(s=>{let r=s,i=e[r]?.type,a=this.storeManager?.getStore(he[i]);a&&n.forEach(l=>{let c=this.storeManager?.getStore(he[l]);if(c&&l!==i){let d=c.get(fe[r]);qs(d)&&a.set(fe[r],d),c.remove(fe[r])}})})}migrateStorageIfNeeded(e,n){if(!o.storage.migrate.value)return;let s=e??[];s.length===0&&[Ts,As,Rs].forEach(a=>{let l=this.storeManager?.getStore(a);l&&s.push(l)}),(n??Object.keys(fe)).forEach(i=>{let a=fe[i];s.forEach(l=>{let c=this.pluginsManager?.invokeSingle("storage.migrate",a,l.engine,this.errorHandler,this.logger);Q(c)||l.set(a,c)})})}getConfiguredSessionTrackingInfo(){let e=o.loadOptions.value.sessions.autoTrack!==!1;if(!e)return{autoTrack:e};let n,s=o.loadOptions.value.sessions?.timeout;Je(s)?n=s:(this.logger.warn(Ci(ae,s,vt)),n=vt),n===0&&(this.logger.warn(wi(ae)),e=!1),n>0&&n<un&&this.logger.warn(Ui(ae,n,un));let r=this.getCutOffInfo(n);return{timeout:n,autoTrack:e,cutOff:r}}getCutOffInfo(e){let n=o.loadOptions.value.sessions.cutOff,s,r=!1;return n.enabled===!0&&(s=n.duration,r=!0,Je(s)?s<e&&(this.logger.warn(Li(ae,s,e)),r=!1):(this.logger.warn(Di(ae,s,cn)),s=cn)),{enabled:r,duration:s}}onError(e,n,s){this.errorHandler.onError({error:e,context:ae,customMessage:n,groupingHash:s})}getEncryptedCookieData(e,n){let s=[];return e.forEach(r=>{let i=n?.encrypt(K(r.value,!1,[],this.logger));ve(i)&&s.push({name:r.name,value:i})}),s}makeRequestToSetCookie(e,n){this.httpClient?.getAsyncData({url:o.serverCookies.dataServiceUrl.value,options:{method:"POST",data:K({reqType:"setCookies",workspaceId:o.source.value?.workspaceId,data:{options:{maxAge:o.storage.cookie.value?.maxage,path:o.storage.cookie.value?.path,domain:o.storage.cookie.value?.domain,sameSite:o.storage.cookie.value?.samesite,secure:o.storage.cookie.value?.secure,expires:o.storage.cookie.value?.expires},cookies:e}}),sendRawData:!0,withCredentials:!0},isRawResponse:!0,callback:n})}setServerSideCookies(e,n,s){let r=Object.keys(e),i=()=>r.map(d=>({name:e[d].name,value:o.session[d].value})),a={};r.forEach(d=>{a[e[d].name]=s?.get(e[d].name)});let l=()=>{r.forEach(d=>{this.serverSideCookiesRequestInProgress[d]=!1})},c=()=>{i().forEach(d=>{n&&n(d.name,d.value)})};try{let d={};r.forEach(v=>{d[e[v].name]=o.session[v].value});let g=this.getEncryptedCookieData(i(),s);g.length>0?this.makeRequestToSetCookie(g,(v,y)=>{l(),y?.xhr?.status===200?i().forEach(f=>{let p=a[f.name],h=s?.get(f.name);K(d[f.name],!1,[])!==K(h,!1,[])&&(G(p)&&G(h)&&this.logger.error(Ti(f.name)),n&&n(f.name,f.value))}):(this.logger.error(Ii(y?.xhr?.status)),c())}):(c(),l())}catch(d){this.onError(d,vn,vn),c(),l()}}syncValueToStorage(e){let n=o.storage.entries.value,s=n[e]?.type;if(Re(s)){let r=this.storeManager.getStore(he[s]),i=n[e]?.key,a=o.session[e].value;a&&(_(a)||ee(a))?o.serverCookies.isEnabledServerSideCookies.value&&s===x?(this.serverSideCookiesRequestInProgress[e]=!0,this.serverSideCookieDebounceFuncs[e]&&globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[e]),this.serverSideCookieDebounceFuncs[e]=globalThis.setTimeout(()=>{let l={[e]:{name:i}};this.setServerSideCookies(l,(c,d)=>{r?.set(c,d)},r)},ro)):r?.set(i,a):r?.remove(i)}}registerEffects(){Os.forEach(e=>{X(()=>{this.syncValueToStorage(e)})})}setAnonymousId(e,n){let s=e;(!_(e)||!s)&&(s=void 0),this.isPersistenceEnabledForStorageEntry("anonymousId")?(!s&&n&&(s=this.pluginsManager?.invokeSingle("userSession.anonymousIdGoogleLinker",n)),s=s||Mt()):s=A.anonymousId,o.session.anonymousId.value=s}getAnonymousId(e){let n=o.storage.entries.value.anonymousId?.type;if(Re(n)){let s=o.session.anonymousId.value;(!s||s===A.anonymousId)&&(s=this.getEntryValue("anonymousId")),!s&&e&&(s=this.pluginsManager?.invokeSingle("storage.getAnonymousId",H,e)),o.session.anonymousId.value=s||Mt()}return o.session.anonymousId.value}getEntryValue(e){let n=o.storage.entries.value,s=n[e]?.type;if(Re(s)){let r=this.storeManager?.getStore(he[s]);this.migrateStorageIfNeeded([r],[e]);let i=n[e]?.key;return r?.get(i)??null}return null}getExternalAnonymousIdByCookieName(e){let n=H(x);return n?.isEnabled?n.getItem(e)??null:null}getUserSessionValue(e){return this.serverSideCookiesRequestInProgress[e]?o.session[e].value:this.getEntryValue(e)}getUserId(){return this.getUserSessionValue("userId")}getUserTraits(){return this.getUserSessionValue("userTraits")}getGroupId(){return this.getUserSessionValue("groupId")}getGroupTraits(){return this.getUserSessionValue("groupTraits")}getInitialReferrer(){return this.getUserSessionValue("initialReferrer")}getInitialReferringDomain(){return this.getUserSessionValue("initialReferringDomain")}getSessionInfo(){return this.getUserSessionValue("sessionInfo")}getAuthToken(){return this.getUserSessionValue("authToken")}getSessionId(){let e=this.getSessionInfo()??A.sessionInfo;return e.autoTrack&&!wn(e)||e.manualTrack?e.id??null:null}refreshSession(){let e=this.getSessionInfo()??A.sessionInfo;(e.autoTrack||e.manualTrack)&&(e.autoTrack&&(this.startOrRenewAutoTracking(e),e=o.session.sessionInfo.value),e.sessionStart===void 0?e={...e,sessionStart:!0}:e.sessionStart&&(e={...e,sessionStart:!1})),o.session.sessionInfo.value=e,o.lifecycle.status.value!=="readyExecuted"&&this.syncValueToStorage("sessionInfo")}resetAndStartNewSession(){let e=o.session,{manualTrack:n,autoTrack:s,timeout:r,cutOff:i}=e.sessionInfo.value;if(s){let a={...A.sessionInfo,timeout:r};i&&(a.cutOff={enabled:i.enabled,duration:i.duration}),e.sessionInfo.value=a,this.startOrRenewAutoTracking(e.sessionInfo.value)}else n&&this.startManualTrackingInternal()}reset(e){let{session:n}=o,s=Fl(e);U(()=>{Object.keys(A).forEach(r=>{let i=r;if(s.entries[i]===!0)switch(r){case"anonymousId":this.setAnonymousId();break;case"sessionInfo":this.resetAndStartNewSession();break;default:n[i].value=A[i];break}})})}setUserId(e){o.session.userId.value=this.isPersistenceEnabledForStorageEntry("userId")&&e?e:A.userId}setUserTraits(e){o.session.userTraits.value=this.isPersistenceEnabledForStorageEntry("userTraits")&&N(e)?L(o.session.userTraits.value??A.userTraits,e):A.userTraits}setGroupId(e){o.session.groupId.value=this.isPersistenceEnabledForStorageEntry("groupId")&&e?e:A.groupId}setGroupTraits(e){o.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry("groupTraits")&&N(e)?L(o.session.groupTraits.value??A.groupTraits,e):A.groupTraits}setInitialReferrer(e){o.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry("initialReferrer")&&e?e:A.initialReferrer}setInitialReferringDomain(e){o.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry("initialReferringDomain")&&e?e:A.initialReferringDomain}startOrRenewAutoTracking(e){let n=e;if(wn(e))n=xl(e);else{let s=Date.now(),r=e.timeout;n.expiresAt=s+r}if(Us(n)&&(n.cutOff.expiresAt=void 0),n.cutOff){let s=Bl(n.cutOff);n.cutOff.expiresAt=s}o.session.sessionInfo.value=n}start(e){o.session.sessionInfo.value=Gl(e,this.logger)}startManualTrackingInternal(){this.start(Date.now())}end(){o.session.sessionInfo.value=A.sessionInfo}setAuthToken(e){o.session.authToken.value=this.isPersistenceEnabledForStorageEntry("authToken")&&e?e:A.authToken}},Xl=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],Yl=(t,e)=>{let n=b(e);return _(n.setCookieDomain)||(n.setCookieDomain=void 0),["Strict","Lax","None"].includes(n.sameSiteCookie)||(n.sameSiteCookie=void 0),n.secureCookie=z(n.secureCookie,t.secureCookie),n.sameDomainCookiesOnly=z(n.sameDomainCookiesOnly,t.sameDomainCookiesOnly),["none","default","full"].includes(n.uaChTrackLevel)||(n.uaChTrackLevel=void 0),n.integrations=Y(n.integrations),Array.isArray(n.plugins)||(n.plugins=Xl),n.useGlobalIntegrationsConfigInEvents=z(n.useGlobalIntegrationsConfigInEvents,t.useGlobalIntegrationsConfigInEvents),n.bufferDataPlaneEventsUntilReady=z(n.bufferDataPlaneEventsUntilReady,t.bufferDataPlaneEventsUntilReady),n.sendAdblockPage=z(n.sendAdblockPage,t.sendAdblockPage),n.useServerSideCookies=z(n.useServerSideCookies,t.useServerSideCookies),_(n.dataServiceEndpoint)||(n.dataServiceEndpoint=void 0),n.sendAdblockPageOptions=Y(n.sendAdblockPageOptions),n.loadIntegration=z(n.loadIntegration,t.loadIntegration),ee(n.storage)?(n.storage.migrate=z(n.storage.migrate,t.storage?.migrate),n.storage.cookie=Y(n.storage.cookie),n.storage.encryption=Y(n.storage.encryption),n.storage=Qe(n.storage)):n.storage=void 0,n.destinationsQueueOptions=Y(n.destinationsQueueOptions),n.queueOptions=Y(n.queueOptions),n.lockIntegrationsVersion=z(n.lockIntegrationsVersion,t.lockIntegrationsVersion),n.lockPluginsVersion=z(n.lockPluginsVersion,t.lockPluginsVersion),ws(n.dataPlaneEventsBufferTimeout)||(n.dataPlaneEventsBufferTimeout=void 0),n.beaconQueueOptions=Y(n.beaconQueueOptions),n.preConsent=Y(n.preConsent),n.sourceConfigurationOverride=Y(n.sourceConfigurationOverride),L(t,Qe(n))},Un="dataplaneEventsQueue",$n="destinationsEventsQueue",ql="transformEvent",Jl=(t,e)=>Object.keys(t).filter(n=>t[n]!==!0||!e[n]).reduce((n,s)=>{let r=b(n);return r[s]=t[s],r},{}),Zl=(t,e)=>{let n=b(t),s=e.nativeDestinations.integrationsConfig.value,r=Jl(t.integrations,s);return n.integrations=L(s,r),n},ec=t=>t.consents.preConsent.value.enabled&&t.consents.preConsent.value.events?.delivery==="buffer",Ke=(t,e,n,s)=>{if(O(t))if(m(t))try{t(...e)}catch(r){s.error(xi(n),r)}else s.error(os(n))},Ft=class{constructor(e,n,s,r,i){this.pluginsManager=e,this.errorHandler=r,this.httpClient=s,this.logger=i,this.storeManager=n}init(){this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${Un}.init`,o,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.dmtEventsQueue=this.pluginsManager.invokeSingle(`${ql}.init`,o,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${$n}.init`,o,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger),X(()=>{o.nativeDestinations.clientDestinationsReady.value===!0&&(this.destinationsEventsQueue?.start(),this.dmtEventsQueue?.start())});let e=ec(o),n;X(()=>{let s=o.loadOptions.value.bufferDataPlaneEventsUntilReady===!0&&o.nativeDestinations.clientDestinationsReady.value===!1;(o.nativeDestinations.activeDestinations.value.some(i=>la(i))===!1||s===!1)&&!e&&this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&(globalThis.clearTimeout(n),this.dataplaneEventsQueue?.start())}),o.loadOptions.value.bufferDataPlaneEventsUntilReady===!0&&(n=globalThis.setTimeout(()=>{this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&this.dataplaneEventsQueue?.start()},o.loadOptions.value.dataPlaneEventsBufferTimeout))}resume(){this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&(o.consents.postConsent.value.discardPreConsentEvents&&(this.dataplaneEventsQueue?.clear(),this.destinationsEventsQueue?.clear()),this.dataplaneEventsQueue?.start())}enqueue(e,n){let s=Zl(e,o);this.pluginsManager.invokeSingle(`${Un}.enqueue`,o,this.dataplaneEventsQueue,s,this.errorHandler,this.logger);let r=b(e);this.pluginsManager.invokeSingle(`${$n}.enqueue`,o,this.destinationsEventsQueue,r,this.errorHandler,this.logger);let i=`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}${zt}`;Ke(n,[s],i,this.logger)}},Mn=t=>{let e=new CustomEvent(t,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:!0,cancelable:!0,composed:!0});globalThis.document.dispatchEvent(e)},tc=t=>_(t)&&t.trim().length>0,nc=t=>Ee(t),Vt=class{constructor(){this.preloadBuffer=new Et,this.initialized=!1,this.errorHandler=ys,this.logger=te,this.externalSrcLoader=new Xe(this.logger),this.httpClient=ps,this.httpClient.init(this.errorHandler),this.capabilitiesManager=new $t(this.httpClient,this.errorHandler,this.logger)}load(e,n,s={}){if(!o.lifecycle.status.value){if(!tc(e)){this.logger.error(pi(we,e));return}if(!nc(n)){this.logger.error(vi(we,n));return}U(()=>{o.lifecycle.writeKey.value=b(e),o.lifecycle.dataPlaneUrl.value=b(n),o.loadOptions.value=Yl(o.loadOptions.value,s),o.lifecycle.status.value="mounted"}),this.logger.setMinLogLevel(o.loadOptions.value.logLevel??rs),Pe("state",o,e),this.startLifecycle()}}startLifecycle(){X(()=>{try{switch(o.lifecycle.status.value){case"mounted":this.onMounted();break;case"browserCapabilitiesReady":this.onBrowserCapabilitiesReady();break;case"configured":this.onConfigured();break;case"pluginsLoading":break;case"pluginsReady":this.onPluginsReady();break;case"initialized":this.onInitialized();break;case"loaded":this.onLoaded();break;case"destinationsLoading":break;case"destinationsReady":this.onDestinationsReady();break;case"ready":this.onReady();break;default:break}}catch(e){let n="Failed to load the SDK";this.errorHandler.onError({error:e,context:we,customMessage:n,groupingHash:n})}})}onBrowserCapabilitiesReady(){Vr(this),this.prepareInternalServices(),this.loadConfig()}onLoaded(){this.processBufferedEvents(),o.consents.preConsent.value.enabled===!0?o.lifecycle.status.value="ready":this.loadDestinations()}onMounted(){this.capabilitiesManager.init()}enqueuePreloadBufferEvents(e){Array.isArray(e)&&e.forEach(n=>this.preloadBuffer.enqueue(b(n)))}processDataInPreloadBuffer(){for(;this.preloadBuffer.size()>0;){let e=this.preloadBuffer.dequeue();e&&jr([...e],this)}}prepareInternalServices(){this.pluginsManager=new Rt(oa,this.errorHandler,this.logger),this.storeManager=new Dt(this.pluginsManager,this.errorHandler,this.logger),this.configManager=new wt(this.httpClient,this.errorHandler,this.logger),this.userSessionManager=new Gt(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventRepository=new Ft(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventManager=new xt(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger)}loadConfig(){o.lifecycle.writeKey.value&&this.httpClient.setAuthHeader(o.lifecycle.writeKey.value),this.configManager?.init()}onPluginsReady(){this.storeManager?.init(),this.userSessionManager?.init(),o.consents.enabled.value&&!o.consents.initialized.value&&(this.pluginsManager?.invokeSingle("consentManager.init",o,this.logger),o.consents.preConsent.value.enabled===!1&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",o,this.storeManager,this.logger)),this.eventManager?.init(),o.lifecycle.status.value="initialized"}onConfigured(){this.pluginsManager?.init()}onInitialized(){this.processDataInPreloadBuffer(),U(()=>{o.lifecycle.loaded.value=!0,o.lifecycle.status.value="loaded"}),this.initialized=!0;let e=o.loadOptions.value.onLoaded;Ke(e,[globalThis.rudderanalytics],ar,this.logger),Mn("RSA_Initialised")}onReady(){o.lifecycle.status.value="readyExecuted",o.eventBuffer.readyCallbacksArray.value.forEach(e=>{Ke(e,[],ot,this.logger)}),Mn("RSA_Ready")}processBufferedEvents(){let e=o.eventBuffer.toBeProcessedArray.value;for(;e.length>0;){let n=e.shift();if(o.eventBuffer.toBeProcessedArray.value=e,n){let s=n[0];m(this[s])&&this[s](...n.slice(1),!0)}e=o.eventBuffer.toBeProcessedArray.value}}loadDestinations(){if(o.lifecycle.status.value==="destinationsLoading"||o.lifecycle.status.value==="destinationsReady")return;this.pluginsManager?.invokeSingle("nativeDestinations.setActiveDestinations",o,this.pluginsManager,this.errorHandler,this.logger);let e=o.nativeDestinations.activeDestinations.value.length;if(e===0){o.lifecycle.status.value="destinationsReady";return}o.lifecycle.status.value="destinationsLoading",this.pluginsManager?.invokeSingle("nativeDestinations.load",o,this.externalSrcLoader,this.errorHandler,this.logger),X(()=>{(e===0||o.nativeDestinations.initializedDestinations.value.length+o.nativeDestinations.failedDestinations.value.length===e)&&U(()=>{o.lifecycle.status.value="destinationsReady",o.nativeDestinations.clientDestinationsReady.value=!0})})}onDestinationsReady(){o.lifecycle.status.value!=="ready"&&U(()=>{o.lifecycle.status.value="ready"})}ready(e,n=!1){let s="ready";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}if(this.errorHandler.leaveBreadcrumb(`New ${s} invocation`),!m(e)){this.logger.error(os(ot));return}o.lifecycle.status.value==="readyExecuted"?Ke(e,[],ot,this.logger):o.eventBuffer.readyCallbacksArray.value=[...o.eventBuffer.readyCallbacksArray.value,e]}page(e,n=!1){let s="page";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1,this.eventManager?.addEvent({type:"page",category:e.category,name:e.name,properties:e.properties,options:e.options,callback:e.callback}),o.capabilities.isAdBlocked.value===!0&&e.category!==on&&this.page(We(on,Nr,{path:Pr},o.loadOptions.value.sendAdblockPageOptions))}track(e,n=!1){let s="track";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event - ${e.name}`),o.metrics.triggered.value+=1,this.eventManager?.addEvent({type:s,name:e.name||void 0,properties:e.properties,options:e.options,callback:e.callback})}identify(e,n=!1){let s="identify";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1,e.userId&&o.session.userId.value&&e.userId!==o.session.userId.value&&this.reset(),G(e.userId)||this.userSessionManager?.setUserId(e.userId),this.userSessionManager?.setUserTraits(e.traits),this.eventManager?.addEvent({type:s,userId:e.userId,traits:e.traits,options:e.options,callback:e.callback})}alias(e,n=!1){let s="alias";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1;let r=e.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type:s,to:e.to,from:r,options:e.options,callback:e.callback})}group(e,n=!1){let s="group";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} event`),o.metrics.triggered.value+=1,G(e.groupId)||this.userSessionManager?.setGroupId(e.groupId),this.userSessionManager?.setGroupTraits(e.traits),this.eventManager?.addEvent({type:s,groupId:e.groupId,traits:e.traits,options:e.options,callback:e.callback})}reset(e,n=!1){let s="reset";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} invocation`),this.userSessionManager?.reset(e)}getAnonymousId(e){return this.userSessionManager?.getAnonymousId(e)}setAnonymousId(e,n,s=!1){let r="setAnonymousId";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[r,e,n]];return}this.errorHandler.leaveBreadcrumb(`New ${r} invocation`),this.userSessionManager?.setAnonymousId(e,n)}getUserId(){return o.session.userId.value}getUserTraits(){return o.session.userTraits.value}getGroupId(){return o.session.groupId.value}getGroupTraits(){return o.session.groupTraits.value}startSession(e,n=!1){let s="startSession";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb(`New ${s} invocation`),this.userSessionManager?.start(e)}endSession(e=!1){let n="endSession";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[n]];return}this.errorHandler.leaveBreadcrumb(`New ${n} invocation`),this.userSessionManager?.end()}getSessionId(){return this.userSessionManager?.getSessionId()??null}consent(e,n=!1){let s="consent";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[s,e]];return}this.errorHandler.leaveBreadcrumb("New consent invocation"),U(()=>{o.consents.preConsent.value={...o.consents.preConsent.value,enabled:!1},o.consents.postConsent.value=ll(e);let{initialized:r,consentsData:i}=ks(o.consents.postConsent.value.consentManagement,this.logger);o.consents.initialized.value=r,o.consents.data.value=i}),o.consents.enabled.value&&!o.consents.initialized.value&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",o,this.storeManager,this.logger),this.storeManager?.initializeStorageState(),this.userSessionManager?.syncStorageDataToState(),this.eventManager?.resume(),this.loadDestinations(),this.sendTrackingEvents(n)}sendTrackingEvents(e){if(o.consents.postConsent.value.trackConsent){let n=Qt(kr);e?o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,["track",n]]:this.track(n)}if(o.consents.postConsent.value.sendPageEvent){let n=We();e?o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,["page",n]]:this.page(n)}}setAuthToken(e){this.userSessionManager?.setAuthToken(e)}addCustomIntegration(e,n,s=!1){let r="addCustomIntegration";if(s)this.errorHandler.leaveBreadcrumb(`New ${r} invocation`),this.pluginsManager?.invokeSingle("nativeDestinations.addCustomIntegration",e,n,o,this.logger);else{if(o.lifecycle.loaded.value){this.logger.error(Xi(we,e));return}o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[r,e,n]]}}},ce=class ce{constructor(){k(this,"analyticsInstances",{});k(this,"defaultAnalyticsKey","");k(this,"logger",te);try{if(ce.globalSingleton)return ce.globalSingleton;ce.initializeGlobalResources(),this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this),this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this),this.load=this.load.bind(this),this.ready=this.ready.bind(this),this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this),this.page=this.page.bind(this),this.track=this.track.bind(this),this.identify=this.identify.bind(this),this.alias=this.alias.bind(this),this.group=this.group.bind(this),this.reset=this.reset.bind(this),this.getAnonymousId=this.getAnonymousId.bind(this),this.setAnonymousId=this.setAnonymousId.bind(this),this.getUserId=this.getUserId.bind(this),this.getUserTraits=this.getUserTraits.bind(this),this.getGroupId=this.getGroupId.bind(this),this.getGroupTraits=this.getGroupTraits.bind(this),this.startSession=this.startSession.bind(this),this.endSession=this.endSession.bind(this),this.getSessionId=this.getSessionId.bind(this),this.setAuthToken=this.setAuthToken.bind(this),this.consent=this.consent.bind(this),this.addCustomIntegration=this.addCustomIntegration.bind(this),this.createSafeAnalyticsInstance(),ce.globalSingleton=this,o.autoTrack.pageLifecycle.pageViewId.value=Ze(),o.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now(),this.triggerBufferedLoadEvent(),globalThis.rudderanalytics=this}catch(e){D(e)}}createSafeAnalyticsInstance(){o.lifecycle.safeAnalyticsInstance.value={page:this.page.bind(this),track:this.track.bind(this),identify:this.identify.bind(this),alias:this.alias.bind(this),group:this.group.bind(this),getAnonymousId:this.getAnonymousId.bind(this),getUserId:this.getUserId.bind(this),getUserTraits:this.getUserTraits.bind(this),getGroupId:this.getGroupId.bind(this),getGroupTraits:this.getGroupTraits.bind(this),getSessionId:this.getSessionId.bind(this)}}static initializeGlobalResources(){ys.init(),Zt.configure(),qt.configure(),Jt.configure(),qe.configure()}setDefaultInstanceKey(e){_(e)&&e&&(this.defaultAnalyticsKey=e)}getAnalyticsInstance(e){try{let n=e;return(!_(n)||!n)&&(n=this.defaultAnalyticsKey),this.analyticsInstances[n]||(this.analyticsInstances[n]=new Vt),this.analyticsInstances[n]}catch(n){D(n);return}}load(e,n,s){try{if(this.analyticsInstances[e])return;this.setDefaultInstanceKey(e),this.trackPageLifecycleEvents(s);let r=qn(Oe);Fr(r),Pe(Oe,b(r)),this.getAnalyticsInstance(e)?.load(e,n,I(s))}catch(r){D(r)}}trackPageLifecycleEvents(e){let{autoTrack:n,useBeacon:s}=e??{},{enabled:r=!1,options:i={},pageLifecycle:a}=n??{},{events:l=[it.UNLOADED],enabled:c=r,options:d=i}=a??{};o.autoTrack.pageLifecycle.enabled.value=c,o.autoTrack.enabled.value=r||c,c&&this.setupPageUnloadTracking(l,s,d)}setupPageUnloadTracking(e,n,s){(e.length===0||e.includes(it.UNLOADED))&&(n===!0?pr(r=>{if(r===!1&&o.lifecycle.loaded.value){let i=Date.now(),a=i-o.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(it.UNLOADED,{timeOnPage:a},{...s,originalTimestamp:Qn(new Date(i))})}},!0):this.logger.warn(zi(cr)))}triggerBufferedLoadEvent(){let e=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[],n=Gr(e);Pe(Oe,b([...e])),n.length>0&&(n.shift(),this.load.apply(null,n))}ready(e){try{this.getAnalyticsInstance()?.ready(I(e))}catch(n){D(n)}}page(e,n,s,r,i){try{this.getAnalyticsInstance()?.page(We(I(e),I(n),I(s),I(r),I(i)))}catch(a){D(a)}}track(e,n,s,r){try{this.getAnalyticsInstance()?.track(Qt(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}identify(e,n,s,r){try{this.getAnalyticsInstance()?.identify(Fn(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}alias(e,n,s,r){try{this.getAnalyticsInstance()?.alias(Vn(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}group(e,n,s,r){try{this.getAnalyticsInstance()?.group(jn(I(e),I(n),I(s),I(r)))}catch(i){D(i)}}reset(e){try{this.getAnalyticsInstance()?.reset(I(e))}catch(n){D(n)}}getAnonymousId(e){try{return this.getAnalyticsInstance()?.getAnonymousId(I(e))}catch(n){D(n);return}}setAnonymousId(e,n){try{this.getAnalyticsInstance()?.setAnonymousId(I(e),I(n))}catch(s){D(s)}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId()}catch(e){D(e);return}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits()}catch(e){D(e);return}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId()}catch(e){D(e);return}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits()}catch(e){D(e);return}}startSession(e){try{this.getAnalyticsInstance()?.startSession(I(e))}catch(n){D(n)}}endSession(){try{this.getAnalyticsInstance()?.endSession()}catch(e){D(e)}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId()}catch(e){D(e);return}}setAuthToken(e){try{this.getAnalyticsInstance()?.setAuthToken(I(e))}catch(n){D(n)}}consent(e){try{this.getAnalyticsInstance()?.consent(I(e))}catch(n){D(n)}}addCustomIntegration(e,n){try{this.getAnalyticsInstance()?.addCustomIntegration(I(e),I(n))}catch(s){D(s)}}};k(ce,"globalSingleton",null);var Bn=ce;export{Bn as a};
14
- //# sourceMappingURL=chunk-EMF3RT6E.mjs.map