@deriv-com/analytics 1.43.0 → 1.44.0

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