@deriv-com/analytics 1.41.1 → 1.42.1

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.
@@ -1,3 +1,3 @@
1
1
  /* @deriv-com/analytics - Browser ESM Bundle (RudderStack + PostHog) - Built with tsup */
2
- import{a as G}from"../chunk-YVBRA3QD.mjs";import{c as z,g as E,h as U,i as b,j as D,k as P,l as O}from"../chunk-F3U33XPR.mjs";var Z=4320*60*60,v=class v{constructor(i,e,r=!1){this.analytics=new G;this.has_identified=!1;this.has_initialized=!1;this.current_page="";this.rudderstack_anonymous_cookie_key="rudder_anonymous_id";this.debug=!1;this.log=E("[RudderStack]",()=>this.debug);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,d=["webflow.io"].some(g=>e.endsWith(g))?e:e.split(".").slice(-2).join("."),p;if(crypto?.randomUUID)p=crypto.randomUUID();else if(crypto?.getRandomValues){let g=new Uint8Array(16);crypto.getRandomValues(g),g[6]=g[6]&15|64,g[8]=g[8]&63|128;let _=Array.from(g,x=>x.toString(16).padStart(2,"0")).join("");p=`${_.slice(0,8)}-${_.slice(8,12)}-${_.slice(12,16)}-${_.slice(16,20)}-${_.slice(20)}`}else throw new Error("Crypto API not available for secure random UUID generation");let m=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${this.rudderstack_anonymous_cookie_key}=${p}; path=/; Domain=${d}; max-age=${Z}; SameSite=Lax${m}`}catch(e){console.warn("RudderStack: Failed to set anonymous ID cookie",e)}};this.getUserId=()=>this.analytics.getUserId();this.init=i=>{if(!i){console.warn("RudderStack: Initialization skipped - no key provided");return}this.log("init | loading SDK",{dataplane:z});try{this.setCookieIfNotExists(),this.analytics.load(i,z,{externalAnonymousIdCookieName:this.rudderstack_anonymous_cookie_key,storage:{type:"localStorage"},lockIntegrationsVersion:!0,onLoaded:()=>{this.has_initialized=!0,this.has_identified=!!this.getUserId(),this.log("init | SDK loaded successfully",{userId:this.getUserId(),anonymousId:this.getAnonymousId()}),this.onLoadedCallback?.()}})}catch(e){console.error("RudderStack: Failed to initialize",e)}};this.identifyEvent=(i,e)=>{if(!this.has_initialized){console.warn("RudderStack: Cannot identify - not initialized");return}let r=this.getUserId();if(!r||r!==i)try{this.log("identifyEvent | identifying user",{user_id:i,traits:e}),this.analytics.identify(i,e||{}),this.has_identified=!0}catch(c){console.error("RudderStack: Failed to identify user",c)}else this.log("identifyEvent | user already identified",{user_id:i}),this.has_identified=!0};this.pageView=(i,e="Deriv App",r,c)=>{if(!(!this.has_initialized||i===this.current_page))try{let d={...r&&{user_id:r},...c};this.log("pageView | tracking page view",{platform:e,current_page:i,properties:d}),this.analytics.page(e,i,d),this.current_page=i}catch(d){console.error("RudderStack: Failed to track page view",d)}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting RudderStack session"),this.analytics.reset(),this.has_identified=!1}catch(i){console.error("RudderStack: Failed to reset",i)}};this.track=(i,e)=>{if(this.has_initialized)try{this.log("track | sending event to RudderStack",{event:i,payload:e}),this.analytics.track(i,e)}catch(r){console.warn("RudderStack: Failed to track event",r)}};this.onLoadedCallback=e,this.debug=r,this.init(i)}};v.getRudderStackInstance=(i,e,r=!1)=>(v._instance||(v._instance=new v(i,e,r)),v._instance);var F=v;var R="cached_analytics_events",C="cached_analytics_page_views",$=(l,i)=>{try{let e=localStorage.getItem(R),r=e?JSON.parse(e):[];r.push({name:l,properties:i,timestamp:Date.now()}),localStorage.setItem(R,JSON.stringify(r))}catch(e){console.warn("Analytics: Failed to cache event",e)}},L=(l,i)=>{try{let e=localStorage.getItem(C),r=e?JSON.parse(e):[];r.push({name:l,properties:i,timestamp:Date.now()}),localStorage.setItem(C,JSON.stringify(r))}catch(e){console.warn("Analytics: Failed to cache page view",e)}},N=()=>{try{let l=localStorage.getItem(R);if(l){let i=JSON.parse(l);return Array.isArray(i)?i:[]}}catch(l){console.warn("Analytics: Failed to get cached events",l)}return[]},H=()=>{try{let l=localStorage.getItem(C);if(l){let i=JSON.parse(l);return Array.isArray(i)?i:[]}}catch(l){console.warn("Analytics: Failed to get cached pages",l)}return[]},j=()=>{try{localStorage.removeItem(R)}catch(l){console.warn("Analytics: Failed to clear cached events",l)}},J=()=>{try{localStorage.removeItem(C)}catch(l){console.warn("Analytics: Failed to clear cached page views",l)}};function Y(l){let i=l?.debug??!1,e=E("",()=>i),r,c,d,p={},I={},m=[],g=[],_=!1,x=()=>{if(!_&&c?.has_initialized){_=!0;try{let t=N();t.length>0&&(e(`processStorageCache | replaying ${t.length} cached event(s)`,t),t.forEach(o=>{let a=P(o.properties);c?.track(o.name,a)}),j());let n=H();n.length>0&&(e(`processStorageCache | replaying ${n.length} cached page view(s)`,n),n.forEach(o=>{c?.pageView(o.name,"Deriv App",w(),o.properties)}),J())}catch(t){console.warn("Analytics: Failed to process storage cache",t)}}},B=()=>{e("onSdkLoaded | RudderStack SDK loaded"),x(),g.length>0&&e(`onSdkLoaded | flushing ${g.length} pending identify call(s)`),g.forEach(({userId:t,traits:n})=>{t&&c?.identifyEvent(t,n)}),g=[]},K=async({growthbookKey:t,growthbookDecryptionKey:n,rudderstackKey:o,growthbookOptions:a,posthogOptions:u,debug:f})=>{var h,y;f!==void 0&&(i=f),e("initialise | starting analytics initialization",{rudderstack:!!o,growthbook:!!t,posthog:!!u});try{let k=a?.attributes?.country||(t?await D():void 0);if(o&&(e("initialise | initializing RudderStack"),c=F.getRudderStackInstance(o,B,i)),a?.attributes&&Object.keys(a.attributes).length>0){let s=a.attributes,A=c?.getAnonymousId();p={...p,country:k,...s.user_language&&{user_language:s.user_language},...s.account_type&&{account_type:s.account_type},...s.app_id&&{app_id:s.app_id},...s.residence_country&&{residence_country:s.residence_country},...s.device_type&&{device_type:s.device_type},...s.url&&{url:s.url},...s.email_hash&&{email_hash:s.email_hash},...s.network_type&&{network_type:s.network_type},...s.network_rtt&&{network_rtt:s.network_rtt},...s.network_downlink&&{network_downlink:s.network_downlink},...s.account_currency&&{account_currency:s.account_currency},...s.account_mode&&{account_mode:s.account_mode},loggedIn:!!s.loggedIn,...s.user_id&&!b(s.user_id)&&{user_id:s.user_id},...A&&{anonymous_id:A}}}a??(a={}),a.attributes??(a.attributes={});let S=c?.getAnonymousId();if((h=a.attributes).id??(h.id=S),(y=a.attributes).country??(y.country=k),t){e("initialise | initializing GrowthBook");let{Growthbook:s}=await import("../growthbook-T47IBUAJ.mjs");r=s.getGrowthBookInstance(t,n,a,i),e("initialise | GrowthBook initialized");let A=setInterval(()=>{Object.keys(I).length>0?clearInterval(A):I=V("tracking-buttons-config",{})},1e3)}if(u){e("initialise | initializing PostHog");let{Posthog:s}=await import("../posthog-AGNFJC2G.mjs");d=s.getPosthogInstance(u,i),e("initialise | PostHog initialized")}e("initialise | analytics initialization complete")}catch(k){console.warn("Analytics: Failed to initialize",k)}},W=t=>{e("setAttributes | received attributes",t);let{user_id:n,...o}=t,a=n??w();if(r){let u={...o};n&&!b(n)&&(u.user_id=n),a&&(u.id=a,u.user_id=a),e("setAttributes | called GrowthBook setAttributes",u),r.setAttributes(u)}p={...p,...Object.fromEntries(Object.entries(o).filter(([,u])=>u!==void 0)),...n!==void 0&&!b(n)&&{user_id:n}},e("setAttributes | updated core_data",p)},q=t=>r?.getFeatureState(t)?.experimentResult?.name,V=(t,n)=>r?.getFeatureValue(t,n),M=async()=>await r?.getStatus(),X=t=>r?.isOn(t),Q=t=>r?.setUrl(t),w=()=>{let t=c?.getUserId()||"";return t&&!b(t)?t:""},T={initialise:K,setAttributes:W,identifyEvent:(t,n)=>{let o=t||w();if(!o){e("identifyEvent | skipped \u2014 no user_id available");return}e("identifyEvent | called",{user_id:o,traits:n});let a=y=>{if(!y)return y;let{email:k,...S}=y;return{...S,...k&&{is_internal:U(k)}}},u=n?.rudderstack!==void 0||n?.posthog!==void 0,f,h;if(u){let{rudderstack:y,posthog:k,...S}=n;f=a({...S,...y}),h=a({...S,...k})}else f=a(n),h=a(n);c&&(c.has_initialized?(e("identifyEvent | calling RudderStack identify",{user_id:o,traits:f}),c.identifyEvent(o,f)):g.some(y=>y.userId===o)||(e("identifyEvent | RudderStack not initialized \u2014 queuing identify call",{user_id:o}),g.push({userId:o,traits:f}))),d?.has_initialized&&(e("identifyEvent | calling PostHog identify",{user_id:o,traits:h}),d.identifyEvent(o,h))},backfillPersonProperties:({user_id:t,email:n,language:o,country_of_residence:a})=>{e("backfillPersonProperties | called",{user_id:t}),d?.has_initialized?(e("backfillPersonProperties | backfilling person properties in PostHog",{user_id:t}),d.backfillPersonProperties({user_id:t,email:n,language:o,country_of_residence:a})):e("backfillPersonProperties | skipped \u2014 PostHog not initialized")},getFeatureState:q,getFeatureValue:V,getGrowthbookStatus:M,isFeatureOn:X,setUrl:Q,getId:w,getAnonymousId:()=>c?.getAnonymousId()||"",trackEvent:(t,n)=>{let o=w();e("trackEvent | called",{event:t,analytics_data:n,userId:o,core_data:p});let a={...p,...n,...o&&!p.user_id&&{user_id:o}};if(e("trackEvent | built payload",{event:t,final_payload:a}),!(!(t in I)||I[t])){e("trackEvent | skipped \u2014 event disabled by tracking_config",{event:t});return}let f=c?.has_initialized;if(!navigator.onLine||!f)f?(e("trackEvent | offline \u2014 caching event to memory",{event:t}),m.push({event:t,payload:a})):(e("trackEvent | RudderStack not initialized \u2014 caching event to localStorage",{event:t}),$(t,a));else{m.length>0&&(e(`trackEvent | flushing ${m.length} offline cached event(s) to RudderStack`),m.forEach(y=>{let k=P(y.payload);c?.track(y.event,k)}),m=[]);let h=P(a);e("trackEvent | sending event to RudderStack",{event:t,payload:h}),c?.track(t,h)}if(d?.has_initialized){let h=P(O(a));e("trackEvent | sending event to PostHog",{event:t,payload:h}),d.capture(t,h)}},getInstances:()=>({ab:r,tracking:c,posthog:d}),pageView:(t,n="Deriv App",o)=>{let a=w();e("pageView | called",{current_page:t,platform:n,properties:o,userId:a}),c?.has_initialized?(e("pageView | sending page view to RudderStack",{current_page:t,platform:n}),c.pageView(t,n,a,o)):(e("pageView | RudderStack not initialized \u2014 caching page view to localStorage",{current_page:t}),L(t,{platform:n,...o}))},reset:()=>{e("reset | resetting all providers"),c?.has_initialized&&(e("reset | resetting RudderStack"),c.reset()),d?.has_initialized&&(e("reset | resetting PostHog"),d.reset())},isPosthogFeatureEnabled:t=>d?.isFeatureEnabled(t),getPosthogFeatureFlag:t=>d?.getFeatureFlag(t),getPosthogFeatureFlagPayload:t=>d?.getFeatureFlagPayload(t),getPosthogAllFlags:()=>d?.getAllFlags()??{},onPosthogFeatureFlags:t=>d?.onFeatureFlags(t)??(()=>{}),reloadPosthogFeatureFlags:()=>d?.reloadFeatureFlags()};return typeof window<"u"&&(window.AnalyticsInstance=T),T}var ee=Y();export{ee as Analytics};
2
+ import{a as G}from"../chunk-MWNJTXSL.mjs";import{c as z,g as E,h as U,i as b,j as D,k as P,l as O}from"../chunk-F3U33XPR.mjs";var Z=4320*60*60,v=class v{constructor(i,e,r=!1){this.analytics=new G;this.has_identified=!1;this.has_initialized=!1;this.current_page="";this.rudderstack_anonymous_cookie_key="rudder_anonymous_id";this.debug=!1;this.log=E("[RudderStack]",()=>this.debug);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,d=["webflow.io"].some(g=>e.endsWith(g))?e:e.split(".").slice(-2).join("."),p;if(crypto?.randomUUID)p=crypto.randomUUID();else if(crypto?.getRandomValues){let g=new Uint8Array(16);crypto.getRandomValues(g),g[6]=g[6]&15|64,g[8]=g[8]&63|128;let _=Array.from(g,x=>x.toString(16).padStart(2,"0")).join("");p=`${_.slice(0,8)}-${_.slice(8,12)}-${_.slice(12,16)}-${_.slice(16,20)}-${_.slice(20)}`}else throw new Error("Crypto API not available for secure random UUID generation");let m=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${this.rudderstack_anonymous_cookie_key}=${p}; path=/; Domain=${d}; max-age=${Z}; SameSite=Lax${m}`}catch(e){console.warn("RudderStack: Failed to set anonymous ID cookie",e)}};this.getUserId=()=>this.analytics.getUserId();this.init=i=>{if(!i){console.warn("RudderStack: Initialization skipped - no key provided");return}this.log("init | loading SDK",{dataplane:z});try{this.setCookieIfNotExists(),this.analytics.load(i,z,{externalAnonymousIdCookieName:this.rudderstack_anonymous_cookie_key,storage:{type:"localStorage"},lockIntegrationsVersion:!0,onLoaded:()=>{this.has_initialized=!0,this.has_identified=!!this.getUserId(),this.log("init | SDK loaded successfully",{userId:this.getUserId(),anonymousId:this.getAnonymousId()}),this.onLoadedCallback?.()}})}catch(e){console.error("RudderStack: Failed to initialize",e)}};this.identifyEvent=(i,e)=>{if(!this.has_initialized){console.warn("RudderStack: Cannot identify - not initialized");return}let r=this.getUserId();if(!r||r!==i)try{this.log("identifyEvent | identifying user",{user_id:i,traits:e}),this.analytics.identify(i,e||{}),this.has_identified=!0}catch(c){console.error("RudderStack: Failed to identify user",c)}else this.log("identifyEvent | user already identified",{user_id:i}),this.has_identified=!0};this.pageView=(i,e="Deriv App",r,c)=>{if(!(!this.has_initialized||i===this.current_page))try{let d={...r&&{user_id:r},...c};this.log("pageView | tracking page view",{platform:e,current_page:i,properties:d}),this.analytics.page(e,i,d),this.current_page=i}catch(d){console.error("RudderStack: Failed to track page view",d)}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting RudderStack session"),this.analytics.reset(),this.has_identified=!1}catch(i){console.error("RudderStack: Failed to reset",i)}};this.track=(i,e)=>{if(this.has_initialized)try{this.log("track | sending event to RudderStack",{event:i,payload:e}),this.analytics.track(i,e)}catch(r){console.warn("RudderStack: Failed to track event",r)}};this.onLoadedCallback=e,this.debug=r,this.init(i)}};v.getRudderStackInstance=(i,e,r=!1)=>(v._instance||(v._instance=new v(i,e,r)),v._instance);var F=v;var R="cached_analytics_events",C="cached_analytics_page_views",$=(l,i)=>{try{let e=localStorage.getItem(R),r=e?JSON.parse(e):[];r.push({name:l,properties:i,timestamp:Date.now()}),localStorage.setItem(R,JSON.stringify(r))}catch(e){console.warn("Analytics: Failed to cache event",e)}},L=(l,i)=>{try{let e=localStorage.getItem(C),r=e?JSON.parse(e):[];r.push({name:l,properties:i,timestamp:Date.now()}),localStorage.setItem(C,JSON.stringify(r))}catch(e){console.warn("Analytics: Failed to cache page view",e)}},N=()=>{try{let l=localStorage.getItem(R);if(l){let i=JSON.parse(l);return Array.isArray(i)?i:[]}}catch(l){console.warn("Analytics: Failed to get cached events",l)}return[]},H=()=>{try{let l=localStorage.getItem(C);if(l){let i=JSON.parse(l);return Array.isArray(i)?i:[]}}catch(l){console.warn("Analytics: Failed to get cached pages",l)}return[]},j=()=>{try{localStorage.removeItem(R)}catch(l){console.warn("Analytics: Failed to clear cached events",l)}},J=()=>{try{localStorage.removeItem(C)}catch(l){console.warn("Analytics: Failed to clear cached page views",l)}};function Y(l){let i=l?.debug??!1,e=E("",()=>i),r,c,d,p={},I={},m=[],g=[],_=!1,x=()=>{if(!_&&c?.has_initialized){_=!0;try{let t=N();t.length>0&&(e(`processStorageCache | replaying ${t.length} cached event(s)`,t),t.forEach(o=>{let a=P(o.properties);c?.track(o.name,a)}),j());let n=H();n.length>0&&(e(`processStorageCache | replaying ${n.length} cached page view(s)`,n),n.forEach(o=>{c?.pageView(o.name,"Deriv App",w(),o.properties)}),J())}catch(t){console.warn("Analytics: Failed to process storage cache",t)}}},B=()=>{e("onSdkLoaded | RudderStack SDK loaded"),x(),g.length>0&&e(`onSdkLoaded | flushing ${g.length} pending identify call(s)`),g.forEach(({userId:t,traits:n})=>{t&&c?.identifyEvent(t,n)}),g=[]},K=async({growthbookKey:t,growthbookDecryptionKey:n,rudderstackKey:o,growthbookOptions:a,posthogOptions:u,debug:f})=>{var h,y;f!==void 0&&(i=f),e("initialise | starting analytics initialization",{rudderstack:!!o,growthbook:!!t,posthog:!!u});try{let k=a?.attributes?.country||(t?await D():void 0);if(o&&(e("initialise | initializing RudderStack"),c=F.getRudderStackInstance(o,B,i)),a?.attributes&&Object.keys(a.attributes).length>0){let s=a.attributes,A=c?.getAnonymousId();p={...p,country:k,...s.user_language&&{user_language:s.user_language},...s.account_type&&{account_type:s.account_type},...s.app_id&&{app_id:s.app_id},...s.residence_country&&{residence_country:s.residence_country},...s.device_type&&{device_type:s.device_type},...s.url&&{url:s.url},...s.email_hash&&{email_hash:s.email_hash},...s.network_type&&{network_type:s.network_type},...s.network_rtt&&{network_rtt:s.network_rtt},...s.network_downlink&&{network_downlink:s.network_downlink},...s.account_currency&&{account_currency:s.account_currency},...s.account_mode&&{account_mode:s.account_mode},loggedIn:!!s.loggedIn,...s.user_id&&!b(s.user_id)&&{user_id:s.user_id},...A&&{anonymous_id:A}}}a??(a={}),a.attributes??(a.attributes={});let S=c?.getAnonymousId();if((h=a.attributes).id??(h.id=S),(y=a.attributes).country??(y.country=k),t){e("initialise | initializing GrowthBook");let{Growthbook:s}=await import("../growthbook-TBZXPHJZ.mjs");r=s.getGrowthBookInstance(t,n,a,i),e("initialise | GrowthBook initialized");let A=setInterval(()=>{Object.keys(I).length>0?clearInterval(A):I=V("tracking-buttons-config",{})},1e3)}if(u){e("initialise | initializing PostHog");let{Posthog:s}=await import("../posthog-QH4OCJ4V.mjs");d=s.getPosthogInstance(u,i),e("initialise | PostHog initialized")}e("initialise | analytics initialization complete")}catch(k){console.warn("Analytics: Failed to initialize",k)}},W=t=>{e("setAttributes | received attributes",t);let{user_id:n,...o}=t,a=n??w();if(r){let u={...o};n&&!b(n)&&(u.user_id=n),a&&(u.id=a,u.user_id=a),e("setAttributes | called GrowthBook setAttributes",u),r.setAttributes(u)}p={...p,...Object.fromEntries(Object.entries(o).filter(([,u])=>u!==void 0)),...n!==void 0&&!b(n)&&{user_id:n}},e("setAttributes | updated core_data",p)},q=t=>r?.getFeatureState(t)?.experimentResult?.name,V=(t,n)=>r?.getFeatureValue(t,n),M=async()=>await r?.getStatus(),X=t=>r?.isOn(t),Q=t=>r?.setUrl(t),w=()=>{let t=c?.getUserId()||"";return t&&!b(t)?t:""},T={initialise:K,setAttributes:W,identifyEvent:(t,n)=>{let o=t||w();if(!o){e("identifyEvent | skipped \u2014 no user_id available");return}e("identifyEvent | called",{user_id:o,traits:n});let a=y=>{if(!y)return y;let{email:k,...S}=y;return{...S,...k&&{is_internal:U(k)}}},u=n?.rudderstack!==void 0||n?.posthog!==void 0,f,h;if(u){let{rudderstack:y,posthog:k,...S}=n;f=a({...S,...y}),h=a({...S,...k})}else f=a(n),h=a(n);c&&(c.has_initialized?(e("identifyEvent | calling RudderStack identify",{user_id:o,traits:f}),c.identifyEvent(o,f)):g.some(y=>y.userId===o)||(e("identifyEvent | RudderStack not initialized \u2014 queuing identify call",{user_id:o}),g.push({userId:o,traits:f}))),d?.has_initialized&&(e("identifyEvent | calling PostHog identify",{user_id:o,traits:h}),d.identifyEvent(o,h))},backfillPersonProperties:({user_id:t,email:n,language:o,country_of_residence:a})=>{e("backfillPersonProperties | called",{user_id:t}),d?.has_initialized?(e("backfillPersonProperties | backfilling person properties in PostHog",{user_id:t}),d.backfillPersonProperties({user_id:t,email:n,language:o,country_of_residence:a})):e("backfillPersonProperties | skipped \u2014 PostHog not initialized")},getFeatureState:q,getFeatureValue:V,getGrowthbookStatus:M,isFeatureOn:X,setUrl:Q,getId:w,getAnonymousId:()=>c?.getAnonymousId()||"",trackEvent:(t,n)=>{let o=w();e("trackEvent | called",{event:t,analytics_data:n,userId:o,core_data:p});let a={...p,...n,...o&&!p.user_id&&{user_id:o}};if(e("trackEvent | built payload",{event:t,final_payload:a}),!(!(t in I)||I[t])){e("trackEvent | skipped \u2014 event disabled by tracking_config",{event:t});return}let f=c?.has_initialized;if(!navigator.onLine||!f)f?(e("trackEvent | offline \u2014 caching event to memory",{event:t}),m.push({event:t,payload:a})):(e("trackEvent | RudderStack not initialized \u2014 caching event to localStorage",{event:t}),$(t,a));else{m.length>0&&(e(`trackEvent | flushing ${m.length} offline cached event(s) to RudderStack`),m.forEach(y=>{let k=P(y.payload);c?.track(y.event,k)}),m=[]);let h=P(a);e("trackEvent | sending event to RudderStack",{event:t,payload:h}),c?.track(t,h)}if(d?.has_initialized){let h=P(O(a));e("trackEvent | sending event to PostHog",{event:t,payload:h}),d.capture(t,h)}},getInstances:()=>({ab:r,tracking:c,posthog:d}),pageView:(t,n="Deriv App",o)=>{let a=w();e("pageView | called",{current_page:t,platform:n,properties:o,userId:a}),c?.has_initialized?(e("pageView | sending page view to RudderStack",{current_page:t,platform:n}),c.pageView(t,n,a,o)):(e("pageView | RudderStack not initialized \u2014 caching page view to localStorage",{current_page:t}),L(t,{platform:n,...o}))},reset:()=>{e("reset | resetting all providers"),c?.has_initialized&&(e("reset | resetting RudderStack"),c.reset()),d?.has_initialized&&(e("reset | resetting PostHog"),d.reset())},isPosthogFeatureEnabled:t=>d?.isFeatureEnabled(t),getPosthogFeatureFlag:t=>d?.getFeatureFlag(t),getPosthogFeatureFlagPayload:t=>d?.getFeatureFlagPayload(t),getPosthogAllFlags:()=>d?.getAllFlags()??{},onPosthogFeatureFlags:t=>d?.onFeatureFlags(t)??(()=>{}),reloadPosthogFeatureFlags:()=>d?.reloadFeatureFlags()};return typeof window<"u"&&(window.AnalyticsInstance=T),T}var ee=Y();export{ee as Analytics};
3
3
  //# sourceMappingURL=analytics.esm.mjs.map
@@ -1,5 +1,5 @@
1
1
  /* @deriv-com/analytics - Browser ESM Bundle (RudderStack + PostHog) - Built with tsup */
2
2
  import{a as N}from"./chunk-F3U33XPR.mjs";function P(t){return t!=null&&typeof t=="object"&&t["@@functional/placeholder"]===!0}function Z(t){return function e(n){return arguments.length===0||P(n)?e:t.apply(this,arguments)}}function se(t){return function e(n,s){switch(arguments.length){case 0:return e;case 1:return P(n)?e:Z(function(i){return t(n,i)});default:return P(n)&&P(s)?e:P(n)?Z(function(i){return t(i,s)}):P(s)?Z(function(i){return t(n,i)}):t(n,s)}}}function xt(t){return function e(n,s,i){switch(arguments.length){case 0:return e;case 1:return P(n)?e:se(function(r,a){return t(n,r,a)});case 2:return P(n)&&P(s)?e:P(n)?se(function(r,a){return t(r,s,a)}):P(s)?se(function(r,a){return t(n,r,a)}):Z(function(r){return t(n,s,r)});default:return P(n)&&P(s)&&P(i)?e:P(n)&&P(s)?se(function(r,a){return t(r,a,i)}):P(n)&&P(i)?se(function(r,a){return t(r,s,a)}):P(s)&&P(i)?se(function(r,a){return t(n,r,a)}):P(n)?Z(function(r){return t(r,s,i)}):P(s)?Z(function(r){return t(n,r,i)}):P(i)?Z(function(r){return t(n,s,r)}):t(n,s,i)}}}function De(t,e){return Object.prototype.hasOwnProperty.call(e,t)}var ws=Z(function(e){return e===null?"Null":e===void 0?"Undefined":Object.prototype.toString.call(e).slice(8,-1)});function Yt(t){return Object.prototype.toString.call(t)==="[object Object]"}var Us=Number.isInteger||function(e){return e<<0===e};function Ms(t,e){var n=t<0?e.length+t:t;return e[n]}function $s(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 Ln(t,e,n){if(n||(n=new xs),Bs(t))return t;var s=function(r){var a=n.get(t);if(a)return a;n.set(t,r);for(var l in t)Object.prototype.hasOwnProperty.call(t,l)&&(r[l]=Ln(t[l],!0,n));return r};switch(ws(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 $s(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 Bs(t){var e=typeof t;return t==null||e!="object"&&e!="function"}var xs=(function(){function t(){this.map={},this.length=0}return t.prototype.set=function(e,n){var s=this.hash(e),i=this.map[s];i||(this.map[s]=i=[]),i.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 i=a[s];if(i[0]===e)return i[1]}return}var r=this.hash(e),a=this.map[r];if(a)for(var s=0;s<a.length;s+=1){var i=a[s];if(i[0]===e)return i[1]}},t})(),E=Z(function(e){return e!=null&&typeof e.clone=="function"?e.clone():Ln(e)});function Gs(t,e){for(var n=e,s=0;s<t.length;s+=1){if(n==null)return;var i=t[s];Us(i)?n=Ms(i,n):n=n[i]}return n}var Fs=xt(function(e,n,s){var i={},r;n=n||{},s=s||{};for(r in n)De(r,n)&&(i[r]=De(r,s)?e(r,n[r],s[r]):n[r]);for(r in s)De(r,s)&&!De(r,i)&&(i[r]=s[r]);return i}),Vs=xt(function t(e,n,s){return Fs(function(i,r,a){return Yt(r)&&Yt(a)?t(e,r,a):e(i,r,a)},n,s)}),js=xt(function(e,n,s){return Vs(function(i,r,a){return e(r,a)},n,s)}),Hs=se(Gs),wn=se(function(e,n){var s={};for(var i in n)e(n[i],i,n)&&(s[i]=n[i]);return s}),f=t=>typeof t=="function"&&!!(t.constructor&&t.call&&t.apply),_=t=>typeof t=="string",G=t=>t===null,U=t=>typeof t>"u",W=t=>G(t)||U(t),Ks=t=>typeof t=="bigint",A=t=>!U(t),pe=t=>!W(t),Ws=t=>pe(t)&&t!=="",Gt=t=>{switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return t instanceof Error}},Qs=t=>typeof t=="boolean",ut=(t,e)=>{let n=e.split(".");return Hs(n,t)},zs=(t,e)=>!!ut(t,e),Xs=t=>typeof t=="object",Ys=t=>!G(t)&&Xs(t)&&!Array.isArray(t),O=t=>!G(t)&&Object.prototype.toString.call(t)==="[object Object]",qs=(t,e)=>{if(!Array.isArray(t)||!Array.isArray(e))return E(e);let n=E(t);return e.forEach((s,i)=>{n[i]=Array.isArray(s)||Ys(s)?L(n[i],s):s}),n},L=(t,e)=>js(qs,t,e),te=t=>O(t)&&Object.keys(t).length>0,Te=t=>{let e=wn(A,t);return Object.keys(e).forEach(n=>{let s=e[n];O(s)&&(e[n]=Te(s))}),e},Fe=t=>{let e=wn(pe,t);return Object.keys(e).forEach(n=>{let s=e[n];O(s)&&(e[n]=Fe(s))}),e},Y=t=>{if(te(t))return Fe(t)},Q=(t,e)=>typeof t=="boolean"?t:e,Ft=t=>(Object.getOwnPropertyNames(t).forEach(function(e){t[e]&&typeof t[e]=="object"&&Ft(t[e])}),Object.freeze(t)),Js=t=>t.replace(/^\s+|\s+$/gm,""),qt=t=>t.replace(/^\.+/,""),Ve=t=>{let e=t;if(!_(t)&&!W(t))try{e=JSON.stringify(t)}catch{e=null}return e},Zs=t=>{let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return globalThis.btoa(e)},ei=t=>Zs(new TextEncoder().encode(t)),je=(t,e,n,s,i)=>{let r={category:t,name:e,properties:n,options:s,callback:void 0};f(i)&&(r.callback=i),f(s)&&(r.category=t,r.name=e,r.properties=n,r.options=void 0,r.callback=s),f(n)&&(r.category=t,r.name=e,r.properties=void 0,r.options=void 0,r.callback=n),f(e)&&(r.category=t,r.name=void 0,r.properties=void 0,r.options=void 0,r.callback=e),f(t)&&(r.category=void 0,r.name=void 0,r.properties=void 0,r.options=void 0,r.callback=t),O(t)?(r.name=void 0,r.category=void 0,r.properties=t,f(e)?r.options=void 0:r.options=e):O(e)&&(r.name=void 0,r.properties=e,f(n)?r.options=void 0:r.options=n),_(t)&&!_(e)&&(r.category=void 0,r.name=t),A(r.category)||(r.category=void 0),A(r.name)||(r.name=void 0),r.properties=r.properties?E(r.properties):{},A(r.options)?r.options=E(r.options):r.options=void 0;let a=_(r.name)?r.name:r.properties.name,l=_(r.category)?r.category:r.properties.category;return r.properties=L(O(r.properties)?r.properties:{},{...a&&{name:a},...l&&{category:l}}),r},Vt=(t,e,n,s)=>{let i={name:t,properties:e,options:n,callback:void 0};return f(s)&&(i.callback=s),f(n)&&(i.properties=e,i.options=void 0,i.callback=n),f(e)&&(i.properties=void 0,i.options=void 0,i.callback=e),i.properties=pe(i.properties)?E(i.properties):{},A(i.options)?i.options=E(i.options):i.options=void 0,i},Un=(t,e,n,s)=>{let i={userId:t,traits:e,options:n,callback:void 0};return f(s)&&(i.callback=s),f(n)&&(i.userId=t,i.traits=e,i.options=void 0,i.callback=n),f(e)&&(i.userId=t,i.traits=void 0,i.options=void 0,i.callback=e),(O(t)||G(t))&&(i.userId=null,i.traits=t,f(e)?i.options=void 0:i.options=e),i.userId=Ve(i.userId),O(i.traits)?i.traits=E(i.traits):i.traits=void 0,A(i.options)?i.options=E(i.options):i.options=void 0,i},Mn=(t,e,n,s)=>{let i={to:t,from:e,options:n,callback:void 0};return f(s)&&(i.callback=s),f(n)&&(i.to=t,i.from=e,i.options=void 0,i.callback=n),f(e)?(i.to=t,i.from=void 0,i.options=void 0,i.callback=e):(O(e)||G(e))&&(i.to=t,i.from=void 0,i.options=e),A(i.to)&&(i.to=Ve(i.to)),A(i.from)?i.from=Ve(i.from):i.from=void 0,A(i.options)?i.options=E(i.options):i.options=void 0,i},$n=(t,e,n,s)=>{let i={groupId:t,traits:e,options:n,callback:void 0};return f(s)&&(i.callback=s),f(n)&&(i.groupId=t,i.traits=e,i.options=void 0,i.callback=n),f(e)&&(i.groupId=t,i.traits=void 0,i.options=void 0,i.callback=e),(O(t)||G(t))&&(i.groupId=null,i.traits=t,f(e)?i.options=void 0:i.options=e),i.groupId=Ve(i.groupId),O(i.traits)?i.traits=E(i.traits):i.traits=void 0,A(i.options)?i.options=E(i.options):i.options=void 0,i},tt=(function(t){return t.UNLOADED="Page Unloaded",t})({}),jt="API",dt="CapabilitiesManager",j="ConfigManager",Bn="EventManager",Ie="PluginsManager",oe="UserSessionManager",Ae="ErrorHandler",de="PluginEngine",ti="StoreManager",nt=`Ready${jt}`,ni=`Load${jt}`,si="HttpClient",ii="RudderStackAnalytics",ke="AnalyticsCore";function ri(t){return crypto.getRandomValues(new Uint8Array(t))}var Jt=4096,Ue=[],ie=0,st;for(;ie<256;ie++)Ue[ie]=(ie+256).toString(16).substring(1);function oi(){(!st||ie+16>Jt)&&(st=ri(Jt),ie=0);for(var t=0,e,n="";t<16;t++)e=st[ie+t],t==6?n+=Ue[e&15|64]:t==8?n+=Ue[e&63|128]:n+=Ue[e],t&1&&t>1&&t<11&&(n+="-");return ie+=16,n}var ce=256,Me=[],Le;for(;ce--;)Me[ce]=(ce+256).toString(16).substring(1);function ai(){var t=0,e,n="";if(!Le||ce+16>256){for(Le=Array(t=256);t--;)Le[t]=256*Math.random()|0;t=ce=0}for(;t<16;t++)e=Le[ce+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 ce++,n}var li=()=>!W(globalThis.crypto)&&f(globalThis.crypto.getRandomValues),Ye=()=>li()?oi():ai(),ci=()=>!!window.chrome?.runtime?.id,ui=()=>_(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent),di=(t,e=!1)=>{let n=!1,s=!1;function i(){n||(n=!0,t(s),setTimeout(()=>{n=!1},0))}(e||ui())&&globalThis.addEventListener("beforeunload",()=>{s=!1,i()}),globalThis.addEventListener("blur",()=>{s=!0,i()}),globalThis.addEventListener("focus",()=>{n=!1}),document.addEventListener("pagehide",()=>{s=document.visibilityState==="hidden",i()}),document.addEventListener("visibilitychange",()=>{s=!0,document.visibilityState==="hidden"?i():n=!1})},xn=t=>t.toISOString(),gi=()=>xn(new Date),v=":: ",fi=t=>`A script with the id "${t}" is already loaded. Skipping the loading of this script to prevent conflicts`,Zt=(t,e,n)=>`Unable to load (${_(n)?n:n.type}) the script with the id "${t}" from URL "${e}"`,hi=(t,e,n)=>`A timeout of ${n} ms occurred while trying to load the script with id "${t}" from URL "${e}"`,pi=(t,e)=>`${t}${v}A circular reference has been detected in the object and the property "${e}" has been dropped from the output.`,vi="Failed to convert the value to a JSON string.",mi="Failed to encode the cookie data.",Ei=(t,e)=>`${t}${v}The "${e}" storage type is `,yi="JSONStringify",Si="[BigInt]",Gn="[Circular Reference]",Ii=(t,e,n)=>{let s=[];return function(i,r){if(!e?.includes(i)&&!(t&&W(r))){if(typeof r!="object"||G(r))return r;for(;s.length>0&&s[s.length-1]!==this;)s.pop();return s.includes(r)?(n?.warn(pi(yi,i)),Gn):(s.push(r),r)}}},K=(t,e,n,s)=>{try{return JSON.stringify(t,Ii(e,n,s))}catch(i){return s?.warn(vi,i),null}},bi=t=>{let e=[];return function(s,i){if(Ks(i))return Si;for(;e.length>0&&e[e.length-1]!==this;)e.pop();return e.includes(i)?Gn:(e.push(i),i)}},Fn=(t,e)=>{let n=Array.isArray(t)?[]:{};for(let s in t)if(Object.hasOwnProperty.call(t,s)){let i=t[s],r=e.call(t,s,i);O(r)||Array.isArray(r)?n[s]=Fn(r,e):n[s]=r}return n},y=(t,e)=>{let n=bi(),s=n.call(t,"",t);return O(t)||Array.isArray(t)?Fn(t,n):s},Vn="[SDK DISPATCHED ERROR]",qe=t=>{let{stack:e}=t;if(typeof e=="string"&&e)return e},Ht=(t,e)=>{if(!Gt(t))return new Error(`${e}: ${K(t)}`);try{let n=t.constructor,s=new n(`${e}: ${t.message}`),i=qe(t);return i&&(s.stack=i),Object.getOwnPropertyNames(t).forEach(r=>{if(r!=="message"&&r!=="stack"&&r!=="name")try{s[r]=t[r]}catch{}}),s}catch{return new Error(`${e}: ${K(t)}`)}},C=t=>{if(Gt(t)){let e=qe(t);e&&(t.stack=`${e}
3
- ${Vn}`)}globalThis.dispatchEvent(new ErrorEvent("error",{error:t,bubbles:!0,cancelable:!0,composed:!0}))},en="RudderLabs JavaScript SDK",Ne="3.31.0",Ti="com.rudderlabs.javascript",jn="npm",Ai="modern",tn="RudderJS-Initiated",Ri="ad-block page request",_i="/ad-blocked",_e="preloadedEventsBuffer",Oi="Consent Management Interaction",Ni="ajs_trait_",Pi="ajs_prop_",nn="ajs_aid",Ci="ajs_uid",sn="ajs_event",Di=10*1e3,ki=31536e3*1e3,rn=720*60*1e3,gt=1800*1e3,on=10*1e3,Li=10*1e3,wi=250,Hn=(t="app")=>{globalThis.RudderStackGlobals||(globalThis.RudderStackGlobals={}),globalThis.RudderStackGlobals[t]||(globalThis.RudderStackGlobals[t]={})},Pe=(t,e,n="app")=>{Hn(n),globalThis.RudderStackGlobals[n][t]=e},Kn=(t,e="app")=>(Hn(e),globalThis.RudderStackGlobals[e][t]);function Ui(t,e,n=wi){let s;return(...i)=>{globalThis.clearTimeout(s),s=globalThis.setTimeout(()=>{t.apply(e,i)},n)}}var an=(t,e)=>{let n={};return t.forEach((s,i)=>{if(i.startsWith(e)){let r=i.substring(e.length);n[r]=t.get(i)}}),n},Mi=(t=[])=>{let e={trait:Ni,properties:Pi},n=new URLSearchParams(globalThis.location.search);n.get(sn)&&t.unshift(["track",n.get(sn),an(n,e.properties)]);let s=n.get(Ci),i=an(n,e.trait);if(s||te(i)){let r=[...s?[s]:[],i];t.unshift(["identify",...r])}n.get(nn)&&t.unshift(["setAnonymousId",n.get(nn)])},$i=t=>{let e="load",n=[],s=0;for(;s<t.length;){if(t[s]&&t[s][0]===e){n=E(t[s]),t.splice(s,1);break}s+=1}return n},Bi=t=>{let e="consent",n=t.filter(i=>i[0]===e),s=t.filter(i=>i[0]!==e);t.splice(0,t.length,...n,...s)},xi=t=>{let e=Kn(_e)||[];Mi(e),e.length>0&&(t.enqueuePreloadBufferEvents(e),Pe(_e,[]))},Gi=(t,e)=>{let n=t.shift(),s;if(f(e[n])){switch(n){case"page":s=je(...t);break;case"track":s=Vt(...t);break;case"identify":s=Un(...t);break;case"alias":s=Mn(...t);break;case"group":s=$n(...t);break;default:e[n](...t);break}s&&e[n](s)}},Fi=10*1e3,Vi="RS_JS_SDK",ji=(t,e,n=!0,s=null,i=null,r={})=>{let a=document.createElement("script");return a.type="text/javascript",a.onload=s,a.onerror=i,a.src=t,a.id=e,a.async=n,Object.keys(r).forEach(l=>{a.setAttribute(l,r[l])}),a.setAttribute("data-loader",Vi),a},Hi=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 i=document.getElementsByTagName("html")[0];i?.insertBefore(s,i.firstChild)},Ki=(t,e,n,s=!0,i)=>new Promise((r,a)=>{document.getElementById(e)&&a(new Error(fi(e)));try{let u;Hi(ji(t,e,s,()=>{globalThis.clearTimeout(u),r(e)},S=>{globalThis.clearTimeout(u),a(new Error(Zt(e,t,S)))},i)),u=globalThis.setTimeout(()=>{a(new Error(hi(e,t,n)))},n)}catch(u){a(Ht(u,Zt(e,t,"unknown")))}}),He=class{constructor(e,n=Fi){this.logger=e,this.timeout=n}loadJSFile(e){let{url:n,id:s,timeout:i,async:r,callback:a,extraAttributes:l}=e,u=!f(a);Ki(n,s,i||this.timeout,r,l).then(d=>{u||a(d)}).catch(d=>{u||a(s,d)})}},Wi=Symbol.for("preact-signals");function Je(){if(ee>1)ee--;else{var t,e=!1;for((function(){var i=We;for(We=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();Oe!==void 0;){var n=Oe;for(Oe=void 0,Ke++;n!==void 0;){var s=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&zn(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=s}}if(Ke=0,ee--,e)throw t}}function w(t){if(ee>0)return t();ft=++Qi,ee++;try{return t()}finally{Je()}}var b=void 0;function Wn(t){var e=b;b=void 0;try{return t()}finally{b=e}}var Oe=void 0,ee=0,Ke=0,Qi=0,ft=0,We=void 0,Qe=0;function Qn(t){if(b!==void 0){var e=t.n;if(e===void 0||e.t!==b)return e={i:0,S:t,p:b.s,n:void 0,t:b,e:void 0,x:void 0,r:e},b.s!==void 0&&(b.s.n=e),b.s=e,t.n=e,32&b.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=b.s,e.n=void 0,b.s.n=e,b.s=e),e}}function M(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}M.prototype.brand=Wi;M.prototype.h=function(){return!0};M.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:Wn(function(){var s;(s=e.W)==null||s.call(e)}))};M.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&&Wn(function(){var i;(i=e.Z)==null||i.call(e)}))}};M.prototype.subscribe=function(t){var e=this;return X(function(){var n=e.value,s=b;b=void 0;try{t(n)}finally{b=s}},{name:"sub"})};M.prototype.valueOf=function(){return this.value};M.prototype.toString=function(){return this.value+""};M.prototype.toJSON=function(){return this.value};M.prototype.peek=function(){var t=b;b=void 0;try{return this.value}finally{b=t}};Object.defineProperty(M.prototype,"value",{get:function(){var t=Qn(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Ke>100)throw new Error("Cycle detected");(function(n){ee!==0&&Ke===0&&n.l!==ft&&(n.l=ft,We={S:n,v:n.v,i:n.i,o:We})})(this),this.v=t,this.i++,Qe++,ee++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Je()}}}});function c(t,e){return new M(t,e)}function zn(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 Xn(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 Yn(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 Ee(t,e){M.call(this,void 0),this.x=t,this.s=void 0,this.g=Qe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}Ee.prototype=new M;Ee.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Qe))return!0;if(this.g=Qe,this.f|=1,this.i>0&&!zn(this))return this.f&=-2,!0;var t=b;try{Xn(this),b=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 b=t,Yn(this),this.f&=-2,!0};Ee.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)}M.prototype.S.call(this,t)};Ee.prototype.U=function(t){if(this.t!==void 0&&(M.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)}};Ee.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(Ee.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Qn(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function qn(t){var e=t.m;if(t.m=void 0,typeof e=="function"){ee++;var n=b;b=void 0;try{e()}catch(s){throw t.f&=-2,t.f|=8,Kt(t),s}finally{b=n,Je()}}}function Kt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,qn(t)}function zi(t){if(b!==this)throw new Error("Out-of-order effect");Yn(this),b=t,this.f&=-2,8&this.f&&Kt(this),Je()}function ye(t,e){this.x=t,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=e?.name}ye.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.m=e)}finally{t()}};ye.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,qn(this),Xn(this),ee++;var t=b;return b=this,zi.bind(this,t)};ye.prototype.N=function(){2&this.f||(this.f|=2,this.u=Oe,Oe=this)};ye.prototype.d=function(){this.f|=8,1&this.f||Kt(this)};ye.prototype.dispose=function(){this.d()};function X(t,e){var n=new ye(t,e);try{n.c()}catch(i){throw n.d(),i}var s=n.d.bind(n);return s[Symbol.dispose]=s,s}var ht=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=[]}},we={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5},ln="LOG",Jn="ERROR",Xi="RS SDK",Yi="font-weight: bold; background: black; color: white;",qi="font-weight: normal;",pt=class{constructor(e=ln,n="",s=console){this.minLogLevel=we[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<=we[e]&&this.logProvider[e.toLowerCase()]?.(...this.formatLogData(n))}setScope(e){this.scope=e||this.scope}setMinLogLevel(e){this.minLogLevel=we[e],U(this.minLogLevel)&&(this.minLogLevel=we[ln])}formatLogData(e){if(Array.isArray(e)&&e.length>0){let n=`%c ${Xi}`;this.scope&&(n=`${n} - ${this.scope}`);let s=_(e[0])?e[0].trim():"";n=`${n} %c ${s}`;let i=[n,Yi,qi];return _(e[0])||i.push(e[0]),i.push(...e.slice(1)),i}return e}},ne=new pt,q=(function(t){return t.HANDLEDEXCEPTION="handledException",t.UNHANDLEDEXCEPTION="unhandledException",t.UNHANDLEDREJECTION="unhandledPromiseRejection",t})({}),Zn=["localStorage","memoryStorage","cookieStorage","sessionStorage","none"],vt="cookieStorage",cn="Unable to process/parse source configuration response",Ji="The source is disabled. Please enable the source in the dashboard to send events.",Zi="Failed to prepare data for the request.",er="Failed to invoke plugin because the extension point name is missing.",tr="Failed to invoke plugin because the extension point name is invalid.",nr=t=>`${t}${v}The "getSourceConfig" load API option must be a function that returns valid source configuration data.`,sr=(t,e,n)=>`${t}${v}The base URL "${n}" for ${e} is not valid.`,ir=(t,e,n)=>`${t}${v}The consent manager "${e}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(n)}".`,rr=(t,e)=>`${t}${v}Ignoring a non-error: ${e}.`,un="Failed to log breadcrumb",or=t=>`${t}${v}Failed to handle the error.`,ar=t=>`${t}${v}Plugin name is missing.`,lr=(t,e)=>`${t}${v}Plugin "${e}" already exists.`,cr=(t,e)=>`${t}${v}Plugin "${e}" not found.`,ur=(t,e)=>`${t}${v}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.`,dr=(t,e,n)=>`${t}${v}Plugin "${e}" could not be loaded because some of its dependencies "${n}" do not exist.`,gr=(t,e,n)=>`${t}${v}Failed to invoke the "${e}" extension point of plugin "${n}".`,dn="Failed to fetch the source config",fr=(t,e)=>`${t}${v}The write key "${e}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`,hr=(t,e)=>`${t}${v}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.`,es=t=>`${t}${v}The provided callback parameter is not a function.`,pr=(t,e,n,s,i)=>`${t} with status ${e} (${n}) for URL: ${s}. Response: ${i.trim()}`,vr=(t,e,n)=>`${t} due to timeout or no connection (${e?e.type:""}) at the client side for URL: ${n}`,mr=(t,e)=>`${t} for URL: ${e}`,Er=t=>`Failed to save the value for "${t}" to storage`,yr=t=>`Failed to retrieve or parse data for "${t}" from storage`,Sr=t=>`The server responded with status ${t} while setting the cookies. As a fallback, the cookies will be set client side.`,Ir=t=>`The server failed to set the ${t} cookie. As a fallback, the cookies will be set client side.`,gn="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.",br=(t,e,n)=>`${t}${v}The storage type "${e}" is not supported. Please choose one of the following supported types: "${Zn}". The default type "${n}" will be used instead.`,Tr=(t,e,n,s)=>`${t}${v}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.`,Ar=(t,e,n)=>`${t}${v}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.`,Rr=(t,e,n)=>`${t}${v}The provided cookie domain (${e}) does not match the current webpage's domain (${n}). Hence, the cookies will be set client-side.`,_r=(t,e,n,s)=>`${t}${v}The "${e}" property defined under "${n}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${s}).`,Or=t=>`${t}${v}Please make sure that the "context" property in the event API's "options" argument is a valid object literal with key-value pairs.`,Nr=t=>`${t}${v}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`,Pr=(t,e,n)=>`${t}${v}The session timeout value "${e}" is not a number. The default timeout of ${n} ms will be used instead.`,Cr=(t,e,n)=>`${t}${v}The session cut off duration value "${e}" is not a number. The default cut off duration of ${n} ms will be used instead.`,Dr=(t,e,n)=>`${t}${v}The session cut off duration value "${e}" ms is less than the session timeout value "${n}" ms. The cut off functionality will be disabled.`,kr=t=>`${t}${v}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.`,Lr=(t,e,n)=>`${t}${v}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.`,wr=(t,e,n)=>`${t}${v}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.`,Ur=t=>`${t}${v}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`,Mr=(t,e,n,s)=>`${t}${v}The storage type "${n}" is not available for entry "${e}". The SDK will initialize the entry with "${s}" storage type instead.`,$r=t=>`${t}${v}The callback threw an exception`,Br=(t,e)=>`${t}${v}The provided source config URL "${e}" is invalid. Using the default source config URL instead.`,xr=(t,e)=>`Failed to load the polyfill script with ID "${t}" from URL ${e}.`,Gr=(t,e,n)=>`${t}${v}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.`,Fr=(t,e,n)=>`${t}${v}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.`,Vr=(t,e)=>`${t}${v}${e} plugin is deprecated. Please exclude it from the load API options.`,jr=(t,e,n,s)=>{let i=n.length===1,r=i?` '${n[0]}' plugin was`:` ['${n.join("', '")}'] plugins were`,a=`${t}${v}${e}, but${r} not configured to load.`;return s?`${a} So, ${i?"the plugin":"those plugins"} will be loaded automatically.`:`${a} Ignore if this was intentional. Otherwise, consider adding ${i?"it":"them"} to the 'plugins' load API option.`},Hr=(t,e)=>`${t}${v}The provided polyfill URL "${e}" is invalid. The default polyfill URL will be used instead.`,Kr=t=>`${t}${v}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`,Wr=(t,e)=>`${t}${v}Ignoring unknown plugins: ${e.join(", ")}.`,Qr=(t,e)=>`${t}${v}Failed to load the following unavailable local plugins: ${e.join(", ")}. Some features of the SDK may not work as expected. Make sure you are using the correct SDK bundle variant.`,zr=(t,e)=>`${t}${v}Cannot add custom integration for destination ID "${e}" after the SDK is loaded.`,ts={All:!0},Ze="js-integrations",ns="plugins",Xr=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_]*)?$"),Ce="modern",et="https://cdn.rudderlabs.com",Wt="v3",ss=`${et}/${Wt}/${Ce}/${Ze}`,is=`${et}/${Wt}/${Ce}/${ns}`,rs="https://api.rudderstack.com",ae="v3",Yr="xhr",mt={iubenda:"IubendaConsentManager",oneTrust:"OneTrustConsentManager",ketch:"KetchConsentManager",custom:"CustomConsentManager"},$e={[ae]:"StorageEncryption",legacy:"StorageEncryptionLegacy"},qr={[Yr]:"XhrQueue",beacon:"BeaconQueue"},Jr="rsaRequest",Zr="rsaMetrics",eo="Custom Device Mode",to={configUrl:rs,loadIntegration:!0,sessions:{autoTrack:!0,timeout:gt,cutOff:{enabled:!1}},sameSiteCookie:"Lax",polyfillIfRequired:!0,integrations:ts,useBeacon:!1,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:!0,lockPluginsVersion:!0,uaChTrackLevel:"none",plugins:[],useGlobalIntegrationsConfigInEvents:!1,bufferDataPlaneEventsUntilReady:!1,dataPlaneEventsBufferTimeout:Li,storage:{encryption:{version:ae},migrate:!0,cookie:{}},sendAdblockPage:!1,sameDomainCookiesOnly:!1,secureCookie:!1,sendAdblockPageOptions:{},useServerSideCookies:!1},no=c(E(to)),T=Ft({userId:"",userTraits:{},anonymousId:"",groupId:"",groupTraits:{},initialReferrer:"",initialReferringDomain:"",sessionInfo:{},authToken:null}),it=Ft({entries:{userId:!0,userTraits:!0,groupId:!0,groupTraits:!0,sessionInfo:!0,authToken:!0,anonymousId:!1,initialReferrer:!1,initialReferringDomain:!1}}),so=10,io={userId:c(T.userId),userTraits:c(T.userTraits),anonymousId:c(T.anonymousId),groupId:c(T.groupId),groupTraits:c(T.groupTraits),initialReferrer:c(T.initialReferrer),initialReferringDomain:c(T.initialReferringDomain),sessionInfo:c(T.sessionInfo),authToken:c(T.authToken)},ro={isOnline:c(!0),storage:{isLocalStorageAvailable:c(!1),isCookieStorageAvailable:c(!1),isSessionStorageAvailable:c(!1)},isBeaconAvailable:c(!1),isLegacyDOM:c(!1),isUaCHAvailable:c(!1),isCryptoAvailable:c(!1),isAdBlockerDetectionInProgress:c(!1),isAdBlocked:c(void 0),cspBlockedURLs:c([])},oo={isErrorReportingEnabled:c(!1),isMetricsReportingEnabled:c(!1),breadcrumbs:c([])},ao=c(void 0),lo={activeDataplaneUrl:c(void 0),integrationsCDNPath:c(ss),pluginsCDNPath:c(is),sourceConfigUrl:c(void 0),status:c(void 0),initialized:c(!1),logLevel:c(Jn),loaded:c(!1),readyCallbacks:c([]),writeKey:c(void 0),dataPlaneUrl:c(void 0),safeAnalyticsInstance:c(void 0)},co={enabled:c(!1),initialized:c(!1),data:c({}),activeConsentManagerPluginName:c(void 0),preConsent:c({enabled:!1}),postConsent:c({}),resolutionStrategy:c("and"),provider:c(void 0),metadata:c(void 0)},uo={retries:c(0),dropped:c(0),sent:c(0),queued:c(0),triggered:c(0),metricsServiceUrl:c(void 0)},go=()=>Ai,fo={app:c({name:en,namespace:Ti,version:Ne,installType:jn}),traits:c(null),library:c({name:en,version:Ne,snippetVersion:globalThis.RudderSnippetVersion,variant:go()}),userAgent:c(null),device:c(null),network:c(null),os:c({name:"",version:""}),locale:c(null),screen:c({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),"ua-ch":c(void 0),timezone:c(void 0)},ho={configuredDestinations:c([]),activeDestinations:c([]),loadOnlyIntegrations:c({}),failedDestinations:c([]),loadIntegration:c(!0),initializedDestinations:c([]),clientDestinationsReady:c(!1),integrationsConfig:c({})},po={toBeProcessedArray:c([]),readyCallbacksArray:c([])},vo={ready:c(!1),loadedPlugins:c([]),failedPlugins:c([]),pluginsToLoadFromConfig:c([]),activePlugins:c([]),totalPluginsToLoad:c(0)},mo={encryptionPluginName:c(void 0),migrate:c(!1),type:c(void 0),cookie:c(void 0),entries:c({}),trulyAnonymousTracking:c(!1)},Eo={isEnabledServerSideCookies:c(!1),dataServiceUrl:c(void 0)},yo={eventsQueuePluginName:c(void 0),deliveryEnabled:c(!0)},So={enabled:c(!1),pageLifecycle:{enabled:c(!1),pageViewId:c(void 0),pageLoadedTimestamp:c(void 0)}},Io={capabilities:ro,consents:co,context:fo,eventBuffer:po,lifecycle:lo,loadOptions:no,metrics:uo,nativeDestinations:ho,plugins:vo,reporting:oo,session:io,source:ao,storage:mo,serverCookies:Eo,dataPlaneEvents:yo,autoTrack:So},o={...E(Io)},os=/^\s*at /,bo=/^(eval@)?(\[native code])?$/,To=/(.+?)(?::(\d+))?(?::(\d+))?$/;function as(t){if(!t?.includes(":"))return[t||void 0,void 0,void 0];let e=t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1):t,n=To.exec(e);return n?[n[1]||void 0,n[2]===void 0?void 0:Number(n[2]),n[3]===void 0?void 0:Number(n[3])]:[void 0,void 0,void 0]}function Ao(t){if(!os.test(t))return null;t.includes("(eval ")&&(t=t.replaceAll("eval code","eval").replaceAll(/(\(eval at [^()]*)|(,.*$)/g,""));let e=t.replace(/^\s+/,"").replaceAll("(eval code","(").replace(/^.*?\s+/,""),n=/ (\(.+\)$)/.exec(e),s=n?e.replace(n[0],""):e,[i,r,a]=as(n?n[1]:e);return{functionName:n&&s||void 0,fileName:i==="eval"||i==="<anonymous>"?void 0:i,lineNumber:r,columnNumber:a}}function Ro(t){if(bo.test(t))return null;if(t.includes(" > eval")&&(t=t.replaceAll(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),!t.includes("@")&&!t.includes(":"))return{functionName:t,fileName:void 0,lineNumber:void 0,columnNumber:void 0};let e=t.lastIndexOf("@"),n=e>0?t.slice(0,e):void 0,[s,i,r]=as(t.slice(e+1));return{functionName:n,fileName:s,lineNumber:i,columnNumber:r}}function _o(t){if(!t.stack)throw new Error("Cannot parse given Error object");let e=t.stack.split(`
3
+ ${Vn}`)}globalThis.dispatchEvent(new ErrorEvent("error",{error:t,bubbles:!0,cancelable:!0,composed:!0}))},en="RudderLabs JavaScript SDK",Ne="3.31.1",Ti="com.rudderlabs.javascript",jn="npm",Ai="modern",tn="RudderJS-Initiated",Ri="ad-block page request",_i="/ad-blocked",_e="preloadedEventsBuffer",Oi="Consent Management Interaction",Ni="ajs_trait_",Pi="ajs_prop_",nn="ajs_aid",Ci="ajs_uid",sn="ajs_event",Di=10*1e3,ki=31536e3*1e3,rn=720*60*1e3,gt=1800*1e3,on=10*1e3,Li=10*1e3,wi=250,Hn=(t="app")=>{globalThis.RudderStackGlobals||(globalThis.RudderStackGlobals={}),globalThis.RudderStackGlobals[t]||(globalThis.RudderStackGlobals[t]={})},Pe=(t,e,n="app")=>{Hn(n),globalThis.RudderStackGlobals[n][t]=e},Kn=(t,e="app")=>(Hn(e),globalThis.RudderStackGlobals[e][t]);function Ui(t,e,n=wi){let s;return(...i)=>{globalThis.clearTimeout(s),s=globalThis.setTimeout(()=>{t.apply(e,i)},n)}}var an=(t,e)=>{let n={};return t.forEach((s,i)=>{if(i.startsWith(e)){let r=i.substring(e.length);n[r]=t.get(i)}}),n},Mi=(t=[])=>{let e={trait:Ni,properties:Pi},n=new URLSearchParams(globalThis.location.search);n.get(sn)&&t.unshift(["track",n.get(sn),an(n,e.properties)]);let s=n.get(Ci),i=an(n,e.trait);if(s||te(i)){let r=[...s?[s]:[],i];t.unshift(["identify",...r])}n.get(nn)&&t.unshift(["setAnonymousId",n.get(nn)])},$i=t=>{let e="load",n=[],s=0;for(;s<t.length;){if(t[s]&&t[s][0]===e){n=E(t[s]),t.splice(s,1);break}s+=1}return n},Bi=t=>{let e="consent",n=t.filter(i=>i[0]===e),s=t.filter(i=>i[0]!==e);t.splice(0,t.length,...n,...s)},xi=t=>{let e=Kn(_e)||[];Mi(e),e.length>0&&(t.enqueuePreloadBufferEvents(e),Pe(_e,[]))},Gi=(t,e)=>{let n=t.shift(),s;if(f(e[n])){switch(n){case"page":s=je(...t);break;case"track":s=Vt(...t);break;case"identify":s=Un(...t);break;case"alias":s=Mn(...t);break;case"group":s=$n(...t);break;default:e[n](...t);break}s&&e[n](s)}},Fi=10*1e3,Vi="RS_JS_SDK",ji=(t,e,n=!0,s=null,i=null,r={})=>{let a=document.createElement("script");return a.type="text/javascript",a.onload=s,a.onerror=i,a.src=t,a.id=e,a.async=n,Object.keys(r).forEach(l=>{a.setAttribute(l,r[l])}),a.setAttribute("data-loader",Vi),a},Hi=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 i=document.getElementsByTagName("html")[0];i?.insertBefore(s,i.firstChild)},Ki=(t,e,n,s=!0,i)=>new Promise((r,a)=>{document.getElementById(e)&&a(new Error(fi(e)));try{let u;Hi(ji(t,e,s,()=>{globalThis.clearTimeout(u),r(e)},S=>{globalThis.clearTimeout(u),a(new Error(Zt(e,t,S)))},i)),u=globalThis.setTimeout(()=>{a(new Error(hi(e,t,n)))},n)}catch(u){a(Ht(u,Zt(e,t,"unknown")))}}),He=class{constructor(e,n=Fi){this.logger=e,this.timeout=n}loadJSFile(e){let{url:n,id:s,timeout:i,async:r,callback:a,extraAttributes:l}=e,u=!f(a);Ki(n,s,i||this.timeout,r,l).then(d=>{u||a(d)}).catch(d=>{u||a(s,d)})}},Wi=Symbol.for("preact-signals");function Je(){if(ee>1)ee--;else{var t,e=!1;for((function(){var i=We;for(We=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();Oe!==void 0;){var n=Oe;for(Oe=void 0,Ke++;n!==void 0;){var s=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&zn(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=s}}if(Ke=0,ee--,e)throw t}}function w(t){if(ee>0)return t();ft=++Qi,ee++;try{return t()}finally{Je()}}var b=void 0;function Wn(t){var e=b;b=void 0;try{return t()}finally{b=e}}var Oe=void 0,ee=0,Ke=0,Qi=0,ft=0,We=void 0,Qe=0;function Qn(t){if(b!==void 0){var e=t.n;if(e===void 0||e.t!==b)return e={i:0,S:t,p:b.s,n:void 0,t:b,e:void 0,x:void 0,r:e},b.s!==void 0&&(b.s.n=e),b.s=e,t.n=e,32&b.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=b.s,e.n=void 0,b.s.n=e,b.s=e),e}}function M(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}M.prototype.brand=Wi;M.prototype.h=function(){return!0};M.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:Wn(function(){var s;(s=e.W)==null||s.call(e)}))};M.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&&Wn(function(){var i;(i=e.Z)==null||i.call(e)}))}};M.prototype.subscribe=function(t){var e=this;return X(function(){var n=e.value,s=b;b=void 0;try{t(n)}finally{b=s}},{name:"sub"})};M.prototype.valueOf=function(){return this.value};M.prototype.toString=function(){return this.value+""};M.prototype.toJSON=function(){return this.value};M.prototype.peek=function(){var t=b;b=void 0;try{return this.value}finally{b=t}};Object.defineProperty(M.prototype,"value",{get:function(){var t=Qn(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Ke>100)throw new Error("Cycle detected");(function(n){ee!==0&&Ke===0&&n.l!==ft&&(n.l=ft,We={S:n,v:n.v,i:n.i,o:We})})(this),this.v=t,this.i++,Qe++,ee++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Je()}}}});function c(t,e){return new M(t,e)}function zn(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 Xn(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 Yn(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 Ee(t,e){M.call(this,void 0),this.x=t,this.s=void 0,this.g=Qe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}Ee.prototype=new M;Ee.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Qe))return!0;if(this.g=Qe,this.f|=1,this.i>0&&!zn(this))return this.f&=-2,!0;var t=b;try{Xn(this),b=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 b=t,Yn(this),this.f&=-2,!0};Ee.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)}M.prototype.S.call(this,t)};Ee.prototype.U=function(t){if(this.t!==void 0&&(M.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)}};Ee.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(Ee.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Qn(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function qn(t){var e=t.m;if(t.m=void 0,typeof e=="function"){ee++;var n=b;b=void 0;try{e()}catch(s){throw t.f&=-2,t.f|=8,Kt(t),s}finally{b=n,Je()}}}function Kt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,qn(t)}function zi(t){if(b!==this)throw new Error("Out-of-order effect");Yn(this),b=t,this.f&=-2,8&this.f&&Kt(this),Je()}function ye(t,e){this.x=t,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=e?.name}ye.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.m=e)}finally{t()}};ye.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,qn(this),Xn(this),ee++;var t=b;return b=this,zi.bind(this,t)};ye.prototype.N=function(){2&this.f||(this.f|=2,this.u=Oe,Oe=this)};ye.prototype.d=function(){this.f|=8,1&this.f||Kt(this)};ye.prototype.dispose=function(){this.d()};function X(t,e){var n=new ye(t,e);try{n.c()}catch(i){throw n.d(),i}var s=n.d.bind(n);return s[Symbol.dispose]=s,s}var ht=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=[]}},we={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5},ln="LOG",Jn="ERROR",Xi="RS SDK",Yi="font-weight: bold; background: black; color: white;",qi="font-weight: normal;",pt=class{constructor(e=ln,n="",s=console){this.minLogLevel=we[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<=we[e]&&this.logProvider[e.toLowerCase()]?.(...this.formatLogData(n))}setScope(e){this.scope=e||this.scope}setMinLogLevel(e){this.minLogLevel=we[e],U(this.minLogLevel)&&(this.minLogLevel=we[ln])}formatLogData(e){if(Array.isArray(e)&&e.length>0){let n=`%c ${Xi}`;this.scope&&(n=`${n} - ${this.scope}`);let s=_(e[0])?e[0].trim():"";n=`${n} %c ${s}`;let i=[n,Yi,qi];return _(e[0])||i.push(e[0]),i.push(...e.slice(1)),i}return e}},ne=new pt,q=(function(t){return t.HANDLEDEXCEPTION="handledException",t.UNHANDLEDEXCEPTION="unhandledException",t.UNHANDLEDREJECTION="unhandledPromiseRejection",t})({}),Zn=["localStorage","memoryStorage","cookieStorage","sessionStorage","none"],vt="cookieStorage",cn="Unable to process/parse source configuration response",Ji="The source is disabled. Please enable the source in the dashboard to send events.",Zi="Failed to prepare data for the request.",er="Failed to invoke plugin because the extension point name is missing.",tr="Failed to invoke plugin because the extension point name is invalid.",nr=t=>`${t}${v}The "getSourceConfig" load API option must be a function that returns valid source configuration data.`,sr=(t,e,n)=>`${t}${v}The base URL "${n}" for ${e} is not valid.`,ir=(t,e,n)=>`${t}${v}The consent manager "${e}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(n)}".`,rr=(t,e)=>`${t}${v}Ignoring a non-error: ${e}.`,un="Failed to log breadcrumb",or=t=>`${t}${v}Failed to handle the error.`,ar=t=>`${t}${v}Plugin name is missing.`,lr=(t,e)=>`${t}${v}Plugin "${e}" already exists.`,cr=(t,e)=>`${t}${v}Plugin "${e}" not found.`,ur=(t,e)=>`${t}${v}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.`,dr=(t,e,n)=>`${t}${v}Plugin "${e}" could not be loaded because some of its dependencies "${n}" do not exist.`,gr=(t,e,n)=>`${t}${v}Failed to invoke the "${e}" extension point of plugin "${n}".`,dn="Failed to fetch the source config",fr=(t,e)=>`${t}${v}The write key "${e}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`,hr=(t,e)=>`${t}${v}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.`,es=t=>`${t}${v}The provided callback parameter is not a function.`,pr=(t,e,n,s,i)=>`${t} with status ${e} (${n}) for URL: ${s}. Response: ${i.trim()}`,vr=(t,e,n)=>`${t} due to timeout or no connection (${e?e.type:""}) at the client side for URL: ${n}`,mr=(t,e)=>`${t} for URL: ${e}`,Er=t=>`Failed to save the value for "${t}" to storage`,yr=t=>`Failed to retrieve or parse data for "${t}" from storage`,Sr=t=>`The server responded with status ${t} while setting the cookies. As a fallback, the cookies will be set client side.`,Ir=t=>`The server failed to set the ${t} cookie. As a fallback, the cookies will be set client side.`,gn="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.",br=(t,e,n)=>`${t}${v}The storage type "${e}" is not supported. Please choose one of the following supported types: "${Zn}". The default type "${n}" will be used instead.`,Tr=(t,e,n,s)=>`${t}${v}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.`,Ar=(t,e,n)=>`${t}${v}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.`,Rr=(t,e,n)=>`${t}${v}The provided cookie domain (${e}) does not match the current webpage's domain (${n}). Hence, the cookies will be set client-side.`,_r=(t,e,n,s)=>`${t}${v}The "${e}" property defined under "${n}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${s}).`,Or=t=>`${t}${v}Please make sure that the "context" property in the event API's "options" argument is a valid object literal with key-value pairs.`,Nr=t=>`${t}${v}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`,Pr=(t,e,n)=>`${t}${v}The session timeout value "${e}" is not a number. The default timeout of ${n} ms will be used instead.`,Cr=(t,e,n)=>`${t}${v}The session cut off duration value "${e}" is not a number. The default cut off duration of ${n} ms will be used instead.`,Dr=(t,e,n)=>`${t}${v}The session cut off duration value "${e}" ms is less than the session timeout value "${n}" ms. The cut off functionality will be disabled.`,kr=t=>`${t}${v}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.`,Lr=(t,e,n)=>`${t}${v}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.`,wr=(t,e,n)=>`${t}${v}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.`,Ur=t=>`${t}${v}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`,Mr=(t,e,n,s)=>`${t}${v}The storage type "${n}" is not available for entry "${e}". The SDK will initialize the entry with "${s}" storage type instead.`,$r=t=>`${t}${v}The callback threw an exception`,Br=(t,e)=>`${t}${v}The provided source config URL "${e}" is invalid. Using the default source config URL instead.`,xr=(t,e)=>`Failed to load the polyfill script with ID "${t}" from URL ${e}.`,Gr=(t,e,n)=>`${t}${v}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.`,Fr=(t,e,n)=>`${t}${v}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.`,Vr=(t,e)=>`${t}${v}${e} plugin is deprecated. Please exclude it from the load API options.`,jr=(t,e,n,s)=>{let i=n.length===1,r=i?` '${n[0]}' plugin was`:` ['${n.join("', '")}'] plugins were`,a=`${t}${v}${e}, but${r} not configured to load.`;return s?`${a} So, ${i?"the plugin":"those plugins"} will be loaded automatically.`:`${a} Ignore if this was intentional. Otherwise, consider adding ${i?"it":"them"} to the 'plugins' load API option.`},Hr=(t,e)=>`${t}${v}The provided polyfill URL "${e}" is invalid. The default polyfill URL will be used instead.`,Kr=t=>`${t}${v}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`,Wr=(t,e)=>`${t}${v}Ignoring unknown plugins: ${e.join(", ")}.`,Qr=(t,e)=>`${t}${v}Failed to load the following unavailable local plugins: ${e.join(", ")}. Some features of the SDK may not work as expected. Make sure you are using the correct SDK bundle variant.`,zr=(t,e)=>`${t}${v}Cannot add custom integration for destination ID "${e}" after the SDK is loaded.`,ts={All:!0},Ze="js-integrations",ns="plugins",Xr=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_]*)?$"),Ce="modern",et="https://cdn.rudderlabs.com",Wt="v3",ss=`${et}/${Wt}/${Ce}/${Ze}`,is=`${et}/${Wt}/${Ce}/${ns}`,rs="https://api.rudderstack.com",ae="v3",Yr="xhr",mt={iubenda:"IubendaConsentManager",oneTrust:"OneTrustConsentManager",ketch:"KetchConsentManager",custom:"CustomConsentManager"},$e={[ae]:"StorageEncryption",legacy:"StorageEncryptionLegacy"},qr={[Yr]:"XhrQueue",beacon:"BeaconQueue"},Jr="rsaRequest",Zr="rsaMetrics",eo="Custom Device Mode",to={configUrl:rs,loadIntegration:!0,sessions:{autoTrack:!0,timeout:gt,cutOff:{enabled:!1}},sameSiteCookie:"Lax",polyfillIfRequired:!0,integrations:ts,useBeacon:!1,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:!0,lockPluginsVersion:!0,uaChTrackLevel:"none",plugins:[],useGlobalIntegrationsConfigInEvents:!1,bufferDataPlaneEventsUntilReady:!1,dataPlaneEventsBufferTimeout:Li,storage:{encryption:{version:ae},migrate:!0,cookie:{}},sendAdblockPage:!1,sameDomainCookiesOnly:!1,secureCookie:!1,sendAdblockPageOptions:{},useServerSideCookies:!1},no=c(E(to)),T=Ft({userId:"",userTraits:{},anonymousId:"",groupId:"",groupTraits:{},initialReferrer:"",initialReferringDomain:"",sessionInfo:{},authToken:null}),it=Ft({entries:{userId:!0,userTraits:!0,groupId:!0,groupTraits:!0,sessionInfo:!0,authToken:!0,anonymousId:!1,initialReferrer:!1,initialReferringDomain:!1}}),so=10,io={userId:c(T.userId),userTraits:c(T.userTraits),anonymousId:c(T.anonymousId),groupId:c(T.groupId),groupTraits:c(T.groupTraits),initialReferrer:c(T.initialReferrer),initialReferringDomain:c(T.initialReferringDomain),sessionInfo:c(T.sessionInfo),authToken:c(T.authToken)},ro={isOnline:c(!0),storage:{isLocalStorageAvailable:c(!1),isCookieStorageAvailable:c(!1),isSessionStorageAvailable:c(!1)},isBeaconAvailable:c(!1),isLegacyDOM:c(!1),isUaCHAvailable:c(!1),isCryptoAvailable:c(!1),isAdBlockerDetectionInProgress:c(!1),isAdBlocked:c(void 0),cspBlockedURLs:c([])},oo={isErrorReportingEnabled:c(!1),isMetricsReportingEnabled:c(!1),breadcrumbs:c([])},ao=c(void 0),lo={activeDataplaneUrl:c(void 0),integrationsCDNPath:c(ss),pluginsCDNPath:c(is),sourceConfigUrl:c(void 0),status:c(void 0),initialized:c(!1),logLevel:c(Jn),loaded:c(!1),readyCallbacks:c([]),writeKey:c(void 0),dataPlaneUrl:c(void 0),safeAnalyticsInstance:c(void 0)},co={enabled:c(!1),initialized:c(!1),data:c({}),activeConsentManagerPluginName:c(void 0),preConsent:c({enabled:!1}),postConsent:c({}),resolutionStrategy:c("and"),provider:c(void 0),metadata:c(void 0)},uo={retries:c(0),dropped:c(0),sent:c(0),queued:c(0),triggered:c(0),metricsServiceUrl:c(void 0)},go=()=>Ai,fo={app:c({name:en,namespace:Ti,version:Ne,installType:jn}),traits:c(null),library:c({name:en,version:Ne,snippetVersion:globalThis.RudderSnippetVersion,variant:go()}),userAgent:c(null),device:c(null),network:c(null),os:c({name:"",version:""}),locale:c(null),screen:c({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),"ua-ch":c(void 0),timezone:c(void 0)},ho={configuredDestinations:c([]),activeDestinations:c([]),loadOnlyIntegrations:c({}),failedDestinations:c([]),loadIntegration:c(!0),initializedDestinations:c([]),clientDestinationsReady:c(!1),integrationsConfig:c({})},po={toBeProcessedArray:c([]),readyCallbacksArray:c([])},vo={ready:c(!1),loadedPlugins:c([]),failedPlugins:c([]),pluginsToLoadFromConfig:c([]),activePlugins:c([]),totalPluginsToLoad:c(0)},mo={encryptionPluginName:c(void 0),migrate:c(!1),type:c(void 0),cookie:c(void 0),entries:c({}),trulyAnonymousTracking:c(!1)},Eo={isEnabledServerSideCookies:c(!1),dataServiceUrl:c(void 0)},yo={eventsQueuePluginName:c(void 0),deliveryEnabled:c(!0)},So={enabled:c(!1),pageLifecycle:{enabled:c(!1),pageViewId:c(void 0),pageLoadedTimestamp:c(void 0)}},Io={capabilities:ro,consents:co,context:fo,eventBuffer:po,lifecycle:lo,loadOptions:no,metrics:uo,nativeDestinations:ho,plugins:vo,reporting:oo,session:io,source:ao,storage:mo,serverCookies:Eo,dataPlaneEvents:yo,autoTrack:So},o={...E(Io)},os=/^\s*at /,bo=/^(eval@)?(\[native code])?$/,To=/(.+?)(?::(\d+))?(?::(\d+))?$/;function as(t){if(!t?.includes(":"))return[t||void 0,void 0,void 0];let e=t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1):t,n=To.exec(e);return n?[n[1]||void 0,n[2]===void 0?void 0:Number(n[2]),n[3]===void 0?void 0:Number(n[3])]:[void 0,void 0,void 0]}function Ao(t){if(!os.test(t))return null;t.includes("(eval ")&&(t=t.replaceAll("eval code","eval").replaceAll(/(\(eval at [^()]*)|(,.*$)/g,""));let e=t.replace(/^\s+/,"").replaceAll("(eval code","(").replace(/^.*?\s+/,""),n=/ (\(.+\)$)/.exec(e),s=n?e.replace(n[0],""):e,[i,r,a]=as(n?n[1]:e);return{functionName:n&&s||void 0,fileName:i==="eval"||i==="<anonymous>"?void 0:i,lineNumber:r,columnNumber:a}}function Ro(t){if(bo.test(t))return null;if(t.includes(" > eval")&&(t=t.replaceAll(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),!t.includes("@")&&!t.includes(":"))return{functionName:t,fileName:void 0,lineNumber:void 0,columnNumber:void 0};let e=t.lastIndexOf("@"),n=e>0?t.slice(0,e):void 0,[s,i,r]=as(t.slice(e+1));return{functionName:n,fileName:s,lineNumber:i,columnNumber:r}}function _o(t){if(!t.stack)throw new Error("Cannot parse given Error object");let e=t.stack.split(`
4
4
  `);return e.some(n=>os.test(n))?e.map(Ao).filter(n=>n!==null):e.map(Ro).filter(n=>n!==null)}var ls="global code",Oo=t=>A(t)&&/^global code$/i.test(t)?ls:t,No=t=>{let e={file:t.fileName,method:Oo(t.functionName),lineNumber:t.lineNumber,columnNumber:t.columnNumber};return e.lineNumber&&e.lineNumber>-1&&!e.file&&!e.method&&(e.file=ls),e},fn=t=>_(t)?t:"";function hn(t,e,n,s){return{errorClass:fn(t),message:`${n}${fn(e)}`,type:"browserjs",stacktrace:s.reduce((i,r)=>{let a=No(r);try{return JSON.stringify(a)==="{}"?i:i.concat(a)}catch{return i}},[])}}var cs=(t,e)=>{let n;return Gt(t)&&_(qe(t))?n=t:(e.warn(rr(Ae,K(t))),n=void 0),n},Po=(t,e)=>{try{let n=_o(t);return hn(t.name,t.message,e,n)}catch{return hn(t.name,t.message,e,[])}},pn=(t,e)=>{try{return JSON.parse(t||"")}catch(n){let s=Ht(n,"Failed to parse response data");e(s)}},Be="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 .*/],ko=[new RegExp(`${Be}.*`),/A script with the id .* is already loaded\./],Lo=[...Co,...Do],wo="integrations",Uo="sdk",Mo=Uo,$o={headers:{Accept:"application/json","Content-Type":"application/json;charset=UTF-8"},method:"GET"},vn=(t,e,n)=>{let s=L($o,e||{});return n&&(s.headers=L(s.headers,{Authorization:n})),s.url=t,s},mn=(t,e=Di,n)=>new Promise((s,i)=>{let r;if(t.sendRawData===!0)r=t.data;else if(r=K(t.data,!1,[],n),G(r)){i({error:new Error(Zi),undefined:void 0,options:t});return}let a=new XMLHttpRequest,l=d=>{i({error:new Error(pr(Be,a.status,a.statusText,t.url,a.responseText)),xhr:a,options:t})},u=d=>{i({error:new Error(vr(Be,d,t.url)),xhr:a,options:t,...d?.type==="timeout"?{timedOut:!0}:{}})};a.ontimeout=u,a.onerror=u,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(r)}catch(d){i({error:Ht(d,mr(Be,t.url)),xhr:a,options:t})}}),Et=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:i,isRawResponse:r}=e;try{let a=await mn(vn(n,s,this.basicAuthHeader),i,this.logger);return{data:r?a.response:pn(a.response,this.onError),details:a}}catch(a){return{data:void 0,details:a}}}getAsyncData(e){let{callback:n,url:s,options:i,timeout:r,isRawResponse:a}=e,l=!f(n);mn(vn(s,i,this.basicAuthHeader),r,this.logger).then(u=>{l||n(a?u.response:pn(u.response,this.onError),u)}).catch(u=>{l||n(void 0,u)})}onError(e,n){this.errorHandler?.onError({error:e,context:si,groupingHash:n})}setAuthHeader(e,n=!1){let s=n?e:ei(`${e}:`);this.basicAuthHeader=`Basic ${s}`}resetAuthHeader(){this.basicAuthHeader=void 0}},us=new Et(ne),Bo="1",xo=()=>["rsa"],Go=["www.test-host.com","localhost","127.0.0.1","[::1]"],Fo=["userId","userTraits","groupId","groupTraits","anonymousId","config","integration","eventBuffer","traits","authToken"],Vo="RudderStack JavaScript SDK",jo="git+https://github.com/rudderlabs/rudder-sdk-js.git",Ho="js",ds=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,i)=>{o.capabilities.isAdBlockerDetectionInProgress.value=!1,o.capabilities.isAdBlocked.value=i?.error!==void 0||i?.xhr?.responseURL!==n}})}catch(e){throw o.capabilities.isAdBlockerDetectionInProgress.value=!1,e}},Ko=(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}},Wo=t=>({type:"manual",name:t,timestamp:new Date,metaData:{}}),Qo=(t=()=>window.location.hostname)=>{let e=t();return!e||e&&Go.includes(e)?"development":"production"},zo=t=>{let e=K(t,!1,Fo);return e!==null?JSON.parse(e):{}},Xo=()=>globalThis.location.href.split("?")[0],Yo=(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"}),qo=(t,e)=>({locale:t.value??"NA",userAgent:e.value??"NA",time:new Date}),Jo=(t,e,n,s)=>{let{context:i,lifecycle:r,session:a,source:l,reporting:u,autoTrack:d}=n,{app:p,locale:S,userAgent:R,timezone:g,screen:h,library:I}=i;return{payloadVersion:"5",notifier:{name:Vo,version:p.value.version,url:jo},events:[{exceptions:[E(t)],severity:e.severity,unhandled:e.unhandled,severityReason:e.severityReason,app:{version:p.value.version,releaseStage:Qo(),type:p.value.installType},device:qo(S,R),request:{url:Xo(),clientIp:"[NOT COLLECTED]"},breadcrumbs:E(u.breadcrumbs.value),context:t.message,groupingHash:s,metaData:{app:{snippetVersion:I.value.snippetVersion},device:{...h.value,timezone:g.value},...zo(n)},user:Yo(l,a,r,d)}]}},Zo=(t,e,n)=>{if(U(t.capabilities.isAdBlocked.value)){t.capabilities.isAdBlockerDetectionInProgress.value===!1&&ds(e);let s=X(()=>{A(t.capabilities.isAdBlocked.value)&&(n(t.capabilities.isAdBlocked.value===!1),s())})}else n(t.capabilities.isAdBlocked.value===!1)},ea=(t,e,n)=>{let s=t.message;return new Promise(i=>{if(Lo.some(r=>r.test(s))){let r=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(s)?.[0];_(r)?r.startsWith(et)?e.capabilities.cspBlockedURLs.value.includes(r)?i(!1):Zo(e,n,i):i(!1):i(!0)}else i(!ko.some(r=>r.test(s)))})},gs=t=>t?t.split("/").at(-2):void 0,fs=t=>{let e=t.stacktrace[0]?.file;if(!(!e||typeof e!="string"))return e},ta=t=>{let e=fs(t);if(!e)return!1;let n=e.substring(e.lastIndexOf("/")+1);return gs(e)===Ze||xo().some(i=>n.startsWith(i)&&n.endsWith(".js"))},na=(t,e)=>{if(e)return e;let n=fs(t);return gs(n)===Ze?wo:Mo},sa=(t,e,n)=>{let s={version:Bo,message_id:Ye(),source:{name:Ho,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(!A(t))s=e;else if(_(t))s=t;else{let i=cs(t,n);A(i)?s=i.message:s=e}return s},yt=class{constructor(e,n){N(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(et)&&!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:i,groupingHash:r,category:a}=e,l=e.errorType??q.HANDLEDEXCEPTION,u=Ko(n,l),d=cs(u,this.logger);if(U(d))return;let p=i?`${i} - `:"",S=`${s}${v}${p}`,R=Po(d,S),h=qe(d).includes(Vn);if(!h&&!ta(R)&&l!==q.HANDLEDEXCEPTION)return;if(o.reporting.isErrorReportingEnabled.value&&await ea(R,o,this.httpClient)){let m={severity:"error",unhandled:l!==q.HANDLEDEXCEPTION,severityReason:{type:l}},D=ia(r,R.message,this.logger),k=Jo(R,m,o,D),Se=na(R,a);this.httpClient.getAsyncData({url:o.metrics.metricsServiceUrl.value,options:{method:"POST",data:sa(k,o,Se),sendRawData:!0},isRawResponse:!0})}(l===q.HANDLEDEXCEPTION||h)&&this.logger.error(R.message)}catch(n){this.logger.error(or(Ae),n)}}leaveBreadcrumb(e){try{o.reporting.breadcrumbs.value=[...o.reporting.breadcrumbs.value,Wo(e)]}catch(n){this.onError({error:n,context:Ae,customMessage:un,groupingHash:un})}}},hs=new yt(us,ne),St=class{constructor(e,n={}){N(this,"plugins",[]);N(this,"byName",{});N(this,"cache",{});N(this,"config",{throws:!0});this.config={throws:!0,...n},this.logger=e}register(e,n){if(!e.name){let i=ar(de);if(this.config.throws)throw new Error(i);this.logger.error(i,e);return}if(this.byName[e.name]){let i=lr(de,e.name);if(this.config.throws)throw new Error(i);this.logger.error(i);return}this.cache={},this.plugins=this.plugins.slice();let s=this.plugins.length;this.plugins.forEach((i,r)=>{i.deps?.includes(e.name)&&(s=Math.min(s,r))}),this.plugins.splice(s,0,e),this.byName[e.name]=e,f(e.initialize)&&e.initialize(n)}unregister(e){let n=this.byName[e];if(!n){let i=cr(de,e);if(this.config.throws)throw new Error(i);this.logger.error(i);return}let s=this.plugins.indexOf(n);if(s===-1){let i=ur(de,e);if(this.config.throws)throw new Error(i);this.logger.error(i);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(i=>!this.byName[i])){let i=s.deps.filter(r=>!this.byName[r]);return this.logger.error(dr(de,s.name,i)),!1}return n==="."?!0:zs(s,n)})),this.cache[n]}processRawPlugins(e){e(this.plugins),this.cache={}}invoke(e,n=!0,...s){let i=e;if(!i)throw new Error(er);let r=i.startsWith("!"),a=this.config.throws??i.endsWith("!");if(i=i.replace(/(^!|!$)/g,""),!i)throw new Error(tr);let l=i.split(".");l.pop();let u=l.join(".");return(n?this.getPlugins(i):[this.getPlugins(i)[0]]).map(p=>{let S=ut(p,i);if(!f(S)||r)return S;try{return S.apply(ut(p,u),s)}catch(R){if(a)throw R;this.logger.error(gr(de,i,p.name),R)}return null})}invokeSingle(e,...n){return this.invoke(e,!1,...n)[0]}invokeMultiple(e,...n){return this.invoke(e,!0,...n)}},ra=new St(ne,{throws:!0}),oa=t=>t.config.connectionMode!=="cloud"||t.config.useNativeSDKToSend===!0||t.config.useNativeSDK===!0,aa=t=>t.config.connectionMode==="hybrid"||t.config.useNativeSDKToSend===!0,En=t=>t.filter(oa),la=(t,e)=>`${t.replaceAll(" ","-")}___${e}`,ps=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],ca=["Bugsnag","ErrorReporting"],ua={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 vs(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]=vs(n[s],e[s]));return n}var da=t=>vs({},(globalThis.__federation_shared__||{}).default||{});async function ga(t){let e=ua[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(r=>{import(r).then(a=>{if(!e.inited){let l=da();a.init(l),e.lib=a,e.lib.init(l),e.inited=!0}n(e.lib)}).catch(s)})})}function $(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 ga(t).then(n=>n.get(e).then(s=>s()))}var fa=t=>{switch(t){case"BeaconQueue":return()=>B("rudderAnalyticsRemotePlugins","./BeaconQueue").then(e=>$(e,!0));case"CustomConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./CustomConsentManager").then(e=>$(e,!0));case"DeviceModeDestinations":return()=>B("rudderAnalyticsRemotePlugins","./DeviceModeDestinations").then(e=>$(e,!0));case"DeviceModeTransformation":return()=>B("rudderAnalyticsRemotePlugins","./DeviceModeTransformation").then(e=>$(e,!0));case"ExternalAnonymousId":return()=>B("rudderAnalyticsRemotePlugins","./ExternalAnonymousId").then(e=>$(e,!0));case"GoogleLinker":return()=>B("rudderAnalyticsRemotePlugins","./GoogleLinker").then(e=>$(e,!0));case"KetchConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./KetchConsentManager").then(e=>$(e,!0));case"IubendaConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./IubendaConsentManager").then(e=>$(e,!0));case"NativeDestinationQueue":return()=>B("rudderAnalyticsRemotePlugins","./NativeDestinationQueue").then(e=>$(e,!0));case"OneTrustConsentManager":return()=>B("rudderAnalyticsRemotePlugins","./OneTrustConsentManager").then(e=>$(e,!0));case"StorageEncryption":return()=>B("rudderAnalyticsRemotePlugins","./StorageEncryption").then(e=>$(e,!0));case"StorageEncryptionLegacy":return()=>B("rudderAnalyticsRemotePlugins","./StorageEncryptionLegacy").then(e=>$(e,!0));case"StorageMigrator":return()=>B("rudderAnalyticsRemotePlugins","./StorageMigrator").then(e=>$(e,!0));case"XhrQueue":return()=>B("rudderAnalyticsRemotePlugins","./XhrQueue").then(e=>$(e,!0));default:return}},ha=t=>{let e={};return t.forEach(n=>{if(ps.includes(n)){let s=fa(n);s&&(e[n]=s)}}),e},ms=()=>({}),pa=()=>({}),va=t=>ha?.(t)||{},rt={...ms(),...pa()},ma=t=>({...va(t)}),It=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)&&w(()=>{o.plugins.ready.value=!0,o.lifecycle.status.value="pluginsReady"})})}getPluginsToLoadBasedOnConfig(){let e=o.plugins.pluginsToLoadFromConfig.value;if(!e)return[];e=e.filter(i=>ca.includes(i)?(this.logger.warn(Vr(Ie,i)),!1):!0);let n=[{configurationStatus:()=>A(o.dataPlaneEvents.eventsQueuePluginName.value),configurationStatusStr:"Data plane events delivery is enabled",activePluginName:o.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(qr),shouldAddMissingPlugins:!0},{configurationStatus:()=>En(o.nativeDestinations.configuredDestinations.value).length>0,configurationStatusStr:"Device mode destinations are connected to the source",supportedPlugins:["DeviceModeDestinations","NativeDestinationQueue"]},{configurationStatus:()=>En(o.nativeDestinations.configuredDestinations.value).some(i=>i.shouldApplyDeviceModeTransformation),configurationStatusStr:"Device mode transformations are enabled for at least one destination",supportedPlugins:["DeviceModeTransformation"]},{configurationStatus:()=>A(o.consents.activeConsentManagerPluginName.value),configurationStatusStr:"Consent management is enabled",activePluginName:o.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(mt)},{configurationStatus:()=>A(o.storage.encryptionPluginName.value),configurationStatusStr:"Storage encryption is enabled",activePluginName:o.storage.encryptionPluginName.value,supportedPlugins:Object.values($e)},{configurationStatus:()=>o.storage.migrate.value,configurationStatusStr:"Storage migration is enabled",supportedPlugins:["StorageMigrator"]}],s=!1;return n.forEach(i=>{i.configurationStatus()?(e=e.filter(i.activePluginName?r=>!(r!==i.activePluginName&&i.supportedPlugins.includes(r)):r=>A(r)),this.addMissingPlugins(i,s,e)):e=e.filter(i.basePlugins!==void 0?r=>!(i.basePlugins.includes(r)||i.supportedPlugins.includes(r)):r=>!i.supportedPlugins.includes(r))}),[...Object.keys(ms()),...e]}addMissingPlugins(e,n,s){let i=e.shouldAddMissingPlugins||n,r;e.activePluginName?r=[...e.basePlugins||[],e.activePluginName]:r=[...e.supportedPlugins];let a=r.filter(l=>!s.includes(l));a.length>0&&(i&&s.push(...a),this.logger.warn(jr(Ie,e.configurationStatusStr,a,i)))}setActivePlugins(){let e=this.getPluginsToLoadBasedOnConfig(),n=[...Object.keys(rt),...ps],s=[],i=[];e.forEach(r=>{n.includes(r)?s.push(r):i.push(r)}),i.length>0&&this.logger.warn(Wr(Ie,i)),w(()=>{o.plugins.totalPluginsToLoad.value=e.length,o.plugins.activePlugins.value=s,o.plugins.failedPlugins.value=i})}registerLocalPlugins(){let e=[];Object.entries(rt).forEach(([n,s])=>{o.plugins.activePlugins.value.includes(n)&&(f(s)?this.register([s()]):e.push(n))}),e.length>0&&(o.plugins.failedPlugins.value=[...o.plugins.failedPlugins.value,...e],this.logger.error(Qr(Ie,e)))}registerRemotePlugins(){let e=ma(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.keys(rt).forEach(e=>{try{this.engine.unregister(e)}catch(n){this.onError(n,`Failed to unregister plugin "${e}"`)}})}onError(e,n,s){this.errorHandler.onError({error:e,context:Ie,customMessage:n,groupingHash:s})}},x="cookieStorage",F="localStorage",V="sessionStorage",z="memoryStorage",ue="none",Ea="test_rudder_cookie",ya="test_rudder_ls",Sa="test_rudder_ss",Ia="rl_user_id",ba="rl_trait",Ta="rl_anonymous_id",Aa="rl_group_id",Ra="rl_group_trait",_a="rl_page_init_referrer",Oa="rl_page_init_referring_domain",Na="rl_session",Pa="rl_auth_token",ge={userId:Ia,userTraits:ba,anonymousId:Ta,groupId:Aa,groupTraits:Ra,initialReferrer:_a,initialReferringDomain:Oa,sessionInfo:Na,authToken:Pa},Ca="__tld__",Es="clientDataInCookie",ys="clientDataInLocalStorage",Da="clientDataInMemory",Ss="clientDataInSessionStorage",Is=["userId","userTraits","anonymousId","groupId","groupTraits","initialReferrer","initialReferringDomain","sessionInfo","authToken"],fe={[x]:Es,[F]:ys,[z]:Da,[V]:Ss},yn=(t,e)=>{try{return encodeURIComponent(t)}catch(n){e?.error(mi,n);return}},Sn=t=>{try{return decodeURIComponent(t)}catch{return}},ka=t=>{let e={},n=t.split(/\s*;\s*/),s;return n[0]&&n.forEach(i=>{s=i.split("=");let r=s[0]?Sn(s[0]):void 0;r&&(e[r]=s[1]?Sn(s[1]):void 0)}),e},La=(t,e,n,s)=>{let i={...n||{}},r=`${yn(t,s)}=${yn(e,s)}`;G(e)&&(i.maxage=-1),i.maxage&&(i.expires=new Date(+new Date+i.maxage)),i.path&&(r+=`; path=${i.path}`),i.domain&&(r+=`; domain=${i.domain}`),i.expires&&(r+=`; expires=${i.expires.toUTCString()}`),i.samesite&&(r+=`; samesite=${i.samesite}`),i.secure&&(r+="; secure"),globalThis.document.cookie=r},bt=()=>{let t=globalThis.document.cookie;return ka(t)},wa=t=>bt()[t],J=function(t,e,n,s){switch(arguments.length){case 4:case 3:case 2:return La(t,e,n,s);case 1:return t?wa(t):bt();default:return bt()}},Ua=t=>{let e=document.createElement("a");return e.href=t,e.hostname},Ma=t=>{let n=(typeof globalThis.URL!="function"?Ua(t):new URL(t).hostname)?.split(".")??[],s=n[n.length-1],i=[];if(n.length===4&&s&&s===parseInt(s,10).toString())return i;if(n.length<=1)return n[0]&&n[0].indexOf("localhost")!==-1?["localhost"]:i;for(let r=n.length-2;r>=0;r-=1)i.push(n.slice(r).join("."));return i},$a=t=>{let e=Ma(t);for(let n=0;n<e.length;n+=1){let s=e[n],i=Ca,r={domain:`${s.indexOf("localhost")!==-1?"":"."}${s}`};try{if(J(i,1,r),J(i))return J(i,null,r),s}catch{try{J(i,null,r)}catch{}}}return""},Ba=()=>{let t=`.${$a(globalThis.location.href)}`;return{maxage:ki,path:"/",domain:!t||t==="."?void 0:t,samesite:"Lax",enabled:!0}},xa=()=>({enabled:!0}),Ga=()=>({enabled:!0}),Fa=()=>({enabled:!0}),Tt=class{constructor(e){N(this,"isEnabled",!0);N(this,"length",0);N(this,"data",{});this.options=Fa(),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)}},ze=new Tt(ne);function Va(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var xe={exports:{}},ja=xe.exports,In;function Ha(){return In||(In=1,(function(t,e){(function(n,s){t.exports=s()})(ja,function(){function n(g){return g=JSON.stringify(g),!!/^\{[\s\S]*\}$/.test(g)}function s(g){return g===void 0||typeof g=="function"?g+"":JSON.stringify(g)}function i(g){if(typeof g=="string")try{return JSON.parse(g)}catch{return g}}function r(g){return{}.toString.call(g)==="[object Function]"}function a(g){return Object.prototype.toString.call(g)==="[object Array]"}function l(g){var h="_Is_Incognit",I="yes";try{g||(g=window.localStorage),g.setItem(h,I),g.removeItem(h)}catch{var m={};m._data={},m.setItem=function(k,Se){return m._data[k]=String(Se)},m.getItem=function(k){return m._data.hasOwnProperty(k)?m._data[k]:void 0},m.removeItem=function(k){return delete m._data[k]},m.clear=function(){return m._data={}},g=m}finally{g.getItem(h)===I&&g.removeItem(h)}return g}var u=l();function d(){if(!(this instanceof d))return new d}d.prototype={set:function(h,I){if(h&&!n(h))u.setItem(h,s(I));else if(n(h))for(var m in h)this.set(m,h[m]);return this},get:function(h){if(h===void 0){var I={};return this.forEach(function(ks,Ls){return I[ks]=Ls}),I}if(h.charAt(0)==="?")return this.has(h.substr(1));var m=arguments;if(m.length>1){for(var D={},k=0,Se=m.length;k<Se;k++){var Ds=i(u.getItem(m[k]));this.has(m[k])&&(D[m[k]]=Ds)}return D}return i(u.getItem(h))},clear:function(){return u.clear(),this},remove:function(h){var I=this.get(h);return u.removeItem(h),I},has:function(h){return{}.hasOwnProperty.call(this.get(),h)},keys:function(){var h=[];return this.forEach(function(I){h.push(I)}),h},forEach:function(h){for(var I=0,m=u.length;I<m;I++){var D=u.key(I);h(D,this.get(D))}return this},search:function(h){for(var I=this.keys(),m={},D=0,k=I.length;D<k;D++)I[D].indexOf(h)>-1&&(m[I[D]]=this.get(I[D]));return m},len:function(){return u.length}};var p=null;function S(g,h){var I=arguments,m=null;if(p||(p=d()),I.length===0)return p.get();if(I.length===1){if(typeof g=="string")return p.get(g);if(n(g))return p.set(g)}if(I.length===2&&typeof g=="string"){if(!h)return p.remove(g);if(h&&typeof h=="string")return p.set(g,h);h&&r(h)&&(m=null,m=h(g,p.get(g)),S.set(g,m))}if(I.length===2&&a(g)&&r(h))for(var D=0,k=g.length;D<k;D++)m=h(g[D],p.get(g[D])),S.set(g[D],m);return S}for(var R in d.prototype)S[R]=d.prototype[R];return S})})(xe)),xe.exports}var Ka=Ha(),re=Va(Ka),bs=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},he=(t=F,e,n)=>{let s,i,r=Ei(dt,t),a="unavailable",l=!0,u;try{switch(t){case z:return!0;case x:s=e,i=Ea;break;case F:s=e??globalThis.localStorage,i=ya;break;case V:s=e??globalThis.sessionStorage,i=Sa;break;default:return!1}if(s&&(s.setItem(i,"true"),s.getItem(i)))return s.removeItem(i),!0;l=!1}catch(d){l=!1,u=d,bs(d)&&(a="full")}return l||n?.warn(`${r}${a}.`,u),!1},At=class{constructor(e){N(this,"isSupportAvailable",!0);N(this,"isEnabled",!0);N(this,"length",0);this.options=xa(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isSupportAvailable=he(F),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,n){re.set(e,n),this.length=re.len()}getItem(e){let n=re.get(e);return U(n)?null:n}removeItem(e){re.remove(e),this.length=re.len()}clear(){re.clear(),this.length=0}key(e){return this.keys()[e]??null}keys(){return re.keys()}},Qt=new At(ne),Rt=class{constructor(e){N(this,"isSupportAvailable",!0);N(this,"isEnabled",!0);N(this,"length",0);this.options=Ga(),this.logger=e}configure(e){return this.options=L(this.options,e??{}),this.isSupportAvailable=he(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 U(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}},zt=new Rt(ne),_t=class{constructor(e){N(this,"isSupportAvailable",!0);N(this,"isEnabled",!0);N(this,"length",0);this.logger=e}configure(e){return this.options||(this.options=Ba()),this.options=L(this.options,e??{}),this.options.sameDomainCookiesOnly&&delete this.options.domain,this.isSupportAvailable=he(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 U(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())}},Xt=new _t(ne),H=t=>{switch(t){case F:return Qt;case V:return zt;case z:return ze;case x:return Xt;default:return ze}},Wa=t=>{let e=Xt.configure(t);o.storage.cookie.value={maxage:e.maxage,path:e.path,domain:e.domain,samesite:e.samesite,expires:e.expires,secure:e.secure}},Qa=t=>{Qt.configure(t)},za=t=>{ze.configure(t)},Xa=t=>{zt.configure(t)},Ya=(t={},e={},n={},s={})=>{Wa(t),Qa(e),za(n),Xa(s)},Ot=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:i,noKeyValidation:r,noCompoundKey:a}=this;if(r)return a?e:[n,s,e].join(".");let l;return Object.values(i).forEach(u=>{u===e&&(l=a?e:[n,s,e].join("."))}),l}swapQueueStoreToInMemoryEngine(){let{name:e,id:n,validKeys:s,noCompoundKey:i}=this,r=H(z);Object.keys(s).forEach(a=>{let l=this.get(s[a]),u=i?a:[e,n,a].join(".");r.setItem(u,l),this.remove(a)}),this.engine=r}set(e,n){let s=this.createValidKey(e);if(s)try{this.engine.setItem(s,this.encrypt(K(n,!1,[],this.logger)))}catch(i){if(bs(i))this.logger.warn(Ur(`Store ${this.id}`)),this.swapQueueStoreToInMemoryEngine(),this.set(e,n);else{let r=Er(e);this.onError(i,r,r)}}}get(e){let n=this.createValidKey(e),s;try{return!n||(s=this.decrypt(this.engine.getItem(n)),W(s)||s==="")?null:JSON.parse(s)}catch(i){let r=o.storage.encryptionPluginName.value;if(!r||!o.plugins.failedPlugins.value.includes(r)){let l=yr(e);this.onError(i,l,l)}return null}}remove(e){let n=this.createValidKey(e);n&&this.engine.removeItem(n)}getOriginalEngine(){return this.originalEngine}decrypt(e){return W(e)?null:this.crypto(e,"decrypt")}encrypt(e){return this.crypto(e,"encrypt")}crypto(e,n){if(!this.isEncrypted||!e||typeof e!="string"||Js(e)==="")return e;let i=`storage.${n}`,r=this.pluginsManager?this.pluginsManager.invokeSingle(i,e):e;return typeof r>"u"?e:r??""}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=ue;break;case"session":e!=="sessionInfo"&&(n=ue);break;case"anonymousId":e!=="anonymousId"&&(n=ue);break}return n},Nt=class{constructor(e,n,s){N(this,"stores",{});N(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(),[z,F,x,V].forEach(n=>{H(n)?.isEnabled&&this.setStore({id:fe[n],name:fe[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;(A(s?.type)||A(s?.entries))&&(e=s?.type,n=s?.entries);let i=!0,r={};Is.forEach(a=>{let l=a,u=a,d=n?.[l]?.type,S=qa(o,a)??d??e??vt,R=this.getResolvedStorageTypeForEntry(S,a);R!==ue&&(i=!1),r={...r,[a]:{type:R,key:ge[u]}}}),w(()=>{o.storage.type.value=e,o.storage.entries.value=r,o.storage.trulyAnonymousTracking.value=i})}getResolvedStorageTypeForEntry(e,n){let s=e;switch(e){case F:H(F)?.isEnabled||(s=z);break;case V:H(V)?.isEnabled||(s=z);break;case z:case ue:break;case x:default:H(x)?.isEnabled?s=x:H(F)?.isEnabled?s=F:H(V)?.isEnabled?s=V:s=z;break}return s!==e&&this.logger.warn(Mr(ti,n,e,s)),s}setStore(e){let n=H(e.type);return this.stores[e.id]=new Ot(e,n,this.pluginsManager),this.stores[e.id]}getStore(e){return this.stores[e]}},Ja=t=>O(t)&&O(t.source)&&!W(t.source.id)&&O(t.source.config)&&Array.isArray(t.source.destinations),Za=t=>typeof t=="string"&&Zn.includes(t),Ts=t=>{let e=new URL(t),{host:n,protocol:s}=e,i=n.split("."),r;return i.length>2?r=`${i[i.length-2]}.${i[i.length-1]}`:r=n,{topDomain:r,protocol:s}},el=t=>{let{topDomain:e,protocol:n}=Ts(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}=Ts(window.location.href);return e===t},ve=t=>t?.endsWith("/")?ve(t.substring(0,t.length-1)):t,Pt=t=>{try{return new URL(t).host}catch{return null}},As=t=>Pt(t)??"",sl=t=>{let e={};try{let n=new URL(t),s="utm_";n.searchParams.forEach((i,r)=>{if(r.startsWith(s)){let a=r.substring(s.length);a==="campaign"&&(a="name"),e[a]=i}})}catch{}return e},il=t=>{let e=t;try{let n=new URL(t);e=n.origin+n.pathname+n.search}catch{}return e},rl=t=>t.replace(/\/{2,}/g,"/"),me=t=>{if(!_(t))return!1;try{return f(globalThis.URL)&&new URL(t),Xr.test(t)}catch{return!1}},ot="none",at="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(O(t)){let n=E(t);e.storage=n.storage,te(n.integrations)&&(e.integrations=n.integrations),e.discardPreConsentEvents=n.discardPreConsentEvents===!0,e.sendPageEvent=n.sendPageEvent===!0,e.trackConsent=n.trackConsent===!0,te(n.consentManagement)&&(e.consentManagement=L(n.consentManagement,{enabled:o.consents.enabled.value}))}return e},bn=t=>te(t)||Array.isArray(t),cl=(t,e)=>{let{provider:n}=t,s=n?mt[n]:void 0;return n&&!s&&(e.error(ir(j,n,mt)),n=void 0),{provider:n,consentManagerPluginName:s}},Rs=(t,e)=>{let n,s=[],i=[],r=!1,a,l=t?.enabled===!0;te(t)&&l&&({provider:a,consentManagerPluginName:n}=cl(t,e),bn(t.allowedConsentIds)&&(s=t.allowedConsentIds,r=!0),bn(t.deniedConsentIds)&&(i=t.deniedConsentIds,r=!0));let u={allowedConsentIds:s,deniedConsentIds:i};return l=l&&!!n,{provider:a,consentManagerPluginName:n,initialized:r,enabled:l,consentsData:u}},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 i=s.getAttribute("src");if(i&&n.test(i))return i}},dl=t=>{o.reporting.isErrorReportingEnabled.value=ol(t.source.config)&&!ci(),o.reporting.isMetricsReportingEnabled.value=al(t.source.config)},gl=t=>{let{useServerSideCookies:e,dataServiceEndpoint:n,storage:s,setCookieDomain:i,sameDomainCookiesOnly:r}=o.loadOptions.value,a=s?.cookie,l=!1,u;if(e){l=e;let d=a.domain??i,p=A(d)&&!nl(qt(d))||r,S=tl(n??Jr,p);if(me(S)){u=ve(S);let R=Pt(window.location.href),g=Pt(S);R!==g&&(a={...a,samesite:"None",secure:!0}),!r&&p&&g!==qt(d)&&(l=!1,t.warn(Rr(j,d,g)))}else l=!1}return{sscEnabled:l,cookieOptions:a,finalDataServiceUrl:u}},fl=t=>{let{storage:e}=o.loadOptions.value,n=e?.type;A(n)&&!Za(n)&&(t.warn(br(j,n,vt)),n=vt);let s=e?.encryption?.version,i=s&&$e[s];!U(s)&&U(i)?(t.warn(Tr(j,s,$e,ae)),s=ae):U(s)&&(s=ae);let r=e?.migrate,a=r&&s===ae;r===!0&&a!==r&&t.warn(Ar(j,s,ae));let{sscEnabled:l,finalDataServiceUrl:u,cookieOptions:d}=gl(t);w(()=>{o.storage.type.value=n,o.storage.cookie.value=d,o.serverCookies.isEnabledServerSideCookies.value=l,o.serverCookies.dataServiceUrl.value=u,o.storage.encryptionPluginName.value=$e[s],o.storage.migrate.value=a})},hl=t=>{let{provider:e,consentManagerPluginName:n,initialized:s,enabled:i,consentsData:r}=Rs(o.loadOptions.value.consentManagement,t),a=o.loadOptions.value.preConsent,l=a?.storage?.strategy??ot,u=["none","session","anonymousId"];A(l)&&!u.includes(l)&&(l=ot,t.warn(Gr(j,a?.storage?.strategy,ot)));let d=a?.events?.delivery??at,p=["immediate","buffer"];A(d)&&!p.includes(d)&&(d=at,t.warn(Fr(j,a?.events?.delivery,at))),w(()=>{o.consents.activeConsentManagerPluginName.value=n,o.consents.initialized.value=s,o.consents.enabled.value=i,o.consents.data.value=r,o.consents.provider.value=e,o.consents.preConsent.value={enabled:o.loadOptions.value.preConsent?.enabled===!0&&s===!1&&i===!0,storage:{strategy:l},events:{delivery:d}}})},pl=t=>{let e=o.consents.resolutionStrategy.value,n;O(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),w(()=>{o.consents.metadata.value=E(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(Nr(j)))),w(()=>{o.dataPlaneEvents.eventsQueuePluginName.value=n})}},ml=(t,e,n,s,i)=>{let r=new URLSearchParams({p:jn,v:Ne,build:Ce,writeKey:e,lockIntegrationsVersion:n.toString(),lockPluginsVersion:s.toString()}),a=rs,l=r,u="/sourceConfig/",d="";if(me(t)){let p=new URL(t);ve(p.pathname).endsWith("/sourceConfig")||(p.pathname=`${ve(p.pathname)}/sourceConfig/`),p.pathname=rl(p.pathname),r.forEach((S,R)=>{p.searchParams.get(R)===null&&p.searchParams.set(R,S)}),a=p.origin,u=p.pathname,l=p.searchParams,d=p.hash}else i.warn(Br(j,t));return`${a}${u}?${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:la(e.destinationDefinition.displayName,e.id),isCustomIntegration:e.destinationDefinition.displayName===eo})),_s=(t,e,n,s,i,r,a)=>{let l;if(r){if(!me(r))return a.error(sr(j,t,r)),null;l=ve(r)}else if(l=n,o.context.app.value.installType==="cdn"){let u=ul();u&&(l=u.split("/").slice(0,-1).concat(e).join("/"))}return i&&(l=l.replace(new RegExp(`/${Wt}/${Ce}/${e}$`),`/${s}/${Ce}/${e}`)),l},yl=(t,e,n,s)=>_s("integrations",Ze,ss,t,e,n,s),Sl=(t,e,n,s)=>_s("plugins",ns,is,t,e,n,s),Ct=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:i,destSDKBaseURL:r,pluginsSDKBaseURL:a,integrations:l}=o.loadOptions.value,u=yl(Ne,s,r,this.logger);if(G(u))return;let d;d=Sl(Ne,i,a,this.logger),d!==null&&(this.attachEffects(),o.lifecycle.activeDataplaneUrl.value=ve(o.lifecycle.dataPlaneUrl.value),fl(this.logger),hl(this.logger),vl(this.logger),w(()=>{o.lifecycle.integrationsCDNPath.value=u,o.lifecycle.pluginsCDNPath.value=d,e&&(o.lifecycle.logLevel.value=e),o.lifecycle.sourceConfigUrl.value=ml(n,o.lifecycle.writeKey.value,s,i,this.logger),o.metrics.metricsServiceUrl.value=`${o.lifecycle.activeDataplaneUrl.value}/${Zr}`,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(!A(e)){A(n)?this.onError(n.error,dn):this.onError(new Error(dn));return}let s;try{_(e)?s=JSON.parse(e):s=e}catch(r){this.onError(r,cn);return}if(!Ja(s)){this.onError(new Error(cn));return}if(s.source.enabled===!1){this.logger.error(Ji);return}dl(s);let i=s.source.destinations.length>0?El(s.source.destinations):[];w(()=>{o.source.value={config:s.source.config,name:s.source.name,id:s.source.id,workspaceId:s.source.workspaceId},o.nativeDestinations.configuredDestinations.value=i,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(!f(e)){this.logger.error(nr(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})}},Il=()=>{let t=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return t?.[1]?t[1]:"NA"},Os=(t=()=>document)=>t()?.referrer||"$direct",bl=(t=()=>document)=>{let n=t().getElementsByTagName("link"),s="";for(let i=0;n[i];i+=1){let r=n[i];if(r.getAttribute("rel")==="canonical"&&!s){s=r.getAttribute("href")??"";break}}return s},Tl=(t=()=>globalThis.navigator)=>{let e=t();if(U(e))return null;let{userAgent:n}=e,{brave:s}=e;if(s&&Object.getPrototypeOf(s).isBrave){let i=n.match(/(chrome)\/([\w.]+)/i);i&&(n=`${n} Brave/${i[2]}`)}return n},Al=(t=()=>globalThis.navigator)=>{let e=t();return U(e)?null:e.language??e.browserLanguage},Ns=(t=()=>globalThis.location,e=()=>document)=>{let n=t(),s=bl(e),i=n.pathname,{href:r}=n,a=r,{search:l}=n;if(s)try{let S=new URL(s);S.search===""?a=s+l:a=s,i=S.pathname}catch{}let u=il(a),{title:d}=e(),p=Os(e);return{path:i,referrer:p,referring_domain:As(p),search:l,title:d,url:u,tab_url:r}},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()})},_l=()=>{let t=globalThis.document.createElement("div");return t.setAttribute("data-a-b","c"),t.dataset?t.dataset.aB==="c":!1},Dt={URL:()=>!f(globalThis.URL)||!f(globalThis.URLSearchParams),Promise:()=>!f(globalThis.Promise),"Number.isNaN":()=>!f(globalThis.Number.isNaN),"Number.isInteger":()=>!f(globalThis.Number.isInteger),"Array.from":()=>!f(globalThis.Array.from),"Array.prototype.find":()=>!f(globalThis.Array.prototype.find),"Array.prototype.includes":()=>!f(globalThis.Array.prototype.includes),"String.prototype.endsWith":()=>!f(globalThis.String.prototype.endsWith),"String.prototype.startsWith":()=>!f(globalThis.String.prototype.startsWith),"String.prototype.includes":()=>!f(globalThis.String.prototype.includes),"String.prototype.replaceAll":()=>!f(globalThis.String.prototype.replaceAll),"String.fromCodePoint":()=>!f(globalThis.String.fromCodePoint),"Object.entries":()=>!f(globalThis.Object.entries),"Object.values":()=>!f(globalThis.Object.values),"Object.assign":()=>!f(globalThis.Object.assign),"Object.fromEntries":()=>!f(globalThis.Object.fromEntries),"Element.prototype.dataset":()=>!_l(),TextEncoder:()=>!f(globalThis.TextEncoder)||!f(globalThis.TextDecoder),requestAnimationFrame:()=>!f(globalThis.requestAnimationFrame)||!f(globalThis.cancelAnimationFrame),CustomEvent:()=>!f(globalThis.CustomEvent),"navigator.sendBeacon":()=>!f(globalThis.navigator.sendBeacon),ArrayBuffer:()=>!f(globalThis.Uint8Array),Set:()=>!f(globalThis.Set),atob:()=>!f(globalThis.atob)},Ol=()=>{let t=Object.keys(Dt),e=!1;for(let n=0;n<t.length;n++){let s=Dt[t[n]];if(f(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(Dt).join("%2C")}`,Cl=10*1e3,Tn="rudderstackPolyfill",Dl=()=>!W(globalThis.crypto)&&f(globalThis.crypto.getRandomValues),An=()=>!W(globalThis.navigator.userAgentData),kl=()=>!W(globalThis.navigator.sendBeacon)&&f(globalThis.navigator.sendBeacon),Rn=()=>{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},kt=class{constructor(e,n,s){this.httpClient=e,this.errorHandler=n,this.logger=s,this.externalSrcLoader=new He(this.logger),this.onError=this.onError.bind(this),this.onReady=this.onReady.bind(this)}init(){this.prepareBrowserCapabilities(),this.attachWindowListeners()}detectBrowserCapabilities(){w(()=>{o.capabilities.storage.isCookieStorageAvailable.value=he(x,H(x),this.logger),o.capabilities.storage.isLocalStorageAvailable.value=he(F,void 0,this.logger),o.capabilities.storage.isSessionStorageAvailable.value=he(V,void 0,this.logger),o.capabilities.isBeaconAvailable.value=kl(),o.capabilities.isUaCHAvailable.value=An(),o.capabilities.isCryptoAvailable.value=Dl(),o.capabilities.isOnline.value=globalThis.navigator.onLine,o.context.userAgent.value=Tl(),o.context.locale.value=Al(),o.context.screen.value=Rn(),o.context.timezone.value=Il(),An()&&Rl(e=>{o.context["ua-ch"].value=e},o.loadOptions.value.uaChTrackLevel)}),X(()=>{o.loadOptions.value.sendAdblockPage===!0&&o.lifecycle.sourceConfigUrl.value!==void 0&&ds(this.httpClient)})}prepareBrowserCapabilities(){o.capabilities.isLegacyDOM.value=Ol();let e=o.loadOptions.value.polyfillURL,n=Pl;if(pe(e)&&(me(e)?n=e:this.logger.warn(Hr(dt,e))),o.loadOptions.value.polyfillIfRequired&&o.capabilities.isLegacyDOM.value&&me(n)){let i=n!==o.loadOptions.value.polyfillURL;if(i){let r=`RS_polyfillCallback_${o.lifecycle.writeKey.value}`,a=()=>{this.onReady(),delete globalThis[r]};globalThis[r]=a,n=`${n}&callback=${r}`}this.externalSrcLoader.loadJSFile({url:n,id:Tn,async:!0,timeout:Cl,callback:r=>{r?i||this.onReady():this.onError(new Error(xr(Tn,n)))}})}else this.onReady()}attachWindowListeners(){globalThis.addEventListener("offline",()=>{o.capabilities.isOnline.value=!1}),globalThis.addEventListener("online",()=>{o.capabilities.isOnline.value=!0}),globalThis.addEventListener("resize",Ui(()=>{o.context.screen.value=Rn()},this))}onReady(){this.detectBrowserCapabilities(),o.lifecycle.status.value="browserCapabilitiesReady"}onError(e,n){this.errorHandler.onError({error:e,context:dt,groupingHash:n})}},Ll="web",wl=["integrations","anonymousId","originalTimestamp"],_n=["library","consentManagement","userAgent","ua-ch","screen"],lt=["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"],Ps=t=>typeof t=="number"&&!Number.isNaN(t),Ul=(t,e)=>e.toString().length>=t,Xe=t=>Ps(t)&&t>=0&&Number.isInteger(t),On=10,Cs=t=>{let{cutOff:e}=t,n=Date.now();return!!(e?.enabled&&e.expiresAt&&n>e.expiresAt)},Nn=t=>!t.expiresAt||Date.now()>t.expiresAt||Cs(t),Ml=()=>Date.now(),$l=(t,e)=>!t||!Xe(t)||!Ul(On,t)?(e.warn(wr(oe,t,On)),!1):!0,Bl=t=>{if(t?.enabled)return t.expiresAt??(Xe(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:$l(t,e)?t:Ml(),sessionStart:void 0,manualTrack:!0}),Re=t=>t===x||t===F||t===V||t===z,Lt=()=>Ye(),Fl=t=>{if(Qs(t)){let{entries:e,...n}=it;return{...n,entries:{...e,anonymousId:t}}}return O(t)&&O(t.entries)?L(it,t):{...it}},Vl=t=>{let e=Ns(),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,i=Ns();return Object.keys(i).forEach(r=>{U(s[r])&&(s[r]=n[r]||i[r])}),U(s.initial_referrer)&&(s.initial_referrer=n.initial_referrer||o.session.initialReferrer.value),U(s.initial_referring_domain)&&(s.initial_referring_domain=n.initial_referring_domain||o.session.initialReferringDomain.value),s},ct=(t,e,n)=>{O(t)&&Object.keys(t).forEach(s=>{(lt.includes(s)||lt.includes(s.toLowerCase()))&&n.warn(_r(Bn,s,e,lt))})},Hl=(t,e)=>{let{properties:n,traits:s,context:i}=t,{traits:r}=i;ct(n,"properties",e),ct(s,"traits",e),ct(r,"context.traits",e)},Kl=(t,e)=>{e.anonymousId&&_(e.anonymousId)&&(t.anonymousId=e.anonymousId),te(e.integrations)&&(t.integrations=e.integrations),e.originalTimestamp&&_(e.originalTimestamp)&&(t.originalTimestamp=e.originalTimestamp)},Wl=(t,e,n)=>{let s=t;return Object.keys(e).forEach(i=>{if(!wl.includes(i)&&!_n.includes(i))if(i!=="context")s=L(s,{[i]:e[i]});else if(!U(e[i])&&O(e[i])){let r={};Object.keys(e[i]).forEach(a=>{_n.includes(a)||(r[a]=e[i][a])}),s=L(s,{...r})}else n.warn(Or(Bn))}),s},Ql=(t,e,n)=>{O(e)&&(Kl(t,e),t.context=Wl(t.context,e,n))},zl=t=>{let e;return o.loadOptions.value.useGlobalIntegrationsConfigInEvents?e=o.consents.postConsent.value.integrations??o.nativeDestinations.loadOnlyIntegrations.value:t?e=t:e=ts,E(e)},be=(t,e,n,s)=>{let i={channel:Ll,context:{traits:E(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:E(o.consents.data.value.deniedConsentIds),allowedConsentIds:E(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:gi(),messageId:Ye(),userId:t.userId||o.session.userId.value};Re(o.storage.entries.value.anonymousId?.type)?i.anonymousId=o.session.anonymousId.value:i.anonymousId=Lt(),o.storage.trulyAnonymousTracking.value&&(i.context.trulyAnonymousTracking=!0),t.type==="identify"&&(i.context.traits=o.storage.entries.value.userTraits?.type!==ue?E(o.session.userTraits.value):t.context.traits),t.type==="group"&&((t.groupId||o.session.groupId.value)&&(i.groupId=t.groupId||o.session.groupId.value),(t.traits||o.session.groupTraits.value)&&(i.traits=o.storage.entries.value.groupTraits?.type!==ue?E(o.session.groupTraits.value):t.traits));let r=L(t,i);return r.event===void 0&&(r.event=null),r.properties===void 0&&(r.properties=null),Ql(r,e,s),Hl(r,s),r.integrations=zl(r.integrations),r},wt=class{constructor(e){this.logger=e}generatePageEvent(e,n,s,i){let r=s??{};return r=jl(r,i),be({properties:r,name:n,category:e,type:"page"},i,r,this.logger)}generateTrackEvent(e,n,s){return be({properties:n,event:e,type:"track"},s,void 0,this.logger)}generateIdentifyEvent(e,n,s){return be({userId:e,type:"identify",context:{traits:n}},s,void 0,this.logger)}generateAliasEvent(e,n,s){let r=be({previousId:n,type:"alias"},s,void 0,this.logger);return r.userId=e??r.userId,r}generateGroupEvent(e,n,s){let i={type:"group"};return e&&(i.groupId=e),n&&(i.traits=n),be(i,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}},Ut=class{constructor(e,n,s,i){this.eventRepository=e,this.userSessionManager=n,this.errorHandler=s,this.logger=i,this.eventFactory=new wt(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)}},Mt=class{constructor(e,n,s,i,r){this.storeManager=n,this.pluginsManager=e,this.logger=r,this.errorHandler=i,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;pe(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()??T.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=T.sessionInfo:n.cutOff?.enabled===!0&&(e.cutOff={enabled:!0,duration:n.cutOff.duration,expiresAt:s.cutOff?.expiresAt})}else e=T.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||Os();this.setInitialReferrer(s),this.setInitialReferringDomain(As(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 i=s,r=e[i]?.type,a=this.storeManager?.getStore(fe[r]);a&&n.forEach(l=>{let u=this.storeManager?.getStore(fe[l]);if(u&&l!==r){let d=u.get(ge[i]);Ws(d)&&a.set(ge[i],d),u.remove(ge[i])}})})}migrateStorageIfNeeded(e,n){if(!o.storage.migrate.value)return;let s=e??[];s.length===0&&[Es,ys,Ss].forEach(a=>{let l=this.storeManager?.getStore(a);l&&s.push(l)}),(n??Object.keys(ge)).forEach(r=>{let a=ge[r];s.forEach(l=>{let u=this.pluginsManager?.invokeSingle("storage.migrate",a,l.engine,this.errorHandler,this.logger);W(u)||l.set(a,u)})})}getConfiguredSessionTrackingInfo(){let e=o.loadOptions.value.sessions.autoTrack!==!1;if(!e)return{autoTrack:e};let n,s=o.loadOptions.value.sessions?.timeout;Xe(s)?n=s:(this.logger.warn(Pr(oe,s,gt)),n=gt),n===0&&(this.logger.warn(kr(oe)),e=!1),n>0&&n<on&&this.logger.warn(Lr(oe,n,on));let i=this.getCutOffInfo(n);return{timeout:n,autoTrack:e,cutOff:i}}getCutOffInfo(e){let n=o.loadOptions.value.sessions.cutOff,s,i=!1;return n.enabled===!0&&(s=n.duration,i=!0,Xe(s)?s<e&&(this.logger.warn(Dr(oe,s,e)),i=!1):(this.logger.warn(Cr(oe,s,rn)),s=rn)),{enabled:i,duration:s}}onError(e,n,s){this.errorHandler.onError({error:e,context:oe,customMessage:n,groupingHash:s})}getEncryptedCookieData(e,n){let s=[];return e.forEach(i=>{let r=n?.encrypt(K(i.value,!1,[],this.logger));pe(r)&&s.push({name:i.name,value:r})}),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 i=Object.keys(e),r=()=>i.map(d=>({name:e[d].name,value:o.session[d].value})),a={};i.forEach(d=>{a[e[d].name]=s?.get(e[d].name)});let l=()=>{i.forEach(d=>{this.serverSideCookiesRequestInProgress[d]=!1})},u=()=>{r().forEach(d=>{n&&n(d.name,d.value)})};try{let d={};i.forEach(S=>{d[e[S].name]=o.session[S].value});let p=this.getEncryptedCookieData(r(),s);p.length>0?this.makeRequestToSetCookie(p,(S,R)=>{l(),R?.xhr?.status===200?r().forEach(g=>{let h=a[g.name],I=s?.get(g.name);K(d[g.name],!1,[])!==K(I,!1,[])&&(G(h)&&G(I)&&this.logger.error(Ir(g.name)),n&&n(g.name,g.value))}):(this.logger.error(Sr(R?.xhr?.status)),u())}):(u(),l())}catch(d){this.onError(d,gn,gn),u(),l()}}syncValueToStorage(e){let n=o.storage.entries.value,s=n[e]?.type;if(Re(s)){let i=this.storeManager.getStore(fe[s]),r=n[e]?.key,a=o.session[e].value;a&&(_(a)||te(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:r}};this.setServerSideCookies(l,(u,d)=>{i?.set(u,d)},i)},so)):i?.set(r,a):i?.remove(r)}}registerEffects(){Is.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||Lt()):s=T.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===T.anonymousId)&&(s=this.getEntryValue("anonymousId")),!s&&e&&(s=this.pluginsManager?.invokeSingle("storage.getAnonymousId",H,e)),o.session.anonymousId.value=s||Lt()}return o.session.anonymousId.value}getEntryValue(e){let n=o.storage.entries.value,s=n[e]?.type;if(Re(s)){let i=this.storeManager?.getStore(fe[s]);this.migrateStorageIfNeeded([i],[e]);let r=n[e]?.key;return i?.get(r)??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()??T.sessionInfo;return e.autoTrack&&!Nn(e)||e.manualTrack?e.id??null:null}refreshSession(){let e=this.getSessionInfo()??T.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:i,cutOff:r}=e.sessionInfo.value;if(s){let a={...T.sessionInfo,timeout:i};r&&(a.cutOff={enabled:r.enabled,duration:r.duration}),e.sessionInfo.value=a,this.startOrRenewAutoTracking(e.sessionInfo.value)}else n&&this.startManualTrackingInternal()}reset(e){let{session:n}=o,s=Fl(e);w(()=>{Object.keys(T).forEach(i=>{let r=i;if(s.entries[r]===!0)switch(i){case"anonymousId":this.setAnonymousId();break;case"sessionInfo":this.resetAndStartNewSession();break;default:n[r].value=T[r];break}})})}setUserId(e){o.session.userId.value=this.isPersistenceEnabledForStorageEntry("userId")&&e?e:T.userId}setUserTraits(e){o.session.userTraits.value=this.isPersistenceEnabledForStorageEntry("userTraits")&&O(e)?L(o.session.userTraits.value??T.userTraits,e):T.userTraits}setGroupId(e){o.session.groupId.value=this.isPersistenceEnabledForStorageEntry("groupId")&&e?e:T.groupId}setGroupTraits(e){o.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry("groupTraits")&&O(e)?L(o.session.groupTraits.value??T.groupTraits,e):T.groupTraits}setInitialReferrer(e){o.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry("initialReferrer")&&e?e:T.initialReferrer}setInitialReferringDomain(e){o.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry("initialReferringDomain")&&e?e:T.initialReferringDomain}startOrRenewAutoTracking(e){let n=e;if(Nn(e))n=xl(e);else{let s=Date.now(),i=e.timeout;n.expiresAt=s+i}if(Cs(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=T.sessionInfo}setAuthToken(e){o.session.authToken.value=this.isPersistenceEnabledForStorageEntry("authToken")&&e?e:T.authToken}},Xl=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],Yl=Xl,ql=(t,e)=>{let n=E(e);return _(n.setCookieDomain)||(n.setCookieDomain=void 0),["Strict","Lax","None"].includes(n.sameSiteCookie)||(n.sameSiteCookie=void 0),n.secureCookie=Q(n.secureCookie,t.secureCookie),n.sameDomainCookiesOnly=Q(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=Yl),n.useGlobalIntegrationsConfigInEvents=Q(n.useGlobalIntegrationsConfigInEvents,t.useGlobalIntegrationsConfigInEvents),n.bufferDataPlaneEventsUntilReady=Q(n.bufferDataPlaneEventsUntilReady,t.bufferDataPlaneEventsUntilReady),n.sendAdblockPage=Q(n.sendAdblockPage,t.sendAdblockPage),n.useServerSideCookies=Q(n.useServerSideCookies,t.useServerSideCookies),_(n.dataServiceEndpoint)||(n.dataServiceEndpoint=void 0),n.sendAdblockPageOptions=Y(n.sendAdblockPageOptions),n.loadIntegration=Q(n.loadIntegration,t.loadIntegration),te(n.storage)?(n.storage.migrate=Q(n.storage.migrate,t.storage?.migrate),n.storage.cookie=Y(n.storage.cookie),n.storage.encryption=Y(n.storage.encryption),n.storage=Fe(n.storage)):n.storage=void 0,n.destinationsQueueOptions=Y(n.destinationsQueueOptions),n.queueOptions=Y(n.queueOptions),n.lockIntegrationsVersion=Q(n.lockIntegrationsVersion,t.lockIntegrationsVersion),n.lockPluginsVersion=Q(n.lockPluginsVersion,t.lockPluginsVersion),Ps(n.dataPlaneEventsBufferTimeout)||(n.dataPlaneEventsBufferTimeout=void 0),n.beaconQueueOptions=Y(n.beaconQueueOptions),n.preConsent=Y(n.preConsent),n.sourceConfigurationOverride=Y(n.sourceConfigurationOverride),L(t,Fe(n))},Pn="dataplaneEventsQueue",Cn="destinationsEventsQueue",Jl="transformEvent",Zl=(t,e)=>Object.keys(t).filter(n=>t[n]!==!0||!e[n]).reduce((n,s)=>{let i=E(n);return i[s]=t[s],i},{}),ec=(t,e)=>{let n=E(t),s=e.nativeDestinations.integrationsConfig.value,i=Zl(t.integrations,s);return n.integrations=L(s,i),n},tc=t=>t.consents.preConsent.value.enabled&&t.consents.preConsent.value.events?.delivery==="buffer",Ge=(t,e,n,s)=>{if(A(t))if(f(t))try{t(...e)}catch(i){s.error($r(n),i)}else s.error(es(n))},$t=class{constructor(e,n,s,i,r){this.pluginsManager=e,this.errorHandler=i,this.httpClient=s,this.logger=r,this.storeManager=n}init(){this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${Pn}.init`,o,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.dmtEventsQueue=this.pluginsManager.invokeSingle(`${Jl}.init`,o,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${Cn}.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=tc(o),n;X(()=>{let s=o.loadOptions.value.bufferDataPlaneEventsUntilReady===!0&&o.nativeDestinations.clientDestinationsReady.value===!1;(o.nativeDestinations.activeDestinations.value.some(r=>aa(r))===!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=ec(e,o);this.pluginsManager.invokeSingle(`${Pn}.enqueue`,o,this.dataplaneEventsQueue,s,this.errorHandler,this.logger);let i=E(e);this.pluginsManager.invokeSingle(`${Cn}.enqueue`,o,this.destinationsEventsQueue,i,this.errorHandler,this.logger);let r=`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}${jt}`;Ge(n,[s],r,this.logger)}},Dn=t=>{let e=new CustomEvent(t,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:!0,cancelable:!0,composed:!0});globalThis.document.dispatchEvent(e)},nc=t=>_(t)&&t.trim().length>0,sc=t=>me(t),Bt=class{constructor(){this.preloadBuffer=new ht,this.initialized=!1,this.errorHandler=hs,this.logger=ne,this.externalSrcLoader=new He(this.logger),this.httpClient=us,this.httpClient.init(this.errorHandler),this.capabilitiesManager=new kt(this.httpClient,this.errorHandler,this.logger)}load(e,n,s={}){if(!o.lifecycle.status.value){if(!nc(e)){this.logger.error(fr(ke,e));return}if(!sc(n)){this.logger.error(hr(ke,n));return}w(()=>{o.lifecycle.writeKey.value=E(e),o.lifecycle.dataPlaneUrl.value=E(n),o.loadOptions.value=ql(o.loadOptions.value,s),o.lifecycle.status.value="mounted"}),this.logger.setMinLogLevel(o.loadOptions.value.logLevel??Jn),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:ke,customMessage:n,groupingHash:n})}})}onBrowserCapabilitiesReady(){xi(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(E(n)))}processDataInPreloadBuffer(){for(;this.preloadBuffer.size()>0;){let e=this.preloadBuffer.dequeue();e&&Gi([...e],this)}}prepareInternalServices(){this.pluginsManager=new It(ra,this.errorHandler,this.logger),this.storeManager=new Nt(this.pluginsManager,this.errorHandler,this.logger),this.configManager=new Ct(this.httpClient,this.errorHandler,this.logger),this.userSessionManager=new Mt(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventRepository=new $t(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventManager=new Ut(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(),w(()=>{o.lifecycle.loaded.value=!0,o.lifecycle.status.value="loaded"}),this.initialized=!0;let e=o.loadOptions.value.onLoaded;Ge(e,[globalThis.rudderanalytics],ni,this.logger),Dn("RSA_Initialised")}onReady(){o.lifecycle.status.value="readyExecuted",o.eventBuffer.readyCallbacksArray.value.forEach(e=>{Ge(e,[],nt,this.logger)}),Dn("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];f(this[s])&&this[s](...n.slice(1),!0)}e=o.eventBuffer.toBeProcessedArray.value}}loadDestinations(){if(o.lifecycle.status.value==="destinationsLoading"||o.nativeDestinations.clientDestinationsReady.value===!0)return;this.pluginsManager?.invokeSingle("nativeDestinations.setActiveDestinations",o,this.pluginsManager,this.errorHandler,this.logger);let e=o.nativeDestinations.activeDestinations.value.length;if(e===0){w(()=>{o.nativeDestinations.clientDestinationsReady.value=!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(()=>{o.nativeDestinations.initializedDestinations.value.length+o.nativeDestinations.failedDestinations.value.length===e&&w(()=>{o.lifecycle.status.value="destinationsReady",o.nativeDestinations.clientDestinationsReady.value=!0})})}onDestinationsReady(){o.lifecycle.status.value!=="ready"&&w(()=>{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`),!f(e)){this.logger.error(es(nt));return}o.lifecycle.status.value==="readyExecuted"?Ge(e,[],nt,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!==tn&&this.page(je(tn,Ri,{path:_i},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 i=e.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type:s,to:e.to,from:i,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 i="setAnonymousId";if(!o.lifecycle.loaded.value){o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[i,e,n]];return}this.errorHandler.leaveBreadcrumb(`New ${i} 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"),w(()=>{o.consents.preConsent.value={...o.consents.preConsent.value,enabled:!1},o.consents.postConsent.value=ll(e);let{initialized:i,consentsData:r}=Rs(o.consents.postConsent.value.consentManagement,this.logger);o.consents.initialized.value=i,o.consents.data.value=r}),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=Vt(Oi);e?o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,["track",n]]:this.track(n)}if(o.consents.postConsent.value.sendPageEvent){let n=je();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 i="addCustomIntegration";if(s)this.errorHandler.leaveBreadcrumb(`New ${i} invocation`),this.pluginsManager?.invokeSingle("nativeDestinations.addCustomIntegration",e,n,o,this.logger);else{if(o.lifecycle.loaded.value){this.logger.error(zr(ke,e));return}o.eventBuffer.toBeProcessedArray.value=[...o.eventBuffer.toBeProcessedArray.value,[i,e,n]]}}},le=class le{constructor(){N(this,"analyticsInstances",{});N(this,"defaultAnalyticsKey","");N(this,"logger",ne);try{if(le.globalSingleton)return le.globalSingleton;le.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(),le.globalSingleton=this,o.autoTrack.pageLifecycle.pageViewId.value=Ye(),o.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now(),this.triggerBufferedLoadEvent(),globalThis.rudderanalytics=this}catch(e){C(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(){hs.init(),Xt.configure(),Qt.configure(),zt.configure(),ze.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 Bt),this.analyticsInstances[n]}catch(n){C(n);return}}load(e,n,s){try{if(this.analyticsInstances[e])return;this.setDefaultInstanceKey(e),this.trackPageLifecycleEvents(s);let i=Kn(_e);Bi(i),Pe(_e,E(i)),this.getAnalyticsInstance(e)?.load(e,n,y(s))}catch(i){C(i)}}trackPageLifecycleEvents(e){let{autoTrack:n,useBeacon:s}=e??{},{enabled:i=!1,options:r={},pageLifecycle:a}=n??{},{events:l=[tt.UNLOADED],enabled:u=i,options:d=r}=a??{};o.autoTrack.pageLifecycle.enabled.value=u,o.autoTrack.enabled.value=i||u,u&&this.setupPageUnloadTracking(l,s,d)}setupPageUnloadTracking(e,n,s){(e.length===0||e.includes(tt.UNLOADED))&&(n===!0?di(i=>{if(i===!1&&o.lifecycle.loaded.value){let r=Date.now(),a=r-o.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(tt.UNLOADED,{timeOnPage:a},{...s,originalTimestamp:xn(new Date(r))})}},!0):this.logger.warn(Kr(ii)))}triggerBufferedLoadEvent(){let e=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[],n=$i(e);Pe(_e,E([...e])),n.length>0&&(n.shift(),this.load.apply(null,n))}ready(e){try{this.getAnalyticsInstance()?.ready(y(e))}catch(n){C(n)}}page(e,n,s,i,r){try{this.getAnalyticsInstance()?.page(je(y(e),y(n),y(s),y(i),y(r)))}catch(a){C(a)}}track(e,n,s,i){try{this.getAnalyticsInstance()?.track(Vt(y(e),y(n),y(s),y(i)))}catch(r){C(r)}}identify(e,n,s,i){try{this.getAnalyticsInstance()?.identify(Un(y(e),y(n),y(s),y(i)))}catch(r){C(r)}}alias(e,n,s,i){try{this.getAnalyticsInstance()?.alias(Mn(y(e),y(n),y(s),y(i)))}catch(r){C(r)}}group(e,n,s,i){try{this.getAnalyticsInstance()?.group($n(y(e),y(n),y(s),y(i)))}catch(r){C(r)}}reset(e){try{this.getAnalyticsInstance()?.reset(y(e))}catch(n){C(n)}}getAnonymousId(e){try{return this.getAnalyticsInstance()?.getAnonymousId(y(e))}catch(n){C(n);return}}setAnonymousId(e,n){try{this.getAnalyticsInstance()?.setAnonymousId(y(e),y(n))}catch(s){C(s)}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId()}catch(e){C(e);return}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits()}catch(e){C(e);return}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId()}catch(e){C(e);return}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits()}catch(e){C(e);return}}startSession(e){try{this.getAnalyticsInstance()?.startSession(y(e))}catch(n){C(n)}}endSession(){try{this.getAnalyticsInstance()?.endSession()}catch(e){C(e)}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId()}catch(e){C(e);return}}setAuthToken(e){try{this.getAnalyticsInstance()?.setAuthToken(y(e))}catch(n){C(n)}}consent(e){try{this.getAnalyticsInstance()?.consent(y(e))}catch(n){C(n)}}addCustomIntegration(e,n){try{this.getAnalyticsInstance()?.addCustomIntegration(y(e),y(n))}catch(s){C(s)}}};N(le,"globalSingleton",null);var kn=le;export{kn as a};
5
- //# sourceMappingURL=chunk-YVBRA3QD.mjs.map
5
+ //# sourceMappingURL=chunk-MWNJTXSL.mjs.map