var rudderanalytics=function(e){"use strict";function t(e){return null!=e&&"object"==typeof e&&!0===e["@@functional/placeholder"]}function n(e){return function n(i){return 0===arguments.length||t(i)?n:e.apply(this,arguments)}}function i(e){return function i(s,r){switch(arguments.length){case 0:return i;case 1:return t(s)?i:n((function(t){return e(s,t)}));default:return t(s)&&t(r)?i:t(s)?n((function(t){return e(t,r)})):t(r)?n((function(t){return e(s,t)})):e(s,r)}}}function s(e){return function s(r,o,a){switch(arguments.length){case 0:return s;case 1:return t(r)?s:i((function(t,n){return e(r,t,n)}));case 2:return t(r)&&t(o)?s:t(r)?i((function(t,n){return e(t,o,n)})):t(o)?i((function(t,n){return e(r,t,n)})):n((function(t){return e(r,o,t)}));default:return t(r)&&t(o)&&t(a)?s:t(r)&&t(o)?i((function(t,n){return e(t,n,a)})):t(r)&&t(a)?i((function(t,n){return e(t,o,n)})):t(o)&&t(a)?i((function(t,n){return e(r,t,n)})):t(r)?n((function(t){return e(t,o,a)})):t(o)?n((function(t){return e(r,t,a)})):t(a)?n((function(t){return e(r,o,t)})):e(r,o,a)}}}function r(e,t){return Object.prototype.hasOwnProperty.call(t,e)}var o=n((function(e){return null===e?"Null":void 0===e?"Undefined":Object.prototype.toString.call(e).slice(8,-1)}));function a(e){return"[object Object]"===Object.prototype.toString.call(e)}const l=Number.isInteger||function(e){return(e|0)===e};function u(e,t){var n,i=e<0?t.length+e:e;return n=t,"[object String]"===Object.prototype.toString.call(n)?t.charAt(i):t[i]}function c(e,t,n){if(n||(n=new d),function(e){var t=typeof e;return null==e||"object"!=t&&"function"!=t}(e))return e;var i,s=function(t){var i=n.get(e);if(i)return i;for(var s in n.set(e,t),e)Object.prototype.hasOwnProperty.call(e,s)&&(t[s]=c(e[s],!0,n));return t};switch(o(e)){case"Object":return s(Object.create(Object.getPrototypeOf(e)));case"Array":return s(Array(e.length));case"Date":return new Date(e.valueOf());case"RegExp":return i=e,new RegExp(i.source,i.flags?i.flags:(i.global?"g":"")+(i.ignoreCase?"i":"")+(i.multiline?"m":"")+(i.sticky?"y":"")+(i.unicode?"u":"")+(i.dotAll?"s":""));case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"BigInt64Array":case"BigUint64Array":return e.slice();default:return e}}var d=function(){function e(){this.map={},this.length=0}return e.prototype.set=function(e,t){var n=this.hash(e),i=this.map[n];i||(this.map[n]=i=[]),i.push([e,t]),this.length+=1},e.prototype.hash=function(e){var t=[];for(var n in e)t.push(Object.prototype.toString.call(e[n]));return t.join()},e.prototype.get=function(e){if(this.length<=180)for(var t in this.map)for(var n=this.map[t],i=0;i"function"==typeof e&&Boolean(e.constructor&&e.call&&e.apply),k=e=>"string"==typeof e,I=e=>null===e,E=e=>void 0===e,S=e=>I(e)||E(e),T=e=>!E(e),A=e=>!S(e),w=e=>{switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return e instanceof Error}},$=(e,t)=>{const n=t.split(".");return y(n,e)},C=e=>!I(e)&&"[object Object]"===Object.prototype.toString.call(e),O=(e,t)=>{if(!Array.isArray(e)||!Array.isArray(t))return g(t);const n=g(e);return t.forEach(((e,t)=>{n[t]=Array.isArray(e)||(e=>!I(e)&&(e=>"object"==typeof e)(e)&&!Array.isArray(e))(e)?P(n[t],e):e})),n},P=(e,t)=>f(O,e,t),D=e=>C(e)&&Object.keys(e).length>0,R=e=>{const t=m(T,e);return Object.keys(t).forEach((e=>{const n=t[e];C(n)&&(t[e]=R(n))})),t},N=e=>{const t=m(A,e);return Object.keys(t).forEach((e=>{const n=t[e];C(n)&&(t[e]=N(n))})),t},L=e=>{if(D(e))return N(e)},M=(e,t)=>"boolean"==typeof e?e:t,B=e=>e.replace(/^\.+/,""),x=e=>{let t=e;if(!k(e)&&!S(e))try{t=JSON.stringify(e)}catch(e){t=null}return t},U=e=>(e=>{const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return globalThis.btoa(t)})((new TextEncoder).encode(e)),j=(e,t,n,i,s)=>{const r={category:e,name:t,properties:n,options:i,callback:void 0};b(s)&&(r.callback=s),b(i)&&(r.category=e,r.name=t,r.properties=n,r.options=void 0,r.callback=i),b(n)&&(r.category=e,r.name=t,r.properties=void 0,r.options=void 0,r.callback=n),b(t)&&(r.category=e,r.name=void 0,r.properties=void 0,r.options=void 0,r.callback=t),b(e)&&(r.category=void 0,r.name=void 0,r.properties=void 0,r.options=void 0,r.callback=e),C(e)?(r.name=void 0,r.category=void 0,r.properties=e,b(t)?r.options=void 0:r.options=t):C(t)&&(r.name=void 0,r.properties=t,b(n)?r.options=void 0:r.options=n),k(e)&&!k(t)&&(r.category=void 0,r.name=e),T(r.category)||(r.category=void 0),T(r.name)||(r.name=void 0),r.properties=r.properties?g(r.properties):{},T(r.options)?r.options=g(r.options):r.options=void 0;const o=k(r.name)?r.name:r.properties.name,a=k(r.category)?r.category:r.properties.category;return r.properties=P(C(r.properties)?r.properties:{},{...o&&{name:o},...a&&{category:a}}),r},_=(e,t,n,i)=>{const s={name:e,properties:t,options:n,callback:void 0};return b(i)&&(s.callback=i),b(n)&&(s.properties=t,s.options=void 0,s.callback=n),b(t)&&(s.properties=void 0,s.options=void 0,s.callback=t),s.properties=A(s.properties)?g(s.properties):{},T(s.options)?s.options=g(s.options):s.options=void 0,s},H=(e,t,n,i)=>{const s={userId:e,traits:t,options:n,callback:void 0};return b(i)&&(s.callback=i),b(n)&&(s.userId=e,s.traits=t,s.options=void 0,s.callback=n),b(t)&&(s.userId=e,s.traits=void 0,s.options=void 0,s.callback=t),(C(e)||I(e))&&(s.userId=null,s.traits=e,b(t)?s.options=void 0:s.options=t),s.userId=x(s.userId),C(s.traits)?s.traits=g(s.traits):s.traits=void 0,T(s.options)?s.options=g(s.options):s.options=void 0,s},F=(e,t,n,i)=>{const s={to:e,from:t,options:n,callback:void 0};return b(i)&&(s.callback=i),b(n)&&(s.to=e,s.from=t,s.options=void 0,s.callback=n),b(t)?(s.to=e,s.from=void 0,s.options=void 0,s.callback=t):(C(t)||I(t))&&(s.to=e,s.from=void 0,s.options=t),T(s.to)&&(s.to=x(s.to)),T(s.from)?s.from=x(s.from):s.from=void 0,T(s.options)?s.options=g(s.options):s.options=void 0,s},G=(e,t,n,i)=>{const s={groupId:e,traits:t,options:n,callback:void 0};return b(i)&&(s.callback=i),b(n)&&(s.groupId=e,s.traits=t,s.options=void 0,s.callback=n),b(t)&&(s.groupId=e,s.traits=void 0,s.options=void 0,s.callback=t),(C(e)||I(e))&&(s.groupId=null,s.traits=e,b(t)?s.options=void 0:s.options=t),s.groupId=x(s.groupId),C(s.traits)?s.traits=g(s.traits):s.traits=void 0,T(s.options)?s.options=g(s.options):s.options=void 0,s};let K=function(e){return e.UNLOADED="Page Unloaded",e}({});const V="API",Q="CapabilitiesManager",z="ConfigManager",q="EventManager",W="PluginsManager",J="UserSessionManager",X="ErrorHandler",Z="PluginEngine",Y=`Ready${V}`,ee=`Load${V}`,te="AnalyticsCore";for(var ne,ie=[],se=0;se<256;se++)ie[se]=(se+256).toString(16).substring(1);function re(){var e;(!ne||se+16>4096)&&(e=4096,ne=crypto.getRandomValues(new Uint8Array(e)),se=0);for(var t,n=0,i="";n<16;n++)t=ne[se+n],i+=6==n?ie[15&t|64]:8==n?ie[63&t|128]:ie[t],1&n&&n>1&&n<11&&(i+="-");return se+=16,i}for(var oe,ae=256,le=[];ae--;)le[ae]=(ae+256).toString(16).substring(1);const ue=()=>!S(globalThis.crypto)&&b(globalThis.crypto.getRandomValues)?re():function(){var e,t=0,n="";if(!oe||ae+16>256){for(oe=Array(t=256);t--;)oe[t]=256*Math.random()|0;t=ae=0}for(;t<16;t++)e=oe[ae+t],n+=6==t?le[15&e|64]:8==t?le[63&e|128]:le[e],1&t&&t>1&&t<11&&(n+="-");return ae++,n}(),ce=e=>e.toISOString(),de=":: ",ge=(e,t,n)=>`Unable to load (${k(n)?n:n.type}) the script with the id "${e}" from URL "${t}"`,he="[Circular Reference]",pe=(e,t,n)=>{const i=[];return function(s,r){if(!(t?.includes(s)||e&&S(r))){if("object"!=typeof r||I(r))return r;for(;i.length>0&&i[i.length-1]!==this;)i.pop();return i.includes(r)?(n?.warn(((e,t)=>`${e}${de}A circular reference has been detected in the object and the property "${t}" has been dropped from the output.`)("JSONStringify",s)),he):(i.push(r),r)}}},ve=(e,t,n,i)=>{try{return JSON.stringify(e,pe(t,n,i))}catch(e){return i?.warn("Failed to convert the value to a JSON string.",e),null}},fe=e=>{const t=[];return function(e,n){if((e=>"bigint"==typeof e)(n))return"[BigInt]";for(;t.length>0&&t[t.length-1]!==this;)t.pop();return t.includes(n)?he:(t.push(n),n)}},ye=(e,t)=>{const n=Array.isArray(e)?[]:{};for(const i in e)if(Object.hasOwnProperty.call(e,i)){const s=e[i],r=t.call(e,i,s);C(r)||Array.isArray(r)?n[i]=ye(r,t):n[i]=r}return n},me=(e,t)=>{const n=fe(),i=n.call(e,"",e);return C(e)||Array.isArray(e)?ye(e,n):i},be="[SDK DISPATCHED ERROR]",ke=e=>{const{stack:t,stacktrace:n}=e,i=e["opera#sourceloc"],s=t??n??i;if(s&&"string"==typeof s)return s},Ie=(e,t)=>{let n=e;return w(e)?n.message=`${t}: ${e.message}`:n=new Error(`${t}: ${ve(e)}`),n},Ee=e=>{if(w(e)){const t=ke(e);if(t){const{stack:n,stacktrace:i}=e,s=e["opera#sourceloc"];switch(t){case n:e.stack=`${n}\n${be}`;break;case i:e.stacktrace=`${i}\n${be}`;break;default:e["opera#sourceloc"]=`${s}\n${be}`}}}globalThis.dispatchEvent(new ErrorEvent("error",{error:e,bubbles:!0,cancelable:!0,composed:!0}))},Se="RudderLabs JavaScript SDK",Te="3.21.0",Ae="RudderJS-Initiated",we="preloadedEventsBuffer",$e="ajs_aid",Ce="ajs_uid",Oe="ajs_event",Pe=432e5,De=18e5,Re=(e="app")=>{globalThis.RudderStackGlobals||(globalThis.RudderStackGlobals={}),globalThis.RudderStackGlobals[e]||(globalThis.RudderStackGlobals[e]={})},Ne=(e,t,n="app")=>{Re(n),globalThis.RudderStackGlobals[n][e]=t},Le=(e,t="app")=>(Re(t),globalThis.RudderStackGlobals[t][e]);const Me=(e,t)=>{const n={};return e.forEach(((i,s)=>{if(s.startsWith(t)){const i=s.substring(t.length);n[i]=e.get(s)}})),n},Be=e=>{const t=Le(we)||[];((e=[])=>{const t="ajs_trait_",n="ajs_prop_",i=new URLSearchParams(globalThis.location.search);i.get(Oe)&&e.unshift(["track",i.get(Oe),Me(i,n)]),i.get(Ce)&&e.unshift(["identify",i.get(Ce),Me(i,t)]),i.get($e)&&e.unshift(["setAnonymousId",i.get($e)])})(t),t.length>0&&(e.enqueuePreloadBufferEvents(t),Ne(we,[]))},xe=(e,t)=>{const n=e.shift();let i;if(b(t[n])){switch(n){case"page":i=j(...e);break;case"track":i=_(...e);break;case"identify":i=H(...e);break;case"alias":i=F(...e);break;case"group":i=G(...e);break;default:t[n](...e)}i&&t[n](i)}},Ue=(e,t,n,i=!0,s)=>new Promise(((r,o)=>{document.getElementById(t)&&o(new Error((e=>`A script with the id "${e}" is already loaded. Skipping the loading of this script to prevent conflicts`)(t)));try{let a;(e=>{const t=document.getElementsByTagName("head");if(t.length>0)return void t[0]?.insertBefore(e,t[0]?.firstChild);const n=document.getElementsByTagName("script");if(n.length>0&&n[0]?.parentNode)return void n[0]?.parentNode.insertBefore(e,n[0]);const i=document.createElement("head");i.appendChild(e);const s=document.getElementsByTagName("html")[0];s?.insertBefore(i,s.firstChild)})(((e,t,n=!0,i=null,s=null,r={})=>{const o=document.createElement("script");return o.type="text/javascript",o.onload=i,o.onerror=s,o.src=e,o.id=t,o.async=n,Object.keys(r).forEach((e=>{o.setAttribute(e,r[e])})),o.setAttribute("data-loader","RS_JS_SDK"),o})(e,t,i,(()=>{globalThis.clearTimeout(a),r(t)}),(n=>{globalThis.clearTimeout(a),o(new Error(ge(t,e,n)))}),s)),a=globalThis.setTimeout((()=>{o(new Error(((e,t,n)=>`A timeout of ${n} ms occurred while trying to load the script with id "${e}" from URL "${t}"`)(t,e,n)))}),n)}catch(n){o(Ie(n,ge(t,e,"unknown")))}}));class je{constructor(e,t=1e4){this.logger=e,this.timeout=t}loadJSFile(e){const{url:t,id:n,timeout:i,async:s,callback:r,extraAttributes:o}=e,a=!b(r);Ue(t,n,i||this.timeout,s,o).then((e=>{a||r(e)})).catch((e=>{a||r(n,e)}))}}var _e=Symbol.for("preact-signals");function He(){if(Qe>1)Qe--;else{for(var e,t=!1;void 0!==Ve;){var n=Ve;for(Ve=void 0,ze++;void 0!==n;){var i=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&Ze(n))try{n.c()}catch(n){t||(e=n,t=!0)}n=i}}if(ze=0,Qe--,t)throw e}}function Fe(e){if(Qe>0)return e();Qe++;try{return e()}finally{He()}}var Ge=void 0;function Ke(e){var t=Ge;Ge=void 0;try{return e()}finally{Ge=t}}var Ve=void 0,Qe=0,ze=0,qe=0;function We(e){if(void 0!==Ge){var t=e.n;if(void 0===t||t.t!==Ge)return t={i:0,S:e,p:Ge.s,n:void 0,t:Ge,e:void 0,x:void 0,r:t},void 0!==Ge.s&&(Ge.s.n=t),Ge.s=t,e.n=t,32&Ge.f&&e.S(t),t;if(-1===t.i)return t.i=0,void 0!==t.n&&(t.n.p=t.p,void 0!==t.p&&(t.p.n=t.n),t.p=Ge.s,t.n=void 0,Ge.s.n=t,Ge.s=t),t}}function Je(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched}function Xe(e,t){return new Je(e,t)}function Ze(e){for(var t=e.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function Ye(e){for(var t=e.s;void 0!==t;t=t.n){var n=t.S.n;if(void 0!==n&&(t.r=n),t.S.n=t,t.i=-1,void 0===t.n){e.s=t;break}}}function et(e){for(var t=e.s,n=void 0;void 0!==t;){var i=t.p;-1===t.i?(t.S.U(t),void 0!==i&&(i.n=t.n),void 0!==t.n&&(t.n.p=i)):n=t,t.S.n=t.r,void 0!==t.r&&(t.r=void 0),t=i}e.s=n}function tt(e,t){Je.call(this,void 0),this.x=e,this.s=void 0,this.g=qe-1,this.f=4,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched}function nt(e){var t=e.u;if(e.u=void 0,"function"==typeof t){Qe++;var n=Ge;Ge=void 0;try{t()}catch(t){throw e.f&=-2,e.f|=8,it(e),t}finally{Ge=n,He()}}}function it(e){for(var t=e.s;void 0!==t;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,nt(e)}function st(e){if(Ge!==this)throw new Error("Out-of-order effect");et(this),Ge=e,this.f&=-2,8&this.f&&it(this),He()}function rt(e){this.x=e,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}function ot(e){var t=new rt(e);try{t.c()}catch(e){throw t.d(),e}return t.d.bind(t)}Je.prototype.brand=_e,Je.prototype.h=function(){return!0},Je.prototype.S=function(e){var t=this,n=this.t;n!==e&&void 0===e.e&&(e.x=n,this.t=e,void 0!==n?n.e=e:Ke((function(){var e;null==(e=t.W)||e.call(t)})))},Je.prototype.U=function(e){var t=this;if(void 0!==this.t){var n=e.e,i=e.x;void 0!==n&&(n.x=i,e.e=void 0),void 0!==i&&(i.e=n,e.x=void 0),e===this.t&&(this.t=i,void 0===i&&Ke((function(){var e;null==(e=t.Z)||e.call(t)})))}},Je.prototype.subscribe=function(e){var t=this;return ot((function(){var n=t.value,i=Ge;Ge=void 0;try{e(n)}finally{Ge=i}}))},Je.prototype.valueOf=function(){return this.value},Je.prototype.toString=function(){return this.value+""},Je.prototype.toJSON=function(){return this.value},Je.prototype.peek=function(){var e=Ge;Ge=void 0;try{return this.value}finally{Ge=e}},Object.defineProperty(Je.prototype,"value",{get:function(){var e=We(this);return void 0!==e&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(ze>100)throw new Error("Cycle detected");this.v=e,this.i++,qe++,Qe++;try{for(var t=this.t;void 0!==t;t=t.x)t.t.N()}finally{He()}}}}),tt.prototype=new Je,tt.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if(32==(36&this.f))return!0;if(this.f&=-5,this.g===qe)return!0;if(this.g=qe,this.f|=1,this.i>0&&!Ze(this))return this.f&=-2,!0;var e=Ge;try{Ye(this),Ge=this;var t=this.x();(16&this.f||this.v!==t||0===this.i)&&(this.v=t,this.f&=-17,this.i++)}catch(e){this.v=e,this.f|=16,this.i++}return Ge=e,et(this),this.f&=-2,!0},tt.prototype.S=function(e){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}Je.prototype.S.call(this,e)},tt.prototype.U=function(e){if(void 0!==this.t&&(Je.prototype.U.call(this,e),void 0===this.t)){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}},tt.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;void 0!==e;e=e.x)e.t.N()}},Object.defineProperty(tt.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=We(this);if(this.h(),void 0!==e&&(e.i=this.i),16&this.f)throw this.v;return this.v}}),rt.prototype.c=function(){var e=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();"function"==typeof t&&(this.u=t)}finally{e()}},rt.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,nt(this),Ye(this),Qe++;var e=Ge;return Ge=this,st.bind(this,e)},rt.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ve,Ve=this)},rt.prototype.d=function(){this.f|=8,1&this.f||it(this)},rt.prototype.dispose=function(){this.d()};class at{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return 0===this.items.length?null:this.items.shift()}isEmpty(){return 0===this.items.length}size(){return this.items.length}clear(){this.items=[]}}const lt={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5},ut="ERROR";const ct=new class{constructor(e="LOG",t="",n=console){this.minLogLevel=lt[e],this.scope=t,this.logProvider=n}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,t){this.minLogLevel<=lt[e]&&this.logProvider[e.toLowerCase()]?.(...this.formatLogData(t))}setScope(e){this.scope=e||this.scope}setMinLogLevel(e){this.minLogLevel=lt[e],E(this.minLogLevel)&&(this.minLogLevel=lt.LOG)}formatLogData(e){if(Array.isArray(e)&&e.length>0){let t="%c RS SDK";this.scope&&(t=`${t} - ${this.scope}`);t=`${t} %c ${k(e[0])?e[0].trim():""}`;const n=[t,"font-weight: bold; background: black; color: white;","font-weight: normal;"];return k(e[0])||n.push(e[0]),n.push(...e.slice(1)),n}return e}};let dt=function(e){return e.HANDLEDEXCEPTION="handledException",e.UNHANDLEDEXCEPTION="unhandledException",e.UNHANDLEDREJECTION="unhandledPromiseRejection",e}({});const gt=["localStorage","memoryStorage","cookieStorage","sessionStorage","none"],ht="cookieStorage",pt="Unable to process/parse source configuration response",vt="Failed to log breadcrumb",ft="Failed to fetch the source config",yt=e=>`${e}${de}The provided callback parameter is not a function.`,mt=(e,t,n)=>`${e} due to timeout or no connection (${t?t.type:""}) at the client side for URL: ${n}`,bt="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.",kt={All:!0},It="js-integrations",Et="plugins",St=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_]*)?$"),Tt="modern",At="https://cdn.rudderlabs.com",wt="v3",$t=`${At}/${wt}/${Tt}/${It}`,Ct=`${At}/${wt}/${Tt}/${Et}`,Ot="https://api.rudderstack.com",Pt="v3",Dt="xhr",Rt={iubenda:"IubendaConsentManager",oneTrust:"OneTrustConsentManager",ketch:"KetchConsentManager",custom:"CustomConsentManager"},Nt={[Pt]:"StorageEncryption",legacy:"StorageEncryptionLegacy"},Lt={[Dt]:"XhrQueue",beacon:"BeaconQueue"},Mt=Xe(g({configUrl:Ot,loadIntegration:!0,sessions:{autoTrack:!0,timeout:De,cutOff:{enabled:!1}},sameSiteCookie:"Lax",polyfillIfRequired:!0,integrations:kt,useBeacon:!1,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:!0,lockPluginsVersion:!0,uaChTrackLevel:"none",plugins:[],useGlobalIntegrationsConfigInEvents:!1,bufferDataPlaneEventsUntilReady:!1,dataPlaneEventsBufferTimeout:1e4,storage:{encryption:{version:Pt},migrate:!0,cookie:{}},sendAdblockPage:!1,sameDomainCookiesOnly:!1,secureCookie:!1,sendAdblockPageOptions:{},useServerSideCookies:!1})),Bt={userId:"",userTraits:{},anonymousId:"",groupId:"",groupTraits:{},initialReferrer:"",initialReferringDomain:"",sessionInfo:{},authToken:null},xt={userId:Xe(Bt.userId),userTraits:Xe(Bt.userTraits),anonymousId:Xe(Bt.anonymousId),groupId:Xe(Bt.groupId),groupTraits:Xe(Bt.groupTraits),initialReferrer:Xe(Bt.initialReferrer),initialReferringDomain:Xe(Bt.initialReferringDomain),sessionInfo:Xe(Bt.sessionInfo),authToken:Xe(Bt.authToken)},Ut={isOnline:Xe(!0),storage:{isLocalStorageAvailable:Xe(!1),isCookieStorageAvailable:Xe(!1),isSessionStorageAvailable:Xe(!1)},isBeaconAvailable:Xe(!1),isLegacyDOM:Xe(!1),isUaCHAvailable:Xe(!1),isCryptoAvailable:Xe(!1),isIE11:Xe(!1),isAdBlockerDetectionInProgress:Xe(!1),isAdBlocked:Xe(void 0),cspBlockedURLs:Xe([])},jt={isErrorReportingEnabled:Xe(!1),isMetricsReportingEnabled:Xe(!1),breadcrumbs:Xe([])},_t=Xe(void 0),Ht={activeDataplaneUrl:Xe(void 0),integrationsCDNPath:Xe($t),pluginsCDNPath:Xe(Ct),sourceConfigUrl:Xe(void 0),status:Xe(void 0),initialized:Xe(!1),logLevel:Xe(ut),loaded:Xe(!1),readyCallbacks:Xe([]),writeKey:Xe(void 0),dataPlaneUrl:Xe(void 0)},Ft={enabled:Xe(!1),initialized:Xe(!1),data:Xe({}),activeConsentManagerPluginName:Xe(void 0),preConsent:Xe({enabled:!1}),postConsent:Xe({}),resolutionStrategy:Xe("and"),provider:Xe(void 0),metadata:Xe(void 0)},Gt={retries:Xe(0),dropped:Xe(0),sent:Xe(0),queued:Xe(0),triggered:Xe(0),metricsServiceUrl:Xe(void 0)},Kt={app:Xe({name:Se,namespace:"com.rudderlabs.javascript",version:Te,installType:"cdn"}),traits:Xe(null),library:Xe({name:Se,version:Te,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:Xe(null),device:Xe(null),network:Xe(null),os:Xe({name:"",version:""}),locale:Xe(null),screen:Xe({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),"ua-ch":Xe(void 0),timezone:Xe(void 0)},Vt={configuredDestinations:Xe([]),activeDestinations:Xe([]),loadOnlyIntegrations:Xe({}),failedDestinations:Xe([]),loadIntegration:Xe(!0),initializedDestinations:Xe([]),clientDestinationsReady:Xe(!1),integrationsConfig:Xe({})},Qt={toBeProcessedArray:Xe([]),readyCallbacksArray:Xe([])},zt={ready:Xe(!1),loadedPlugins:Xe([]),failedPlugins:Xe([]),pluginsToLoadFromConfig:Xe([]),activePlugins:Xe([]),totalPluginsToLoad:Xe(0)},qt={encryptionPluginName:Xe(void 0),migrate:Xe(!1),type:Xe(void 0),cookie:Xe(void 0),entries:Xe({}),trulyAnonymousTracking:Xe(!1)},Wt={isEnabledServerSideCookies:Xe(!1),dataServiceUrl:Xe(void 0)},Jt={eventsQueuePluginName:Xe(void 0),deliveryEnabled:Xe(!0)},Xt={enabled:Xe(!1),pageLifecycle:{enabled:Xe(!1),pageViewId:Xe(void 0),pageLoadedTimestamp:Xe(void 0)}},Zt={...g({capabilities:Ut,consents:Ft,context:Kt,eventBuffer:Qt,lifecycle:Ht,loadOptions:Mt,metrics:Gt,nativeDestinations:Vt,plugins:zt,reporting:jt,session:xt,source:_t,storage:qt,serverCookies:Wt,dataPlaneEvents:Jt,autoTrack:Xt})};function Yt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var en,tn={exports:{}},nn={exports:{}};function sn(){return en||(en=1,nn.exports=function(){function e(e){return!isNaN(parseFloat(e))&&isFinite(e)}function t(e){return e.charAt(0).toUpperCase()+e.substring(1)}function n(e){return function(){return this[e]}}var i=["isConstructor","isEval","isNative","isToplevel"],s=["columnNumber","lineNumber"],r=["fileName","functionName","source"],o=["args"],a=["evalOrigin"],l=i.concat(s,r,o,a);function u(e){if(e)for(var n=0;n-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var t=e.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),n=t.match(/ (\(.+\)$)/);t=n?t.replace(n[0],""):t;var i=this.extractLocation(n?n[1]:t),s=n&&t||void 0,r=["eval",""].indexOf(i[0])>-1?void 0:i[0];return new on({functionName:s,fileName:r,lineNumber:i[1],columnNumber:i[2],source:e})}),this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter((function(e){return!e.match(un)}),this).map((function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new on({functionName:e});var t=/((.*".+"[^@]*)?[^@]*)(?:@)/,n=e.match(t),i=n&&n[1]?n[1]:void 0,s=this.extractLocation(e.replace(t,""));return new on({functionName:i,fileName:s[0],lineNumber:s[1],columnNumber:s[2],source:e})}),this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,n=e.message.split("\n"),i=[],s=2,r=n.length;s/,"$2").replace(/\([^)]*\)/g,"")||void 0;s.match(/\(([^)]*)\)/)&&(t=s.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var o=void 0===t||"[arguments not available]"===t?void 0:t.split(",");return new on({functionName:r,args:o,fileName:i[0],lineNumber:i[1],columnNumber:i[2],source:e})}),this)}})),tn.exports);const dn=Yt(cn),gn="global code",hn=e=>k(e)?e:"";function pn(e,t,n,i){return{errorClass:hn(e),message:`${n}${hn(t)}`,type:"browserjs",stacktrace:i.reduce(((e,t)=>{const n=(e=>{const t={file:e.fileName,method:(n=e.functionName,T(n)&&/^global code$/i.test(n)?gn:n),lineNumber:e.lineNumber,columnNumber:e.columnNumber};var n;return t.lineNumber&&t.lineNumber>-1&&!t.file&&!t.method&&(t.file=gn),t})(t);try{return"{}"===JSON.stringify(n)?e:e.concat(n)}catch{return e}}),[])}}const vn=(e,t)=>{let n;var i,s;return w(e)&&k(ke(e))?n=e:(t.warn((i=X,s=ve(e),`${i}${de}Ignoring a non-error: ${s}.`)),n=void 0),n},fn=(e,t)=>{try{return JSON.parse(e||"")}catch(e){t(Ie(e,"Failed to parse response data"))}},yn="The request failed",mn=[new RegExp(`${yn}.*`),/A script with the id .* is already loaded\./],bn=[/Failed to fetch dynamically imported module: .*/,/Unable to load \(.*\) the script with the id .*/,/A timeout of \d+ ms occurred while trying to load the script with id .*/],kn={headers:{Accept:"application/json","Content-Type":"application/json;charset=UTF-8"},method:"GET"},In=(e,t,n)=>{const i=P(kn,t||{});return n&&(i.headers=P(i.headers,{Authorization:n})),i.url=e,i},En=(e,t=1e4,n)=>new Promise(((i,s)=>{let r;if(!0===e.sendRawData)r=e.data;else if(r=ve(e.data,!1,[],n),I(r))return void s({error:new Error("Failed to prepare data for the request."),undefined:void 0,options:e});const o=new XMLHttpRequest,a=t=>{s({error:new Error(mt(yn,t,e.url)),xhr:o,options:e,..."timeout"===t?.type?{timedOut:!0}:{}})};o.ontimeout=a,o.onerror=a,o.onload=()=>{var t,n,r,a,l;o.status>=200&&o.status<400?i({response:o.responseText,xhr:o,options:e}):s({error:new Error((t=yn,n=o.status,r=o.statusText,a=e.url,l=o.responseText,`${t} with status ${n} (${r}) for URL: ${a}. Response: ${l.trim()}`)),xhr:o,options:e})},o.open(e.method,e.url,!0),!0===e.withCredentials&&(o.withCredentials=!0),o.timeout=t,Object.keys(e.headers).forEach((t=>{e.headers[t]&&o.setRequestHeader(t,e.headers[t])}));try{o.send(r)}catch(t){s({error:Ie(t,(l=yn,u=e.url,`${l} for URL: ${u}`)),xhr:o,options:e})}var l,u}));const Sn=new class{constructor(e){this.logger=e,this.onError=this.onError.bind(this)}init(e){this.errorHandler=e}async getData(e){const{url:t,options:n,timeout:i,isRawResponse:s}=e;try{const e=await En(In(t,n,this.basicAuthHeader),i,this.logger);return{data:s?e.response:fn(e.response,this.onError),details:e}}catch(e){return{data:void 0,details:e}}}getAsyncData(e){const{callback:t,url:n,options:i,timeout:s,isRawResponse:r}=e,o=!b(t);En(In(n,i,this.basicAuthHeader),s,this.logger).then((e=>{o||t(r?e.response:fn(e.response,this.onError),e)})).catch((e=>{o||t(void 0,e)}))}onError(e,t){this.errorHandler?.onError({error:e,context:"HttpClient",groupingHash:t})}setAuthHeader(e,t=!1){const n=t?e:U(`${e}:`);this.basicAuthHeader=`Basic ${n}`}resetAuthHeader(){this.basicAuthHeader=void 0}}(ct),Tn=["www.test-host.com","localhost","127.0.0.1","[::1]"],An=["userId","userTraits","groupId","groupTraits","anonymousId","config","instance","eventBuffer","traits","authToken"],wn=e=>{Zt.capabilities.isAdBlockerDetectionInProgress.value=!0;try{const t=new URL(Zt.lifecycle.sourceConfigUrl.value),n=`${t.origin}${t.pathname}?view=ad`;e.getAsyncData({url:n,options:{method:"HEAD",headers:{"Content-Type":void 0}},isRawResponse:!0,callback:(e,t)=>{Zt.capabilities.isAdBlockerDetectionInProgress.value=!1,Zt.capabilities.isAdBlocked.value=void 0!==t?.error||t?.xhr?.responseURL!==n}})}catch(e){throw Zt.capabilities.isAdBlockerDetectionInProgress.value=!1,e}},$n=()=>{const e=globalThis.location.hostname;return!e||e&&Tn.includes(e)?"development":"production"},Cn=e=>{const t=ve(e,!1,An);return null!==t?JSON.parse(t):{}},On=(e,t,n,i)=>({id:`${e.value?.id??n.writeKey.value}..${t.sessionInfo.value.id??"NA"}..${i.pageLifecycle.pageViewId.value??"NA"}`,name:e.value?.name??"NA"}),Pn=(e,t)=>({locale:e.value??"NA",userAgent:t.value??"NA",time:new Date}),Dn=(e,t,n)=>{const i=e.message;return new Promise((e=>{if(bn.some((e=>e.test(i)))){const s=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(i)?.[0];k(s)?s.startsWith(At)?t.capabilities.cspBlockedURLs.value.includes(s)?e(!1):((e,t,n)=>{if(E(e.capabilities.isAdBlocked.value)){!1===e.capabilities.isAdBlockerDetectionInProgress.value&&wn(t);const i=ot((()=>{T(e.capabilities.isAdBlocked.value)&&(n(!1===e.capabilities.isAdBlocked.value),i())}))}else n(!1===e.capabilities.isAdBlocked.value)})(t,n,e):e(!1):e(!0)}else e(!mn.some((e=>e.test(i))))}))},Rn=(e,t)=>{const n={version:"1",message_id:ue(),source:{name:"js",sdk_version:t.context.app.value.version,write_key:t.lifecycle.writeKey.value,install_type:t.context.app.value.installType},errors:e};return ve(n)};const Nn=new class{initialized=!1;constructor(e,t){this.httpClient=e,this.logger=t}init(){this.initialized||(this.attachErrorListeners(),this.initialized=!0)}attachErrorListeners(){globalThis.addEventListener("error",(e=>{this.onError({error:e,context:X,errorType:dt.UNHANDLEDEXCEPTION})})),globalThis.addEventListener("unhandledrejection",(e=>{this.onError({error:e,context:X,errorType:dt.UNHANDLEDREJECTION})})),document.addEventListener("securitypolicyviolation",(e=>{const t=k(e.blockedURI)?e.blockedURI:"";"enforce"===e.disposition&&t.startsWith(At)&&!Zt.capabilities.cspBlockedURLs.value.includes(t)&&(Zt.capabilities.cspBlockedURLs.value=[...Zt.capabilities.cspBlockedURLs.value,t])}))}async onError(e){try{const{error:t,context:n,customMessage:i,groupingHash:s}=e,r=e.errorType??dt.HANDLEDEXCEPTION,o=((e,t)=>{switch(t){case dt.UNHANDLEDEXCEPTION:{const{error:t}=e;return t||e}case dt.UNHANDLEDREJECTION:return e.reason;case dt.HANDLEDEXCEPTION:default:return e}})(t,r),a=vn(o,this.logger);if(E(a))return;const l=i?`${i} - `:"",u=((e,t)=>{try{const n=dn.parse(e);return pn(e.name,e.message,t,n)}catch{return pn(e.name,e.message,t,[])}})(a,`${n}${de}${l}`),c=ke(a).includes(be);if(!c&&!(e=>{const t=e.stacktrace[0]?.file;if(!t||"string"!=typeof t)return!1;const n=t.substring(t.lastIndexOf("/")+1),i=t.split("/");return i[i.length-2]===It||["rsa"].some((e=>n.startsWith(e)&&n.endsWith(".js")))})(u)&&r!==dt.HANDLEDEXCEPTION)return;if(Zt.reporting.isErrorReportingEnabled.value){if(await Dn(u,Zt,this.httpClient)){const e={severity:"error",unhandled:r!==dt.HANDLEDEXCEPTION,severityReason:{type:r}},t=((e,t,n,i)=>{let s;if("cdn"!==n.context.app.value.installType)return s;if(T(e))if(k(e))s=e;else{const n=vn(e,i);s=T(n)?n.message:t}else s=t;return s})(s,u.message,Zt,this.logger),n=((e,t,n,i)=>{const{context:s,lifecycle:r,session:o,source:a,reporting:l,autoTrack:u}=n,{app:c,locale:d,userAgent:h,timezone:p,screen:v,library:f}=s;return{payloadVersion:"5",notifier:{name:"RudderStack JavaScript SDK",version:c.value.version,url:"__REPOSITORY_URL__"},events:[{exceptions:[g(e)],severity:t.severity,unhandled:t.unhandled,severityReason:t.severityReason,app:{version:c.value.version,releaseStage:$n(),type:c.value.installType},device:Pn(d,h),request:{url:globalThis.location.href.split("?")[0],clientIp:"[NOT COLLECTED]"},breadcrumbs:g(l.breadcrumbs.value),context:e.message,groupingHash:i,metaData:{app:{snippetVersion:f.value.snippetVersion},device:{...v.value,timezone:p.value},...Cn(n)},user:On(a,o,r,u)}]}})(u,e,Zt,t);this.httpClient.getAsyncData({url:Zt.metrics.metricsServiceUrl.value,options:{method:"POST",data:Rn(n,Zt),sendRawData:!0},isRawResponse:!0})}}(r===dt.HANDLEDEXCEPTION||c)&&this.logger.error(u.message)}catch(e){this.logger.error(`${X}${de}Failed to handle the error.`,e)}}leaveBreadcrumb(e){try{Zt.reporting.breadcrumbs.value=[...Zt.reporting.breadcrumbs.value,(t=e,{type:"manual",name:t,timestamp:new Date,metaData:{}})]}catch(e){this.onError({error:e,context:X,customMessage:vt,groupingHash:vt})}var t}}(Sn,ct);const Ln=new class{plugins=[];byName={};cache={};config={throws:!0};constructor(e,t={}){this.config={throws:!0,...t},this.logger=e}register(e,t){if(!e.name){const t=`${Z}${de}Plugin name is missing.`;if(this.config.throws)throw new Error(t);return void this.logger.error(t,e)}if(this.byName[e.name]){const t=((e,t)=>`${e}${de}Plugin "${t}" already exists.`)(Z,e.name);if(this.config.throws)throw new Error(t);return void this.logger.error(t)}this.cache={},this.plugins=this.plugins.slice();let n=this.plugins.length;this.plugins.forEach(((t,i)=>{t.deps?.includes(e.name)&&(n=Math.min(n,i))})),this.plugins.splice(n,0,e),this.byName[e.name]=e,b(e.initialize)&&e.initialize(t)}unregister(e){const t=this.byName[e];if(!t){const t=`${Z}${de}Plugin "${e}" not found.`;if(this.config.throws)throw new Error(t);return void this.logger.error(t)}const n=this.plugins.indexOf(t);if(-1!==n)this.cache={},delete this.byName[e],this.plugins=this.plugins.slice(),this.plugins.splice(n,1);else{const t=((e,t)=>`${e}${de}Plugin "${t}" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.`)(Z,e);if(this.config.throws)throw new Error(t);this.logger.error(t)}}getPlugin(e){return this.byName[e]}getPlugins(e){const t=e??".";return this.cache[t]||(this.cache[t]=this.plugins.filter((e=>{if(e.deps?.some((e=>!this.byName[e]))){const t=e.deps.filter((e=>!this.byName[e]));return this.logger.error(((e,t,n)=>`${e}${de}Plugin "${t}" could not be loaded because some of its dependencies "${n}" do not exist.`)(Z,e.name,t)),!1}return"."===t||((e,t)=>Boolean($(e,t)))(e,t)}))),this.cache[t]}processRawPlugins(e){e(this.plugins),this.cache={}}invoke(e,t=!0,...n){let i=e;if(!i)throw new Error("Failed to invoke plugin because the extension point name is missing.");const s=i.startsWith("!"),r=this.config.throws??i.endsWith("!");if(i=i.replace(/(^!|!$)/g,""),!i)throw new Error("Failed to invoke plugin because the extension point name is invalid.");const o=i.split(".");o.pop();const a=o.join(".");return(t?this.getPlugins(i):[this.getPlugins(i)[0]]).map((e=>{const t=$(e,i);if(!b(t)||s)return t;try{return t.apply($(e,a),n)}catch(t){if(r)throw t;this.logger.error(((e,t,n)=>`${e}${de}Failed to invoke the "${t}" extension point of plugin "${n}".`)(Z,i,e.name),t)}return null}))}invokeSingle(e,...t){return this.invoke(e,!1,...t)[0]}invokeMultiple(e,...t){return this.invoke(e,!0,...t)}}(ct,{throws:!0}),Mn=e=>Boolean("cloud"!==e.config.connectionMode||!0===e.config.useNativeSDKToSend||!0===e.config.useNativeSDK),Bn=e=>e.filter(Mn),xn=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],Un=["Bugsnag","ErrorReporting"],jn={rudderAnalyticsRemotePlugins:{url:()=>Promise.resolve(window.RudderStackGlobals&&window.RudderStackGlobals.app&&window.RudderStackGlobals.app.pluginsCDNPath?`${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js`:"undefined//rsa-plugins.js"),format:"esm",from:"vite"}};function _n(e,t){const n=Object.assign(e,t);for(const e of Object.keys(n))"object"==typeof n[e]&&"object"==typeof t[e]&&(n[e]=_n(n[e],t[e]));return n}const Hn=e=>_n({},(globalThis.__federation_shared__||{}).default||{});function Fn(e,t){if(!e?.default&&t){let t=Object.create(null);return t.default=e,t.__esModule=!0,t}return e}function Gn(e,t){return async function(e){const t=jn[e];return t.inited?t.lib:["esm","systemjs"].includes(t.format)?new Promise(((e,n)=>{("function"==typeof t.url?t.url:()=>Promise.resolve(t.url))().then((i=>{import(i).then((n=>{if(!t.inited){const e=Hn();n.init(e),t.lib=n,t.lib.init(e),t.inited=!0}e(t.lib)})).catch(n)}))})):void 0}(e).then((e=>e.get(t).then((e=>e()))))}const Kn=e=>{const t={};return e.forEach((e=>{if(xn.includes(e)){const n=(e=>{switch(e){case"BeaconQueue":return()=>Gn("rudderAnalyticsRemotePlugins","./BeaconQueue").then((e=>Fn(e,!0)));case"CustomConsentManager":return()=>Gn("rudderAnalyticsRemotePlugins","./CustomConsentManager").then((e=>Fn(e,!0)));case"DeviceModeDestinations":return()=>Gn("rudderAnalyticsRemotePlugins","./DeviceModeDestinations").then((e=>Fn(e,!0)));case"DeviceModeTransformation":return()=>Gn("rudderAnalyticsRemotePlugins","./DeviceModeTransformation").then((e=>Fn(e,!0)));case"ExternalAnonymousId":return()=>Gn("rudderAnalyticsRemotePlugins","./ExternalAnonymousId").then((e=>Fn(e,!0)));case"GoogleLinker":return()=>Gn("rudderAnalyticsRemotePlugins","./GoogleLinker").then((e=>Fn(e,!0)));case"KetchConsentManager":return()=>Gn("rudderAnalyticsRemotePlugins","./KetchConsentManager").then((e=>Fn(e,!0)));case"IubendaConsentManager":return()=>Gn("rudderAnalyticsRemotePlugins","./IubendaConsentManager").then((e=>Fn(e,!0)));case"NativeDestinationQueue":return()=>Gn("rudderAnalyticsRemotePlugins","./NativeDestinationQueue").then((e=>Fn(e,!0)));case"OneTrustConsentManager":return()=>Gn("rudderAnalyticsRemotePlugins","./OneTrustConsentManager").then((e=>Fn(e,!0)));case"StorageEncryption":return()=>Gn("rudderAnalyticsRemotePlugins","./StorageEncryption").then((e=>Fn(e,!0)));case"StorageEncryptionLegacy":return()=>Gn("rudderAnalyticsRemotePlugins","./StorageEncryptionLegacy").then((e=>Fn(e,!0)));case"StorageMigrator":return()=>Gn("rudderAnalyticsRemotePlugins","./StorageMigrator").then((e=>Fn(e,!0)));case"XhrQueue":return()=>Gn("rudderAnalyticsRemotePlugins","./XhrQueue").then((e=>Fn(e,!0)));default:return}})(e);n&&(t[e]=n)}})),t},Vn=e=>Kn?.(e)||{},Qn={};class zn{constructor(e,t,n){this.engine=e,this.errorHandler=t,this.logger=n,this.onError=this.onError.bind(this)}init(){Zt.lifecycle.status.value="pluginsLoading",Ne("pluginsCDNPath",Zt.lifecycle.pluginsCDNPath.value),this.setActivePlugins(),this.registerLocalPlugins(),this.registerRemotePlugins(),this.attachEffects()}attachEffects(){ot((()=>{(0===Zt.plugins.activePlugins.value.length||Zt.plugins.loadedPlugins.value.length+Zt.plugins.failedPlugins.value.length===Zt.plugins.totalPluginsToLoad.value)&&Fe((()=>{Zt.plugins.ready.value=!0,Zt.lifecycle.status.value="pluginsReady"}))}))}getPluginsToLoadBasedOnConfig(){let e=Zt.plugins.pluginsToLoadFromConfig.value;if(!e)return[];e=e.filter((e=>!Un.includes(e)||(this.logger.warn(((e,t)=>`${e}${de}${t} plugin is deprecated. Please exclude it from the load API options.`)(W,e)),!1)));const t=[{configurationStatus:()=>T(Zt.dataPlaneEvents.eventsQueuePluginName.value),configurationStatusStr:"Data plane events delivery is enabled",activePluginName:Zt.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(Lt),shouldAddMissingPlugins:!0},{configurationStatus:()=>Bn(Zt.nativeDestinations.configuredDestinations.value).length>0,configurationStatusStr:"Device mode destinations are connected to the source",supportedPlugins:["DeviceModeDestinations","NativeDestinationQueue"]},{configurationStatus:()=>Bn(Zt.nativeDestinations.configuredDestinations.value).some((e=>e.shouldApplyDeviceModeTransformation)),configurationStatusStr:"Device mode transformations are enabled for at least one destination",supportedPlugins:["DeviceModeTransformation"]},{configurationStatus:()=>T(Zt.consents.activeConsentManagerPluginName.value),configurationStatusStr:"Consent management is enabled",activePluginName:Zt.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(Rt)},{configurationStatus:()=>T(Zt.storage.encryptionPluginName.value),configurationStatusStr:"Storage encryption is enabled",activePluginName:Zt.storage.encryptionPluginName.value,supportedPlugins:Object.values(Nt)},{configurationStatus:()=>Zt.storage.migrate.value,configurationStatusStr:"Storage migration is enabled",supportedPlugins:["StorageMigrator"]}];return t.forEach((t=>{t.configurationStatus()?(e=e.filter(t.activePluginName?e=>!(e!==t.activePluginName&&t.supportedPlugins.includes(e)):e=>T(e)),this.addMissingPlugins(t,false,e)):e=e.filter(void 0!==t.basePlugins?e=>!(t.basePlugins.includes(e)||t.supportedPlugins.includes(e)):e=>!t.supportedPlugins.includes(e))})),[...Object.keys({}),...e]}addMissingPlugins(e,t,n){const i=e.shouldAddMissingPlugins||t;let s;s=e.activePluginName?[...e.basePlugins||[],e.activePluginName]:[...e.supportedPlugins];const r=s.filter((e=>!n.includes(e)));r.length>0&&(i&&n.push(...r),this.logger.warn(((e,t,n,i)=>{const s=1===n.length,r=s?` '${n[0]}' plugin was`:` ['${n.join("', '")}'] plugins were`,o=`${e}${de}${t}, but${r} not configured to load.`;return i?`${o} So, ${s?"the plugin":"those plugins"} will be loaded automatically.`:`${o} Ignore if this was intentional. Otherwise, consider adding ${s?"it":"them"} to the 'plugins' load API option.`})(W,e.configurationStatusStr,r,i)))}setActivePlugins(){const e=this.getPluginsToLoadBasedOnConfig(),t=[...Object.keys(Qn),...xn],n=[],i=[];e.forEach((e=>{t.includes(e)?n.push(e):i.push(e)})),i.length>0&&this.logger.warn(`${W}${de}Ignoring unknown plugins: ${i.join(", ")}.`),Fe((()=>{Zt.plugins.totalPluginsToLoad.value=e.length,Zt.plugins.activePlugins.value=n,Zt.plugins.failedPlugins.value=i}))}registerLocalPlugins(){Object.values(Qn).forEach((e=>{b(e)&&Zt.plugins.activePlugins.value.includes(e().name)&&this.register([e()])}))}registerRemotePlugins(){const e=(t=Zt.plugins.activePlugins.value,{...Vn(t)});var t;Promise.all(Object.keys(e).map((async t=>{await e[t]().then((e=>this.register([e.default()]))).catch((e=>{Zt.plugins.failedPlugins.value=[...Zt.plugins.failedPlugins.value,t],this.onError(e,`Failed to load plugin "${t}"`,e)}))}))).catch((e=>{this.onError(e)}))}invokeMultiple(e,...t){try{return this.engine.invokeMultiple(e,...t)}catch(t){return this.onError(t,e),[]}}invokeSingle(e,...t){try{return this.engine.invokeSingle(e,...t)}catch(t){return this.onError(t,e),null}}register(e){e.forEach((e=>{try{this.engine.register(e,Zt)}catch(t){Zt.plugins.failedPlugins.value=[...Zt.plugins.failedPlugins.value,e.name],this.onError(t,`Failed to register plugin "${e.name}"`)}}))}unregisterLocalPlugins(){Object.values(Qn).forEach((e=>{try{this.engine.unregister(e().name)}catch(t){this.onError(t,`Failed to unregister plugin "${e().name}"`)}}))}onError(e,t,n){this.errorHandler.onError({error:e,context:W,customMessage:t,groupingHash:n})}}const qn="cookieStorage",Wn="localStorage",Jn="sessionStorage",Xn="memoryStorage",Zn="none",Yn={userId:"rl_user_id",userTraits:"rl_trait",anonymousId:"rl_anonymous_id",groupId:"rl_group_id",groupTraits:"rl_group_trait",initialReferrer:"rl_page_init_referrer",initialReferringDomain:"rl_page_init_referring_domain",sessionInfo:"rl_session",authToken:"rl_auth_token"},ei="clientDataInCookie",ti="clientDataInLocalStorage",ni="clientDataInSessionStorage",ii=["userId","userTraits","anonymousId","groupId","groupTraits","initialReferrer","initialReferringDomain","sessionInfo","authToken"],si={[qn]:ei,[Wn]:ti,[Xn]:"clientDataInMemory",[Jn]:ni},ri=(e,t)=>{try{return encodeURIComponent(e)}catch(e){return void t?.error("Failed to encode the cookie data.",e)}},oi=e=>{try{return decodeURIComponent(e)}catch(e){return}},ai=()=>(e=>{const t={},n=e.split(/\s*;\s*/);let i;return n[0]?(n.forEach((e=>{i=e.split("=");const n=i[0]?oi(i[0]):void 0;n&&(t[n]=i[1]?oi(i[1]):void 0)})),t):t})(globalThis.document.cookie),li=function(e,t,n,i){switch(arguments.length){case 4:case 3:case 2:return((e,t,n,i)=>{const s={...n||{}};let r=`${ri(e,i)}=${ri(t,i)}`;I(t)&&(s.maxage=-1),s.maxage&&(s.expires=new Date(+new Date+s.maxage)),s.path&&(r+=`; path=${s.path}`),s.domain&&(r+=`; domain=${s.domain}`),s.expires&&(r+=`; expires=${s.expires.toUTCString()}`),s.samesite&&(r+=`; samesite=${s.samesite}`),s.secure&&(r+="; secure"),globalThis.document.cookie=r})(e,t,n,i);case 1:return e?(e=>ai()[e])(e):ai();default:return ai()}},ui=e=>{const t="function"!=typeof globalThis.URL?(e=>{const t=document.createElement("a");return t.href=e,t.hostname})(e):new URL(e).hostname,n=t?.split(".")??[],i=n[n.length-1],s=[];if(4===n.length&&i&&i===parseInt(i,10).toString())return s;if(n.length<=1)return n[0]&&-1!==n[0].indexOf("localhost")?["localhost"]:s;for(let e=n.length-2;e>=0;e-=1)s.push(n.slice(e).join("."));return s},ci=()=>{const e=`.${(e=>{const t=ui(e);for(let e=0;e1){for(var s={},r=0,a=i.length;r-1&&(n[t[i]]=this.get(t[i]));return n},len:function(){return o.length}};var l=null;function u(t,n){var r=arguments,o=null;if(l||(l=a()),0===r.length)return l.get();if(1===r.length){if("string"==typeof t)return l.get(t);if(e(t))return l.set(t)}if(2===r.length&&"string"==typeof t){if(!n)return l.remove(t);if(n&&"string"==typeof n)return l.set(t,n);n&&i(n)&&(o=null,o=n(t,l.get(t)),u.set(t,o))}if(2===r.length&&s(t)&&i(n))for(var c=0,d=t.length;c!S(globalThis.navigator.userAgentData),yi={URL:()=>!b(globalThis.URL)||!b(globalThis.URLSearchParams),Promise:()=>!b(globalThis.Promise),"Number.isNaN":()=>!b(globalThis.Number.isNaN),"Number.isInteger":()=>!b(globalThis.Number.isInteger),"Array.from":()=>!b(globalThis.Array.from),"Array.prototype.find":()=>!b(globalThis.Array.prototype.find),"Array.prototype.includes":()=>!b(globalThis.Array.prototype.includes),"String.prototype.endsWith":()=>!b(globalThis.String.prototype.endsWith),"String.prototype.startsWith":()=>!b(globalThis.String.prototype.startsWith),"String.prototype.includes":()=>!b(globalThis.String.prototype.includes),"String.prototype.replaceAll":()=>!b(globalThis.String.prototype.replaceAll),"String.fromCodePoint":()=>!b(globalThis.String.fromCodePoint),"Object.entries":()=>!b(globalThis.Object.entries),"Object.values":()=>!b(globalThis.Object.values),"Object.assign":()=>!b(globalThis.Object.assign),"Object.fromEntries":()=>!b(globalThis.Object.fromEntries),"Element.prototype.dataset":()=>!(()=>{const e=globalThis.document.createElement("div");return e.setAttribute("data-a-b","c"),!!e.dataset&&"c"===e.dataset.aB})(),TextEncoder:()=>!b(globalThis.TextEncoder)||!b(globalThis.TextDecoder),requestAnimationFrame:()=>!b(globalThis.requestAnimationFrame)||!b(globalThis.cancelAnimationFrame),CustomEvent:()=>!b(globalThis.CustomEvent),"navigator.sendBeacon":()=>!b(globalThis.navigator.sendBeacon),ArrayBuffer:()=>!b(globalThis.Uint8Array),Set:()=>!b(globalThis.Set),atob:()=>!b(globalThis.atob)},mi=()=>{let e={density:0,width:0,height:0,innerWidth:0,innerHeight:0};return e={width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight},e},bi=e=>{const t=["QuotaExceededError","NS_ERROR_DOM_QUOTA_REACHED"].includes(e.name)||[22,1014].includes(e.code);return e instanceof DOMException&&t},ki=(e=Wn,t,n)=>{let i,s;const r=`${Q}${de}The "${e}" storage type is `;let o,a="unavailable",l=!0;try{switch(e){case Xn:return!0;case qn:i=t,s="test_rudder_cookie";break;case Wn:i=t??globalThis.localStorage,s="test_rudder_ls";break;case Jn:i=t??globalThis.sessionStorage,s="test_rudder_ss";break;default:return!1}if(i&&(i.setItem(s,"true"),i.getItem(s)))return i.removeItem(s),!0;l=!1}catch(e){l=!1,o=e,bi(e)&&(a="full")}return l||n?.warn(`${r}${a}.`,o),!1};const Ii=new class{isSupportAvailable=!0;isEnabled=!0;length=0;constructor(e){this.options={enabled:!0},this.logger=e}configure(e){return this.options=P(this.options,e??{}),this.isSupportAvailable=ki(Wn),this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,t){vi.set(e,t),this.length=vi.len()}getItem(e){const t=vi.get(e);return E(t)?null:t}removeItem(e){vi.remove(e),this.length=vi.len()}clear(){vi.clear(),this.length=0}key(e){return this.keys()[e]??null}keys(){return vi.keys()}}(ct);const Ei=new class{isSupportAvailable=!0;isEnabled=!0;length=0;constructor(e){this.options={enabled:!0},this.logger=e}configure(e){return this.options=P(this.options,e??{}),this.isSupportAvailable=ki(Jn),this.isSupportAvailable&&(this.store=globalThis.sessionStorage),this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,t){this.store&&(this.store.setItem(e,t),this.length=this.store.length)}getItem(e){if(!this.store)return null;const t=this.store.getItem(e);return E(t)?null:t}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(){const e=[];if(!this.store)return e;for(let t=0;t{switch(e){case Wn:return Ii;case Jn:return Ei;case Xn:return di;case qn:return Si;default:return di}},Ai=(e={},t={},n={},i={})=>{var s;(e=>{const t=Si.configure(e);Zt.storage.cookie.value={maxage:t.maxage,path:t.path,domain:t.domain,samesite:t.samesite,expires:t.expires,secure:t.secure}})(e),s=t,Ii.configure(s),(e=>{di.configure(e)})(n),(e=>{Ei.configure(e)})(i)};class wi{constructor(e,t,n){this.id=e.id,this.name=e.name,this.isEncrypted=e.isEncrypted??!1,this.validKeys=e.validKeys??{},this.engine=t,this.noKeyValidation=0===Object.keys(this.validKeys).length,this.noCompoundKey=e.noCompoundKey,this.originalEngine=this.engine,this.errorHandler=e.errorHandler,this.logger=e.logger,this.pluginsManager=n}createValidKey(e){const{name:t,id:n,validKeys:i,noKeyValidation:s,noCompoundKey:r}=this;if(s)return r?e:[t,n,e].join(".");let o;return Object.values(i).forEach((i=>{i===e&&(o=r?e:[t,n,e].join("."))})),o}swapQueueStoreToInMemoryEngine(){const{name:e,id:t,validKeys:n,noCompoundKey:i}=this,s=Ti(Xn);Object.keys(n).forEach((r=>{const o=this.get(n[r]),a=i?r:[e,t,r].join(".");s.setItem(a,o),this.remove(r)})),this.engine=s}set(e,t){const n=this.createValidKey(e);if(n)try{this.engine.setItem(n,this.encrypt(ve(t,!1,[],this.logger)))}catch(n){if(bi(n))this.logger.warn(`${`Store ${this.id}`}${de}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`),this.swapQueueStoreToInMemoryEngine(),this.set(e,t);else{const t=(e=>`Failed to save the value for "${e}" to storage`)(e);this.onError(n,t,t)}}}get(e){const t=this.createValidKey(e);let n;try{return t?(n=this.decrypt(this.engine.getItem(t)),S(n)||""===n?null:JSON.parse(n)):null}catch(t){const n=(e=>`Failed to retrieve or parse data for "${e}" from storage`)(e);return this.onError(t,n,n),null}}remove(e){const t=this.createValidKey(e);t&&this.engine.removeItem(t)}getOriginalEngine(){return this.originalEngine}decrypt(e){return S(e)?null:this.crypto(e,"decrypt")}encrypt(e){return this.crypto(e,"encrypt")}crypto(e,t){const n=!this.isEncrypted||!e||"string"!=typeof e||""===(e=>e.replace(/^\s+|\s+$/gm,""))(e);if(n)return e;const i=`storage.${t}`,s=this.pluginsManager?this.pluginsManager.invokeSingle(i,e):e;return void 0===s?e:s??""}onError(e,t,n){this.errorHandler.onError({error:e,context:`Store ${this.id}`,customMessage:t,groupingHash:n})}}class $i{stores={};isInitialized=!1;constructor(e,t,n){this.errorHandler=t,this.logger=n,this.pluginsManager=e}init(){if(this.isInitialized)return;const e=Zt.loadOptions.value,t={cookieStorageOptions:{samesite:e.sameSiteCookie,secure:e.secureCookie,domain:e.setCookieDomain,sameDomainCookiesOnly:e.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};Ai(R(P(t.cookieStorageOptions??{},Zt.storage.cookie?.value??{})),R(t.localStorageOptions),R(t.inMemoryStorageOptions),R(t.sessionStorageOptions)),this.initClientDataStores(),this.isInitialized=!0}initClientDataStores(){this.initializeStorageState();[Xn,Wn,qn,Jn].forEach((e=>{Ti(e)?.isEnabled&&this.setStore({id:si[e],name:si[e],isEncrypted:!0,noCompoundKey:!0,type:e,errorHandler:this.errorHandler,logger:this.logger})}))}initializeStorageState(){let e=Zt.storage.type.value,t=Zt.loadOptions.value.storage?.entries;const n=Zt.consents.postConsent.value.storage;(T(n?.type)||T(n?.entries))&&(e=n?.type,t=n?.entries);let i=!0,s={};ii.forEach((n=>{const r=n,o=n,a=t?.[r]?.type,l=((e,t)=>{let n;if(e.consents.preConsent.value.enabled)switch(e.consents.preConsent.value.storage?.strategy){case"none":n=Zn;break;case"session":"sessionInfo"!==t&&(n=Zn);break;case"anonymousId":"anonymousId"!==t&&(n=Zn)}return n})(Zt,n),u=l??a??e??ht,c=this.getResolvedStorageTypeForEntry(u,n);c!==Zn&&(i=!1),s={...s,[n]:{type:c,key:Yn[o]}}})),Fe((()=>{Zt.storage.type.value=e,Zt.storage.entries.value=s,Zt.storage.trulyAnonymousTracking.value=i}))}getResolvedStorageTypeForEntry(e,t){let n=e;switch(e){case Wn:Ti(Wn)?.isEnabled||(n=Xn);break;case Jn:Ti(Jn)?.isEnabled||(n=Xn);break;case Xn:case Zn:break;default:n=Ti(qn)?.isEnabled?qn:Ti(Wn)?.isEnabled?Wn:Ti(Jn)?.isEnabled?Jn:Xn}return n!==e&&this.logger.warn(((e,t,n,i)=>`${e}${de}The storage type "${n}" is not available for entry "${t}". The SDK will initialize the entry with "${i}" storage type instead.`)("StoreManager",t,e,n)),n}setStore(e){const t=Ti(e.type);return this.stores[e.id]=new wi(e,t,this.pluginsManager),this.stores[e.id]}getStore(e){return this.stores[e]}}const Ci=e=>{const t=new URL(e),{host:n,protocol:i}=t,s=n.split(".");let r;return r=s.length>2?`${s[s.length-2]}.${s[s.length-1]}`:n,{topDomain:r,protocol:i}},Oi=(e,t)=>`${t?window.location.origin:(e=>{const{topDomain:t,protocol:n}=Ci(e);return`${n}//${t}`})(window.location.href)}/${e.startsWith("/")?e.substring(1):e}`,Pi=e=>e?.endsWith("/")?Pi(e.substring(0,e.length-1)):e,Di=e=>{try{return new URL(e).host}catch(e){return null}},Ri=e=>Di(e)??"",Ni=e=>{const t={};try{const n=new URL(e),i="utm_";n.searchParams.forEach(((e,n)=>{if(n.startsWith(i)){let s=n.substring(i.length);"campaign"===s&&(s="name"),t[s]=e}}))}catch(e){}return t},Li=e=>{if(!k(e))return!1;try{return b(globalThis.URL)&&new URL(e),St.test(e)}catch(e){return!1}},Mi="none",Bi="immediate",xi=e=>D(e)||Array.isArray(e),Ui=(e,t)=>{let{provider:n}=e;const i=n?Rt[n]:void 0;var s;return n&&!i&&(t.error((s=Rt,`${z}${de}The consent manager "${n}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(s)}".`)),n=void 0),{provider:n,consentManagerPluginName:i}},ji=(e,t)=>{let n,i,s=[],r=[],o=!1,a=!0===e?.enabled;D(e)&&a&&(({provider:i,consentManagerPluginName:n}=Ui(e,t)),xi(e.allowedConsentIds)&&(s=e.allowedConsentIds,o=!0),xi(e.deniedConsentIds)&&(r=e.deniedConsentIds,o=!0));const l={allowedConsentIds:s,deniedConsentIds:r};return a=a&&Boolean(n),{provider:i,consentManagerPluginName:n,initialized:o,enabled:a,consentsData:l}},_i=e=>{var t;Zt.reporting.isErrorReportingEnabled.value=(t=e.source.config,!0===t?.statsCollection?.errors?.enabled&&!window.chrome?.runtime?.id),Zt.reporting.isMetricsReportingEnabled.value=(e=>!0===e?.statsCollection?.metrics?.enabled)(e.source.config)},Hi=e=>{const{useServerSideCookies:t,dataServiceEndpoint:n,storage:i,setCookieDomain:s,sameDomainCookiesOnly:r}=Zt.loadOptions.value;let o,a=i?.cookie,l=!1;if(t){l=t;const i=a.domain??s,u=T(i)&&!(e=>{const{topDomain:t}=Ci(window.location.href);return t===e})(B(i))||r,c=Oi(n??"rsaRequest",u);if(Li(c)){o=Pi(c);const t=Di(window.location.href),n=Di(c);t!==n&&(a={...a,samesite:"None",secure:!0}),!r&&u&&n!==B(i)&&(l=!1,e.warn(((e,t,n)=>`${e}${de}The provided cookie domain (${t}) does not match the current webpage's domain (${n}). Hence, the cookies will be set client-side.`)(z,i,n)))}else l=!1}return{sscEnabled:l,cookieOptions:a,finalDataServiceUrl:o}},Fi=e=>{const{storage:t}=Zt.loadOptions.value;let n=t?.type;T(n)&&!(e=>"string"==typeof e&>.includes(e))(n)&&(e.warn(((e,t,n)=>`${e}${de}The storage type "${t}" is not supported. Please choose one of the following supported types: "${gt}". The default type "${n}" will be used instead.`)(z,n,ht)),n=ht);let i=t?.encryption?.version;const s=i&&Nt[i];var r,o;!E(i)&&E(s)?(e.warn((r=Nt,o=Pt,`${z}${de}The storage encryption version "${i}" is not supported. Please choose one of the following supported versions: "${Object.keys(r)}". The default version "${o}" will be used instead.`)),i=Pt):E(i)&&(i=Pt);const a=t?.migrate,l=a&&i===Pt;!0===a&&l!==a&&e.warn(((e,t,n)=>`${e}${de}The storage data migration has been disabled because the configured storage encryption version (${t}) is not the latest (${n}). To enable storage data migration, please update the storage encryption version to the latest version.`)(z,i,Pt));const{sscEnabled:u,finalDataServiceUrl:c,cookieOptions:d}=Hi(e);Fe((()=>{Zt.storage.type.value=n,Zt.storage.cookie.value=d,Zt.serverCookies.isEnabledServerSideCookies.value=u,Zt.serverCookies.dataServiceUrl.value=c,Zt.storage.encryptionPluginName.value=Nt[i],Zt.storage.migrate.value=l}))},Gi=e=>{const{provider:t,consentManagerPluginName:n,initialized:i,enabled:s,consentsData:r}=ji(Zt.loadOptions.value.consentManagement,e),o=Zt.loadOptions.value.preConsent;let a=o?.storage?.strategy??Mi;var l,u;T(a)&&!["none","session","anonymousId"].includes(a)&&(a=Mi,e.warn((l=z,u=o?.storage?.strategy,`${l}${de}The pre-consent storage strategy "${u}" is not supported. Please choose one of the following supported strategies: "none, session, anonymousId". The default strategy "${Mi}" will be used instead.`)));let c=o?.events?.delivery??Bi;T(c)&&!["immediate","buffer"].includes(c)&&(c=Bi,e.warn(((e,t,n)=>`${e}${de}The pre-consent events delivery type "${t}" is not supported. Please choose one of the following supported types: "immediate, buffer". The default type "${n}" will be used instead.`)(z,o?.events?.delivery,Bi))),Fe((()=>{Zt.consents.activeConsentManagerPluginName.value=n,Zt.consents.initialized.value=i,Zt.consents.enabled.value=s,Zt.consents.data.value=r,Zt.consents.provider.value=t,Zt.consents.preConsent.value={enabled:!0===Zt.loadOptions.value.preConsent?.enabled&&!1===i&&!0===s,storage:{strategy:a},events:{delivery:c}}}))},Ki=e=>{if(Zt.dataPlaneEvents.deliveryEnabled.value){const t="XhrQueue";let n=t;Zt.loadOptions.value.useBeacon&&(Zt.capabilities.isBeaconAvailable.value?n="BeaconQueue":(n=t,e.warn(`${z}${de}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`))),Fe((()=>{Zt.dataPlaneEvents.eventsQueuePluginName.value=n}))}},Vi=(e,t,n,i,s)=>{const r=new URLSearchParams({p:"cdn",v:Te,build:Tt,writeKey:t,lockIntegrationsVersion:n.toString(),lockPluginsVersion:i.toString()});let o=Ot,a=r,l="/sourceConfig/",u="";if(Li(e)){const t=new URL(e);Pi(t.pathname).endsWith("/sourceConfig")||(t.pathname=`${Pi(t.pathname)}/sourceConfig/`),t.pathname=t.pathname.replace(/\/{2,}/g,"/"),r.forEach(((e,n)=>{null===t.searchParams.get(n)&&t.searchParams.set(n,e)})),o=t.origin,l=t.pathname,a=t.searchParams,u=t.hash}else s.warn(((e,t)=>`${e}${de}The provided source config URL "${t}" is invalid. Using the default source config URL instead.`)(z,e));return`${o}${l}?${a}${u}`},Qi=(e,t,n,i,s,r,o)=>{let a;if(r){if(!Li(r))return o.error(`${z}${de}The base URL "${r}" for ${e} is not valid.`),null;a=Pi(r)}else if(a=n,"cdn"===Zt.context.app.value.installType){const e=(()=>{const e=document.querySelector("script[data-rsa-write-key]");if(e&&e.dataset.rsaWriteKey===Zt.lifecycle.writeKey.value)return e.src;const t=document.getElementsByTagName("script"),n=/(?:^|\/)rsa(\.min)?\.js$/;for(const e of t){const t=e.getAttribute("src");if(t&&n.test(t))return t}})();e&&(a=e.split("/").slice(0,-1).concat(t).join("/"))}return s&&(a=a.replace(new RegExp(`/${wt}/${Tt}/${t}$`),`/${i}/${Tt}/${t}`)),a};class zi{constructor(e,t,n){this.errorHandler=t,this.logger=n,this.httpClient=e,this.onError=this.onError.bind(this),this.processConfig=this.processConfig.bind(this)}attachEffects(){ot((()=>{this.logger.setMinLogLevel(Zt.lifecycle.logLevel.value)}))}init(){const{logLevel:e,configUrl:t,lockIntegrationsVersion:n,lockPluginsVersion:i,destSDKBaseURL:s,pluginsSDKBaseURL:r,integrations:o}=Zt.loadOptions.value,a=((e,t,n,i)=>Qi("integrations",It,$t,e,t,n,i))(Te,n,s,this.logger);if(I(a))return;let l;l=((e,t,n,i)=>Qi("plugins",Et,Ct,e,t,n,i))(Te,i,r,this.logger),null!==l&&(this.attachEffects(),Zt.lifecycle.activeDataplaneUrl.value=Pi(Zt.lifecycle.dataPlaneUrl.value),Fi(this.logger),Gi(this.logger),Ki(this.logger),Fe((()=>{Zt.lifecycle.integrationsCDNPath.value=a,Zt.lifecycle.pluginsCDNPath.value=l,e&&(Zt.lifecycle.logLevel.value=e),Zt.lifecycle.sourceConfigUrl.value=Vi(t,Zt.lifecycle.writeKey.value,n,i,this.logger),Zt.metrics.metricsServiceUrl.value=`${Zt.lifecycle.activeDataplaneUrl.value}/rsaMetrics`,Zt.nativeDestinations.loadOnlyIntegrations.value=o})),this.getConfig())}onError(e,t,n){this.errorHandler.onError({error:e,context:z,customMessage:t,groupingHash:n})}processConfig(e,t){if(!T(e))return void(T(t)?this.onError(t.error,ft):this.onError(new Error(ft)));let n;try{n=k(e)?JSON.parse(e):e}catch(e){return void this.onError(e,pt)}if(!(e=>C(e)&&C(e.source)&&!S(e.source.id)&&C(e.source.config)&&Array.isArray(e.source.destinations))(n))return void this.onError(new Error(pt));if(!1===n.source.enabled)return void this.logger.error("The source is disabled. Please enable the source in the dashboard to send events.");_i(n);const i=n.source.destinations.length>0?n.source.destinations.map((e=>({id:e.id,displayName:e.destinationDefinition.displayName,enabled:e.enabled,config:e.config,shouldApplyDeviceModeTransformation:e.shouldApplyDeviceModeTransformation??!1,propagateEventsUntransformedOnError:e.propagateEventsUntransformedOnError??!1,userFriendlyId:`${e.destinationDefinition.displayName.replaceAll(" ","-")}___${e.id}`}))):[];Fe((()=>{Zt.source.value={config:n.source.config,name:n.source.name,id:n.source.id,workspaceId:n.source.workspaceId},Zt.nativeDestinations.configuredDestinations.value=i,Zt.plugins.pluginsToLoadFromConfig.value=Zt.loadOptions.value.plugins??[],(e=>{let t,n=Zt.consents.resolutionStrategy.value;C(e.consentManagementMetadata)&&(Zt.consents.provider.value&&(n=e.consentManagementMetadata.providers.find((e=>e.provider===Zt.consents.provider.value))?.resolutionStrategy??Zt.consents.resolutionStrategy.value),t=e.consentManagementMetadata),"custom"===Zt.consents.provider.value&&(n=void 0),Fe((()=>{Zt.consents.metadata.value=g(t),Zt.consents.resolutionStrategy.value=n}))})(n),Zt.lifecycle.status.value="configured"}))}getConfig(){const e=Zt.loadOptions.value.getSourceConfig;if(e){if(!b(e))return void this.logger.error((t=z,`${t}${de}The "getSourceConfig" load API option must be a function that returns valid source configuration data.`));const n=e();n instanceof Promise?n.then((e=>this.processConfig(e))).catch((e=>{this.onError(e,"SourceConfig")})):this.processConfig(n)}else this.httpClient.getAsyncData({url:Zt.lifecycle.sourceConfigUrl.value,options:{headers:{"Content-Type":void 0}},callback:this.processConfig});var t}}const qi=()=>document?.referrer||"$direct",Wi=()=>{const e=(()=>{const e=document.getElementsByTagName("link");let t="";for(let n=0;e[n];n+=1){const i=e[n];if("canonical"===i.getAttribute("rel")&&!t){t=i.getAttribute("href")??"";break}}return t})();let t=globalThis.location.pathname;const{href:n}=globalThis.location;let i=n;const{search:s}=globalThis.location;if(e)try{const n=new URL(e);i=""===n.search?e+s:e,t=n.pathname}catch(e){}const r=(e=>{let t=e;try{const n=new URL(e);t=n.origin+n.pathname+n.search}catch(e){}return t})(i),{title:o}=document,a=qi();return{path:t,referrer:a,referring_domain:Ri(a),search:s,title:o,url:r,tab_url:n}},Ji=`https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=${Object.keys(yi).join("%2C")}`,Xi="rudderstackPolyfill";class Zi{constructor(e,t,n){this.httpClient=e,this.errorHandler=t,this.logger=n,this.externalSrcLoader=new je(this.logger),this.onError=this.onError.bind(this),this.onReady=this.onReady.bind(this)}init(){this.prepareBrowserCapabilities(),this.attachWindowListeners()}detectBrowserCapabilities(){Fe((()=>{Zt.capabilities.storage.isCookieStorageAvailable.value=ki(qn,Ti(qn),this.logger),Zt.capabilities.storage.isLocalStorageAvailable.value=ki(Wn,void 0,this.logger),Zt.capabilities.storage.isSessionStorageAvailable.value=ki(Jn,void 0,this.logger),Zt.capabilities.isBeaconAvailable.value=!S(globalThis.navigator.sendBeacon)&&b(globalThis.navigator.sendBeacon),Zt.capabilities.isUaCHAvailable.value=fi(),Zt.capabilities.isCryptoAvailable.value=!S(globalThis.crypto)&&b(globalThis.crypto.getRandomValues),Zt.capabilities.isIE11.value=Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./)),Zt.capabilities.isOnline.value=globalThis.navigator.onLine,Zt.context.userAgent.value=(()=>{if(E(globalThis.navigator))return null;let{userAgent:e}=globalThis.navigator;const{brave:t}=globalThis.navigator;if(t&&Object.getPrototypeOf(t).isBrave){const t=e.match(/(chrome)\/([\w.]+)/i);t&&(e=`${e} Brave/${t[2]}`)}return e})(),Zt.context.locale.value=E(globalThis.navigator)?null:globalThis.navigator.language??globalThis.navigator.browserLanguage,Zt.context.screen.value=mi(),Zt.context.timezone.value=(()=>{const e=/([A-Z]+[+-]\d+)/.exec((new Date).toString());return e?.[1]?e[1]:"NA"})(),fi()&&((e,t="none")=>{"none"===t&&e(void 0),"default"===t&&e(navigator.userAgentData),"full"===t&&navigator.userAgentData?.getHighEntropyValues(["architecture","bitness","brands","mobile","model","platform","platformVersion","uaFullVersion","fullVersionList","wow64"]).then((t=>{e(t)})).catch((()=>{e()}))})((e=>{Zt.context["ua-ch"].value=e}),Zt.loadOptions.value.uaChTrackLevel)})),ot((()=>{!0===Zt.loadOptions.value.sendAdblockPage&&void 0!==Zt.lifecycle.sourceConfigUrl.value&&wn(this.httpClient)}))}prepareBrowserCapabilities(){Zt.capabilities.isLegacyDOM.value=(()=>{const e=Object.keys(yi);let t=!1;for(let n=0;n`${e}${de}The provided polyfill URL "${t}" is invalid. The default polyfill URL will be used instead.`)(Q,e)));if(Zt.loadOptions.value.polyfillIfRequired&&Zt.capabilities.isLegacyDOM.value&&Li(t)){const e=t!==Zt.loadOptions.value.polyfillURL;if(e){const e=`RS_polyfillCallback_${Zt.lifecycle.writeKey.value}`,n=()=>{this.onReady(),delete globalThis[e]};globalThis[e]=n,t=`${t}&callback=${e}`}this.externalSrcLoader.loadJSFile({url:t,id:Xi,async:!0,timeout:1e4,callback:n=>{n?e||this.onReady():this.onError(new Error(((e,t)=>`Failed to load the polyfill script with ID "${e}" from URL ${t}.`)(Xi,t)))}})}else this.onReady()}attachWindowListeners(){globalThis.addEventListener("offline",(()=>{Zt.capabilities.isOnline.value=!1})),globalThis.addEventListener("online",(()=>{Zt.capabilities.isOnline.value=!0})),globalThis.addEventListener("resize",function(e,t,n=250){let i;return(...s)=>{globalThis.clearTimeout(i),i=globalThis.setTimeout((()=>{e.apply(t,s)}),n)}}((()=>{Zt.context.screen.value=mi()}),this))}onReady(){this.detectBrowserCapabilities(),Zt.lifecycle.status.value="browserCapabilitiesReady"}onError(e,t){this.errorHandler.onError({error:e,context:Q,groupingHash:t})}}const Yi=["integrations","anonymousId","originalTimestamp"],es=["library","consentManagement","userAgent","ua-ch","screen"],ts=["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"],ns=e=>"number"==typeof e&&!Number.isNaN(e),is=e=>ns(e)&&e>=0&&Number.isInteger(e),ss=e=>{const{cutOff:t}=e,n=Date.now();return Boolean(t?.enabled&&t.expiresAt&&n>t.expiresAt)},rs=e=>Boolean(!e.expiresAt||Date.now()>e.expiresAt)||ss(e),os=(e,t)=>{return!!(e&&is(e)&&(n=10,i=e,i.toString().length>=n))||(t.warn(((e,t,n)=>`${e}${de}The provided session ID (${t}) is either invalid, not a positive integer, or not at least "${n}" digits long. A new session ID will be auto-generated instead.`)(J,e,10)),!1);var n,i},as=(e,t)=>({id:os(e,t)?e:Date.now(),sessionStart:void 0,manualTrack:!0}),ls=e=>Boolean(e===qn||e===Wn||e===Jn||e===Xn),us=()=>ue(),cs=e=>{const t=Wi(),n={};return Object.keys(t).forEach((i=>{n[i]=e?.[i]||t[i]})),n.initial_referrer=e?.initial_referrer||Zt.session.initialReferrer.value,n.initial_referring_domain=e?.initial_referring_domain||Zt.session.initialReferringDomain.value,n},ds=(e,t,n)=>{C(e)&&Object.keys(e).forEach((e=>{(ts.includes(e)||ts.includes(e.toLowerCase()))&&n.warn(((e,t,n,i)=>`${e}${de}The "${t}" property defined under "${n}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${i}).`)(q,e,t,ts))}))},gs=(e,t,n)=>{let i=e;return Object.keys(t).forEach((e=>{if(!Yi.includes(e)&&!es.includes(e))if("context"!==e)i=P(i,{[e]:t[e]});else if(!E(t[e])&&C(t[e])){const n={};Object.keys(t[e]).forEach((i=>{es.includes(i)||(n[i]=t[e][i])})),i=P(i,{...n})}else n.warn(`${q}${de}Please make sure that the "context" property in the event API's "options" argument is a valid object literal with key-value pairs.`)})),i},hs=(e,t,n)=>{C(t)&&(((e,t)=>{t.anonymousId&&k(t.anonymousId)&&(e.anonymousId=t.anonymousId),D(t.integrations)&&(e.integrations=t.integrations),t.originalTimestamp&&k(t.originalTimestamp)&&(e.originalTimestamp=t.originalTimestamp)})(e,t),e.context=gs(e.context,t,n))},ps=(e,t,n,i)=>{const s={channel:"web",context:{traits:g(Zt.session.userTraits.value),sessionId:Zt.session.sessionInfo.value.id||void 0,sessionStart:Zt.session.sessionInfo.value.sessionStart||void 0,...Zt.consents.enabled.value&&{consentManagement:{deniedConsentIds:g(Zt.consents.data.value.deniedConsentIds),allowedConsentIds:g(Zt.consents.data.value.allowedConsentIds),provider:Zt.consents.provider.value,resolutionStrategy:Zt.consents.resolutionStrategy.value}},"ua-ch":Zt.context["ua-ch"].value,app:Zt.context.app.value,library:Zt.context.library.value,userAgent:Zt.context.userAgent.value,os:Zt.context.os.value,locale:Zt.context.locale.value,screen:Zt.context.screen.value,campaign:Ni(globalThis.location.href),page:cs(n),timezone:Zt.context.timezone.value,...Zt.autoTrack.enabled.value&&{autoTrack:{...Zt.autoTrack.pageLifecycle.enabled.value&&{page:{pageViewId:Zt.autoTrack.pageLifecycle.pageViewId.value}}}}},originalTimestamp:ce(new Date),messageId:ue(),userId:e.userId||Zt.session.userId.value};ls(Zt.storage.entries.value.anonymousId?.type)?s.anonymousId=Zt.session.anonymousId.value:s.anonymousId=us(),Zt.storage.trulyAnonymousTracking.value&&(s.context.trulyAnonymousTracking=!0),"identify"===e.type&&(s.context.traits=Zt.storage.entries.value.userTraits?.type!==Zn?g(Zt.session.userTraits.value):e.context.traits),"group"===e.type&&((e.groupId||Zt.session.groupId.value)&&(s.groupId=e.groupId||Zt.session.groupId.value),(e.traits||Zt.session.groupTraits.value)&&(s.traits=Zt.storage.entries.value.groupTraits?.type!==Zn?g(Zt.session.groupTraits.value):e.traits));const r=P(e,s);return void 0===r.event&&(r.event=null),void 0===r.properties&&(r.properties=null),hs(r,t,i),((e,t)=>{const{properties:n,traits:i,context:s}=e,{traits:r}=s;ds(n,"properties",t),ds(i,"traits",t),ds(r,"context.traits",t)})(r,i),r.integrations=(e=>{let t;return t=Zt.loadOptions.value.useGlobalIntegrationsConfigInEvents?Zt.consents.postConsent.value.integrations??Zt.nativeDestinations.loadOnlyIntegrations.value:e||kt,g(t)})(r.integrations),r};class vs{constructor(e){this.logger=e}generatePageEvent(e,t,n,i){let s=n??{};s=((e,t)=>{const n=t?.page||{},i=e,s=Wi();return Object.keys(s).forEach((e=>{E(i[e])&&(i[e]=n[e]||s[e])})),E(i.initial_referrer)&&(i.initial_referrer=n.initial_referrer||Zt.session.initialReferrer.value),E(i.initial_referring_domain)&&(i.initial_referring_domain=n.initial_referring_domain||Zt.session.initialReferringDomain.value),i})(s,i);return ps({properties:s,name:t,category:e,type:"page"},i,s,this.logger)}generateTrackEvent(e,t,n){return ps({properties:t,event:e,type:"track"},n,void 0,this.logger)}generateIdentifyEvent(e,t,n){return ps({userId:e,type:"identify",context:{traits:t}},n,void 0,this.logger)}generateAliasEvent(e,t,n){const i=ps({previousId:t,type:"alias"},n,void 0,this.logger);return i.userId=e??i.userId,i}generateGroupEvent(e,t,n){const i={type:"group"};return e&&(i.groupId=e),t&&(i.traits=t),ps(i,n,void 0,this.logger)}create(e){let t;switch(e.type){case"page":t=this.generatePageEvent(e.category,e.name,e.properties,e.options);break;case"track":t=this.generateTrackEvent(e.name,e.properties,e.options);break;case"identify":t=this.generateIdentifyEvent(e.userId,e.traits,e.options);break;case"alias":t=this.generateAliasEvent(e.to,e.from,e.options);break;default:t=this.generateGroupEvent(e.groupId,e.traits,e.options)}return t}}class fs{constructor(e,t,n,i){this.eventRepository=e,this.userSessionManager=t,this.errorHandler=n,this.logger=i,this.eventFactory=new vs(this.logger)}init(){this.eventRepository.init()}resume(){this.eventRepository.resume()}addEvent(e){this.userSessionManager.refreshSession();const t=this.eventFactory.create(e);this.eventRepository.enqueue(t,e.callback)}}class ys{constructor(e,t,n,i,s){this.storeManager=t,this.pluginsManager=e,this.logger=s,this.errorHandler=i,this.httpClient=n,this.onError=this.onError.bind(this),this.serverSideCookieDebounceFuncs={}}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());const{externalAnonymousIdCookieName:e,anonymousIdOptions:t}=Zt.loadOptions.value;let n;A(e)&&"string"==typeof e&&(n=this.getExternalAnonymousIdByCookieName(e)),this.setAnonymousId(n??this.getAnonymousId(t)),this.setAuthToken(this.getAuthToken()),this.setInitialReferrerInfo(),this.configureSessionTracking()}configureSessionTracking(){let e;if(this.isPersistenceEnabledForStorageEntry("sessionInfo")){const t=this.getConfiguredSessionTrackingInfo(),n=this.getSessionInfo()??Bt.sessionInfo;e={autoTrack:t.autoTrack&&!0!==n.manualTrack,timeout:t.timeout,manualTrack:n.manualTrack,expiresAt:n.expiresAt,id:n.id,sessionStart:n.sessionStart},e.autoTrack||!0===e.manualTrack?!0===t.cutOff?.enabled&&(e.cutOff={enabled:!0,duration:t.cutOff.duration,expiresAt:n.cutOff?.expiresAt}):e=Bt.sessionInfo}else e=Bt.sessionInfo;Zt.session.sessionInfo.value=e,Zt.session.sessionInfo.value.autoTrack&&this.startOrRenewAutoTracking(Zt.session.sessionInfo.value)}setInitialReferrerInfo(){const e=this.getInitialReferrer(),t=this.getInitialReferringDomain();if(e&&t)this.setInitialReferrer(e),this.setInitialReferringDomain(t);else{const t=e||qi();this.setInitialReferrer(t),this.setInitialReferringDomain(Ri(t))}}isPersistenceEnabledForStorageEntry(e){return ls(Zt.storage.entries.value[e]?.type)}migrateDataFromPreviousStorage(){const e=Zt.storage.entries.value,t=[qn,Wn,Jn];Object.keys(e).forEach((n=>{const i=n,s=e[i]?.type,r=this.storeManager?.getStore(si[s]);r&&t.forEach((e=>{const t=this.storeManager?.getStore(si[e]);if(t&&e!==s){const e=t.get(Yn[i]);(e=>A(e)&&""!==e)(e)&&r.set(Yn[i],e),t.remove(Yn[i])}}))}))}migrateStorageIfNeeded(e,t){if(!Zt.storage.migrate.value)return;let n=e??[];if(0===n.length){[ei,ti,ni].forEach((e=>{const t=this.storeManager?.getStore(e);t&&n.push(t)}))}(t??Object.keys(Yn)).forEach((e=>{const t=Yn[e];n.forEach((e=>{const n=this.pluginsManager?.invokeSingle("storage.migrate",t,e.engine,this.errorHandler,this.logger);S(n)||e.set(t,n)}))}))}getConfiguredSessionTrackingInfo(){let e,t=!1!==Zt.loadOptions.value.sessions.autoTrack;if(!t)return{autoTrack:t};const n=Zt.loadOptions.value.sessions?.timeout;is(n)?e=n:(this.logger.warn(((e,t,n)=>`${e}${de}The session timeout value "${t}" is not a number. The default timeout of ${n} ms will be used instead.`)(J,n,De)),e=De),0===e&&(this.logger.warn(`${J}${de}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.`),t=!1),e>0&&e<1e4&&this.logger.warn(((e,t,n)=>`${e}${de}The session timeout value ${t} ms is less than the recommended minimum of ${n} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`)(J,e,1e4));return{timeout:e,autoTrack:t,cutOff:this.getCutOffInfo(e)}}getCutOffInfo(e){const t=Zt.loadOptions.value.sessions.cutOff;let n,i=!1;return!0===t.enabled&&(n=t.duration,i=!0,is(n)?n`${e}${de}The session cut off duration value "${t}" ms is less than the session timeout value "${n}" ms. The cut off functionality will be disabled.`)(J,n,e)),i=!1):(this.logger.warn(((e,t,n)=>`${e}${de}The session cut off duration value "${t}" is not a number. The default cut off duration of ${n} ms will be used instead.`)(J,n,Pe)),n=Pe)),{enabled:i,duration:n}}onError(e,t,n){this.errorHandler.onError({error:e,context:J,customMessage:t,groupingHash:n})}getEncryptedCookieData(e,t){const n=[];return e.forEach((e=>{const i=t?.encrypt(ve(e.value,!1,[],this.logger));A(i)&&n.push({name:e.name,value:i})})),n}makeRequestToSetCookie(e,t){this.httpClient?.getAsyncData({url:Zt.serverCookies.dataServiceUrl.value,options:{method:"POST",data:ve({reqType:"setCookies",workspaceId:Zt.source.value?.workspaceId,data:{options:{maxAge:Zt.storage.cookie.value?.maxage,path:Zt.storage.cookie.value?.path,domain:Zt.storage.cookie.value?.domain,sameSite:Zt.storage.cookie.value?.samesite,secure:Zt.storage.cookie.value?.secure,expires:Zt.storage.cookie.value?.expires},cookies:e}}),sendRawData:!0,withCredentials:!0},isRawResponse:!0,callback:t})}setServerSideCookies(e,t,n){try{const i=this.getEncryptedCookieData(e,n);i.length>0&&this.makeRequestToSetCookie(i,((i,s)=>{var r;200===s?.xhr?.status?e.forEach((e=>{const i=n?.get(e.name),s=ve(e.value,!1,[]);ve(i,!1,[])!==s&&(this.logger.error(`The server failed to set the ${e.name} cookie. As a fallback, the cookies will be set client side.`),t&&t(e.name,e.value))})):(this.logger.error((r=s?.xhr?.status,`The server responded with status ${r} while setting the cookies. As a fallback, the cookies will be set client side.`)),e.forEach((e=>{t&&t(e.name,e.value)})))}))}catch(n){this.onError(n,bt,bt),e.forEach((e=>{t&&t(e.name,e.value)}))}}syncValueToStorage(e,t){const n=Zt.storage.entries.value,i=n[e]?.type;if(ls(i)){const s=this.storeManager?.getStore(si[i]),r=n[e]?.key;t&&(k(t)||D(t))?Zt.serverCookies.isEnabledServerSideCookies.value&&i===qn?(this.serverSideCookieDebounceFuncs[e]&&globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[e]),this.serverSideCookieDebounceFuncs[e]=globalThis.setTimeout((()=>{this.setServerSideCookies([{name:r,value:t}],((e,t)=>{s?.set(e,t)}),s)}),10)):s?.set(r,t):s?.remove(r)}}registerEffects(){ii.forEach((e=>{ot((()=>{this.syncValueToStorage(e,Zt.session[e].value)}))}))}setAnonymousId(e,t){let n=e;if(k(e)&&n||(n=void 0),this.isPersistenceEnabledForStorageEntry("anonymousId")){if(!n&&t){const e=this.pluginsManager?.invokeSingle("userSession.anonymousIdGoogleLinker",t);n=e}n=n||us()}else n=Bt.anonymousId;Zt.session.anonymousId.value=n}getAnonymousId(e){const t=Zt.storage.entries.value.anonymousId?.type;if(ls(t)){let t=Zt.session.anonymousId.value;if(t&&t!==Bt.anonymousId||(t=this.getEntryValue("anonymousId")),!t&&e){const n=this.pluginsManager?.invokeSingle("storage.getAnonymousId",Ti,e);t=n}Zt.session.anonymousId.value=t||us()}return Zt.session.anonymousId.value}getEntryValue(e){const t=Zt.storage.entries.value,n=t[e]?.type;if(ls(n)){const i=this.storeManager?.getStore(si[n]);this.migrateStorageIfNeeded([i],[e]);const s=t[e]?.key;return i?.get(s)??null}return null}getExternalAnonymousIdByCookieName(e){const t=Ti(qn);return t?.isEnabled?t.getItem(e)??null:null}getUserId(){return this.getEntryValue("userId")}getUserTraits(){return this.getEntryValue("userTraits")}getGroupId(){return this.getEntryValue("groupId")}getGroupTraits(){return this.getEntryValue("groupTraits")}getInitialReferrer(){return this.getEntryValue("initialReferrer")}getInitialReferringDomain(){return this.getEntryValue("initialReferringDomain")}getSessionInfo(){return this.getEntryValue("sessionInfo")}getAuthToken(){return this.getEntryValue("authToken")}getSessionId(){const e=this.getSessionInfo()??Bt.sessionInfo;return e.autoTrack&&!rs(e)||e.manualTrack?e.id??null:null}refreshSession(){let e=this.getSessionInfo()??Bt.sessionInfo;(e.autoTrack||e.manualTrack)&&(e.autoTrack&&(this.startOrRenewAutoTracking(e),e=Zt.session.sessionInfo.value),void 0===e.sessionStart?e={...e,sessionStart:!0}:e.sessionStart&&(e={...e,sessionStart:!1})),Zt.session.sessionInfo.value=e,"readyExecuted"!==Zt.lifecycle.status.value&&this.syncValueToStorage("sessionInfo",e)}reset(e,t){const{session:n}=Zt,{manualTrack:i,autoTrack:s,timeout:r,cutOff:o}=n.sessionInfo.value;Fe((()=>{if(n.userId.value=Bt.userId,n.userTraits.value=Bt.userTraits,n.groupId.value=Bt.groupId,n.groupTraits.value=Bt.groupTraits,n.authToken.value=Bt.authToken,!0===e&&this.setAnonymousId(),!t)if(s){const e={...Bt.sessionInfo,timeout:r};o&&(e.cutOff={enabled:o.enabled,duration:o.duration}),n.sessionInfo.value=e,this.startOrRenewAutoTracking(n.sessionInfo.value)}else i&&this.startManualTrackingInternal()}))}setUserId(e){Zt.session.userId.value=this.isPersistenceEnabledForStorageEntry("userId")&&e?e:Bt.userId}setUserTraits(e){Zt.session.userTraits.value=this.isPersistenceEnabledForStorageEntry("userTraits")&&C(e)?P(Zt.session.userTraits.value??Bt.userTraits,e):Bt.userTraits}setGroupId(e){Zt.session.groupId.value=this.isPersistenceEnabledForStorageEntry("groupId")&&e?e:Bt.groupId}setGroupTraits(e){Zt.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry("groupTraits")&&C(e)?P(Zt.session.groupTraits.value??Bt.groupTraits,e):Bt.groupTraits}setInitialReferrer(e){Zt.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry("initialReferrer")&&e?e:Bt.initialReferrer}setInitialReferringDomain(e){Zt.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry("initialReferringDomain")&&e?e:Bt.initialReferringDomain}startOrRenewAutoTracking(e){let t=e;if(rs(e))t=(e=>{const{timeout:t,cutOff:n}=e,i=Date.now();return{id:i,expiresAt:i+t,timeout:t,autoTrack:!0,...n&&{cutOff:n}}})(e);else{const n=Date.now(),i=e.timeout;t.expiresAt=n+i}if(ss(t)&&(t.cutOff.expiresAt=void 0),t.cutOff){const e=(e=>{if(e?.enabled)return e.expiresAt??(is(e.duration)?Date.now()+e.duration:void 0)})(t.cutOff);t.cutOff.expiresAt=e}Zt.session.sessionInfo.value=t}start(e){Zt.session.sessionInfo.value=as(e,this.logger)}startManualTrackingInternal(){this.start(Date.now())}end(){Zt.session.sessionInfo.value=Bt.sessionInfo}setAuthToken(e){Zt.session.authToken.value=this.isPersistenceEnabledForStorageEntry("authToken")&&e?e:Bt.authToken}}const ms=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],bs="dataplaneEventsQueue",ks="destinationsEventsQueue",Is=(e,t)=>{const n=g(e),i=t.nativeDestinations.integrationsConfig.value,s=((e,t)=>Object.keys(e).filter((n=>!0!==e[n]||!t[n])).reduce(((t,n)=>{const i=g(t);return i[n]=e[n],i}),{}))(e.integrations,i);return n.integrations=P(i,s),n},Es=(e,t,n,i)=>{if(T(e))if(b(e))try{e(...t)}catch(e){i.error(`${n}${de}The callback threw an exception`,e)}else i.error(yt(n))};class Ss{constructor(e,t,n,i,s){this.pluginsManager=e,this.errorHandler=i,this.httpClient=n,this.logger=s,this.storeManager=t}init(){this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${bs}.init`,Zt,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.dmtEventsQueue=this.pluginsManager.invokeSingle("transformEvent.init",Zt,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${ks}.init`,Zt,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger),ot((()=>{!0===Zt.nativeDestinations.clientDestinationsReady.value&&(this.destinationsEventsQueue?.start(),this.dmtEventsQueue?.start())}));const e=(e=>e.consents.preConsent.value.enabled&&"buffer"===e.consents.preConsent.value.events?.delivery)(Zt);let t;ot((()=>{const n=!0===Zt.loadOptions.value.bufferDataPlaneEventsUntilReady&&!1===Zt.nativeDestinations.clientDestinationsReady.value;!1!==Zt.nativeDestinations.activeDestinations.value.some((e=>{return t=e,Boolean("hybrid"===t.config.connectionMode||!0===t.config.useNativeSDKToSend);var t}))&&!1!==n||e||!0===this.dataplaneEventsQueue?.scheduleTimeoutActive||(globalThis.clearTimeout(t),this.dataplaneEventsQueue?.start())})),!0===Zt.loadOptions.value.bufferDataPlaneEventsUntilReady&&(t=globalThis.setTimeout((()=>{!0!==this.dataplaneEventsQueue?.scheduleTimeoutActive&&this.dataplaneEventsQueue?.start()}),Zt.loadOptions.value.dataPlaneEventsBufferTimeout))}resume(){!0!==this.dataplaneEventsQueue?.scheduleTimeoutActive&&(Zt.consents.postConsent.value.discardPreConsentEvents&&(this.dataplaneEventsQueue?.clear(),this.destinationsEventsQueue?.clear()),this.dataplaneEventsQueue?.start())}enqueue(e,t){const n=Is(e,Zt);this.pluginsManager.invokeSingle(`${bs}.enqueue`,Zt,this.dataplaneEventsQueue,n,this.errorHandler,this.logger);const i=g(e);this.pluginsManager.invokeSingle(`${ks}.enqueue`,Zt,this.destinationsEventsQueue,i,this.errorHandler,this.logger);const s=`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}${V}`;Es(t,[n],s,this.logger)}}const Ts=e=>{const t=new CustomEvent(e,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:!0,cancelable:!0,composed:!0});globalThis.document.dispatchEvent(t)};class As{constructor(){this.preloadBuffer=new at,this.initialized=!1,this.errorHandler=Nn,this.logger=ct,this.externalSrcLoader=new je(this.logger),this.httpClient=Sn,this.httpClient.init(this.errorHandler),this.capabilitiesManager=new Zi(this.httpClient,this.errorHandler,this.logger)}load(e,t,n={}){Zt.lifecycle.status.value||((e=>k(e)&&e.trim().length>0)(e)?(e=>Li(e))(t)?(Fe((()=>{Zt.lifecycle.writeKey.value=g(e),Zt.lifecycle.dataPlaneUrl.value=g(t),Zt.loadOptions.value=((e,t)=>{const n=g(t);return k(n.setCookieDomain)||(n.setCookieDomain=void 0),["Strict","Lax","None"].includes(n.sameSiteCookie)||(n.sameSiteCookie=void 0),n.secureCookie=M(n.secureCookie,e.secureCookie),n.sameDomainCookiesOnly=M(n.sameDomainCookiesOnly,e.sameDomainCookiesOnly),["none","default","full"].includes(n.uaChTrackLevel)||(n.uaChTrackLevel=void 0),n.integrations=L(n.integrations),Array.isArray(n.plugins)||(n.plugins=ms),n.useGlobalIntegrationsConfigInEvents=M(n.useGlobalIntegrationsConfigInEvents,e.useGlobalIntegrationsConfigInEvents),n.bufferDataPlaneEventsUntilReady=M(n.bufferDataPlaneEventsUntilReady,e.bufferDataPlaneEventsUntilReady),n.sendAdblockPage=M(n.sendAdblockPage,e.sendAdblockPage),n.useServerSideCookies=M(n.useServerSideCookies,e.useServerSideCookies),k(n.dataServiceEndpoint)||(n.dataServiceEndpoint=void 0),n.sendAdblockPageOptions=L(n.sendAdblockPageOptions),n.loadIntegration=M(n.loadIntegration,e.loadIntegration),D(n.storage)?(n.storage.migrate=M(n.storage.migrate,e.storage?.migrate),n.storage.cookie=L(n.storage.cookie),n.storage.encryption=L(n.storage.encryption),n.storage=N(n.storage)):n.storage=void 0,n.destinationsQueueOptions=L(n.destinationsQueueOptions),n.queueOptions=L(n.queueOptions),n.lockIntegrationsVersion=M(n.lockIntegrationsVersion,e.lockIntegrationsVersion),n.lockPluginsVersion=M(n.lockPluginsVersion,e.lockPluginsVersion),ns(n.dataPlaneEventsBufferTimeout)||(n.dataPlaneEventsBufferTimeout=void 0),n.beaconQueueOptions=L(n.beaconQueueOptions),n.preConsent=L(n.preConsent),n.sourceConfigurationOverride=L(n.sourceConfigurationOverride),P(e,N(n))})(Zt.loadOptions.value,n),Zt.lifecycle.status.value="mounted"})),this.logger.setMinLogLevel(Zt.loadOptions.value.logLevel??ut),Ne("state",Zt,e),this.startLifecycle()):this.logger.error(((e,t)=>`${e}${de}The data plane URL "${t}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`)(te,t)):this.logger.error(((e,t)=>`${e}${de}The write key "${t}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`)(te,e)))}startLifecycle(){ot((()=>{try{switch(Zt.lifecycle.status.value){case"mounted":this.onMounted();break;case"browserCapabilitiesReady":this.onBrowserCapabilitiesReady();break;case"configured":this.onConfigured();break;case"pluginsLoading":case"destinationsLoading":case"readyExecuted":default:break;case"pluginsReady":this.onPluginsReady();break;case"initialized":this.onInitialized();break;case"loaded":this.onLoaded();break;case"destinationsReady":this.onDestinationsReady();break;case"ready":this.onReady()}}catch(e){const t="Failed to load the SDK";this.errorHandler.onError({error:e,context:te,customMessage:t,groupingHash:t})}}))}onBrowserCapabilitiesReady(){Be(this),this.prepareInternalServices(),this.loadConfig()}onLoaded(){this.processBufferedEvents(),!0===Zt.consents.preConsent.value.enabled?Zt.lifecycle.status.value="ready":this.loadDestinations()}onMounted(){this.capabilitiesManager.init()}enqueuePreloadBufferEvents(e){Array.isArray(e)&&e.forEach((e=>this.preloadBuffer.enqueue(g(e))))}processDataInPreloadBuffer(){for(;this.preloadBuffer.size()>0;){const e=this.preloadBuffer.dequeue();e&&xe([...e],this)}}prepareInternalServices(){this.pluginsManager=new zn(Ln,this.errorHandler,this.logger),this.storeManager=new $i(this.pluginsManager,this.errorHandler,this.logger),this.configManager=new zi(this.httpClient,this.errorHandler,this.logger),this.userSessionManager=new ys(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventRepository=new Ss(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventManager=new fs(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger)}loadConfig(){Zt.lifecycle.writeKey.value&&this.httpClient.setAuthHeader(Zt.lifecycle.writeKey.value),this.configManager?.init()}onPluginsReady(){this.storeManager?.init(),this.userSessionManager?.init(),Zt.consents.enabled.value&&!Zt.consents.initialized.value&&(this.pluginsManager?.invokeSingle("consentManager.init",Zt,this.logger),!1===Zt.consents.preConsent.value.enabled&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",Zt,this.storeManager,this.logger)),this.eventManager?.init(),Zt.lifecycle.status.value="initialized"}onConfigured(){this.pluginsManager?.init()}onInitialized(){this.processDataInPreloadBuffer();const e=Zt.loadOptions.value.onLoaded;Es(e,[globalThis.rudderanalytics],ee,this.logger),Fe((()=>{Zt.lifecycle.loaded.value=!0,Zt.lifecycle.status.value="loaded"})),this.initialized=!0,Ts("RSA_Initialised")}onReady(){Zt.lifecycle.status.value="readyExecuted",Zt.eventBuffer.readyCallbacksArray.value.forEach((e=>{Es(e,[],Y,this.logger)})),Ts("RSA_Ready")}processBufferedEvents(){let e=Zt.eventBuffer.toBeProcessedArray.value;for(;e.length>0;){const t=e.shift();if(Zt.eventBuffer.toBeProcessedArray.value=e,t){const e=t[0];b(this[e])&&this[e](...t.slice(1),!0)}e=Zt.eventBuffer.toBeProcessedArray.value}}loadDestinations(){if("destinationsLoading"===Zt.lifecycle.status.value||"destinationsReady"===Zt.lifecycle.status.value)return;this.pluginsManager?.invokeSingle("nativeDestinations.setActiveDestinations",Zt,this.pluginsManager,this.errorHandler,this.logger);const e=Zt.nativeDestinations.activeDestinations.value.length;0!==e?(Zt.lifecycle.status.value="destinationsLoading",this.pluginsManager?.invokeSingle("nativeDestinations.load",Zt,this.externalSrcLoader,this.errorHandler,this.logger),ot((()=>{(0===e||Zt.nativeDestinations.initializedDestinations.value.length+Zt.nativeDestinations.failedDestinations.value.length===e)&&Fe((()=>{Zt.lifecycle.status.value="destinationsReady",Zt.nativeDestinations.clientDestinationsReady.value=!0}))}))):Zt.lifecycle.status.value="destinationsReady"}onDestinationsReady(){"ready"!==Zt.lifecycle.status.value&&(Zt.lifecycle.status.value="ready")}ready(e,t=!1){const n="ready";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} invocation`),b(e)?"readyExecuted"===Zt.lifecycle.status.value?Es(e,[],Y,this.logger):Zt.eventBuffer.readyCallbacksArray.value=[...Zt.eventBuffer.readyCallbacksArray.value,e]:this.logger.error(yt(Y))):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]}page(e,t=!1){const n="page";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} event`),Zt.metrics.triggered.value+=1,this.eventManager?.addEvent({type:"page",category:e.category,name:e.name,properties:e.properties,options:e.options,callback:e.callback}),!0===Zt.capabilities.isAdBlocked.value&&e.category!==Ae&&this.page(j(Ae,"ad-block page request",{path:"/ad-blocked"},Zt.loadOptions.value.sendAdblockPageOptions))):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]}track(e,t=!1){const n="track";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} event - ${e.name}`),Zt.metrics.triggered.value+=1,this.eventManager?.addEvent({type:n,name:e.name||void 0,properties:e.properties,options:e.options,callback:e.callback})):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]}identify(e,t=!1){const n="identify";if(!Zt.lifecycle.loaded.value)return void(Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]);this.errorHandler.leaveBreadcrumb(`New ${n} event`),Zt.metrics.triggered.value+=1;Boolean(e.userId&&Zt.session.userId.value&&e.userId!==Zt.session.userId.value)&&this.reset(),I(e.userId)||this.userSessionManager?.setUserId(e.userId),this.userSessionManager?.setUserTraits(e.traits),this.eventManager?.addEvent({type:n,userId:e.userId,traits:e.traits,options:e.options,callback:e.callback})}alias(e,t=!1){const n="alias";if(!Zt.lifecycle.loaded.value)return void(Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]);this.errorHandler.leaveBreadcrumb(`New ${n} event`),Zt.metrics.triggered.value+=1;const i=e.from??(this.getUserId()||this.userSessionManager?.getAnonymousId());this.eventManager?.addEvent({type:n,to:e.to,from:i,options:e.options,callback:e.callback})}group(e,t=!1){const n="group";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} event`),Zt.metrics.triggered.value+=1,I(e.groupId)||this.userSessionManager?.setGroupId(e.groupId),this.userSessionManager?.setGroupTraits(e.traits),this.eventManager?.addEvent({type:n,groupId:e.groupId,traits:e.traits,options:e.options,callback:e.callback})):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]}reset(e,t=!1){const n="reset";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} invocation, resetAnonymousId: ${e}`),this.userSessionManager?.reset(e)):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]}getAnonymousId(e){return this.userSessionManager?.getAnonymousId(e)}setAnonymousId(e,t,n=!1){const i="setAnonymousId";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${i} invocation`),this.userSessionManager?.setAnonymousId(e,t)):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[i,e,t]]}getUserId(){return Zt.session.userId.value}getUserTraits(){return Zt.session.userTraits.value}getGroupId(){return Zt.session.groupId.value}getGroupTraits(){return Zt.session.groupTraits.value}startSession(e,t=!1){const n="startSession";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} invocation`),this.userSessionManager?.start(e)):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[n,e]]}endSession(e=!1){const t="endSession";Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${t} invocation`),this.userSessionManager?.end()):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,[t]]}getSessionId(){const e=this.userSessionManager?.getSessionId();return e??null}consent(e,t=!1){Zt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb("New consent invocation"),Fe((()=>{Zt.consents.preConsent.value={...Zt.consents.preConsent.value,enabled:!1},Zt.consents.postConsent.value=(e=>{const t={sendPageEvent:!1,trackConsent:!1,discardPreConsentEvents:!1};if(C(e)){const n=g(e);t.storage=n.storage,D(n.integrations)&&(t.integrations=n.integrations),t.discardPreConsentEvents=!0===n.discardPreConsentEvents,t.sendPageEvent=!0===n.sendPageEvent,t.trackConsent=!0===n.trackConsent,D(n.consentManagement)&&(t.consentManagement=P(n.consentManagement,{enabled:Zt.consents.enabled.value}))}return t})(e);const{initialized:t,consentsData:n}=ji(Zt.consents.postConsent.value.consentManagement,this.logger);Zt.consents.initialized.value=t,Zt.consents.data.value=n})),Zt.consents.enabled.value&&!Zt.consents.initialized.value&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",Zt,this.storeManager,this.logger),this.storeManager?.initializeStorageState(),this.userSessionManager?.syncStorageDataToState(),this.eventManager?.resume(),this.loadDestinations(),this.sendTrackingEvents(t)):Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,["consent",e]]}sendTrackingEvents(e){if(Zt.consents.postConsent.value.trackConsent){const t=_("Consent Management Interaction");e?Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,["track",t]]:this.track(t)}if(Zt.consents.postConsent.value.sendPageEvent){const t=j();e?Zt.eventBuffer.toBeProcessedArray.value=[...Zt.eventBuffer.toBeProcessedArray.value,["page",t]]:this.page(t)}}setAuthToken(e){this.userSessionManager?.setAuthToken(e)}}class ws{static globalSingleton=null;analyticsInstances={};defaultAnalyticsKey="";logger=(()=>ct)();constructor(){try{if(ws.globalSingleton)return ws.globalSingleton;ws.initializeGlobalResources(),this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this),this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this),this.load=this.load.bind(this),this.ready=this.ready.bind(this),this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this),this.page=this.page.bind(this),this.track=this.track.bind(this),this.identify=this.identify.bind(this),this.alias=this.alias.bind(this),this.group=this.group.bind(this),this.reset=this.reset.bind(this),this.getAnonymousId=this.getAnonymousId.bind(this),this.setAnonymousId=this.setAnonymousId.bind(this),this.getUserId=this.getUserId.bind(this),this.getUserTraits=this.getUserTraits.bind(this),this.getGroupId=this.getGroupId.bind(this),this.getGroupTraits=this.getGroupTraits.bind(this),this.startSession=this.startSession.bind(this),this.endSession=this.endSession.bind(this),this.getSessionId=this.getSessionId.bind(this),this.setAuthToken=this.setAuthToken.bind(this),this.consent=this.consent.bind(this),ws.globalSingleton=this,Zt.autoTrack.pageLifecycle.pageViewId.value=ue(),Zt.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now(),this.triggerBufferedLoadEvent(),globalThis.rudderanalytics=this}catch(e){Ee(e)}}static initializeGlobalResources(){Nn.init(),Si.configure(),Ii.configure(),Ei.configure(),di.configure()}setDefaultInstanceKey(e){k(e)&&e&&(this.defaultAnalyticsKey=e)}getAnalyticsInstance(e){try{let t=e;k(t)&&t||(t=this.defaultAnalyticsKey);return Boolean(this.analyticsInstances[t])||(this.analyticsInstances[t]=new As),this.analyticsInstances[t]}catch(e){return void Ee(e)}}load(e,t,n){try{if(this.analyticsInstances[e])return;this.setDefaultInstanceKey(e),this.trackPageLifecycleEvents(n);const i=Le(we);(e=>{const t="consent",n=e.filter((e=>e[0]===t)),i=e.filter((e=>e[0]!==t));e.splice(0,e.length,...n,...i)})(i),Ne(we,g(i)),this.getAnalyticsInstance(e)?.load(e,t,me(n))}catch(e){Ee(e)}}trackPageLifecycleEvents(e){const{autoTrack:t,useBeacon:n}=e??{},{enabled:i=!1,options:s={},pageLifecycle:r}=t??{},{events:o=[K.UNLOADED],enabled:a=i,options:l=s}=r??{};Zt.autoTrack.pageLifecycle.enabled.value=a,Zt.autoTrack.enabled.value=i||a,a&&this.setupPageUnloadTracking(o,n,l)}setupPageUnloadTracking(e,t,n){(0===e.length||e.includes(K.UNLOADED))&&(!0===t?(e=>{let t=!1,n=!1;function i(){t||(t=!0,e(n),setTimeout((()=>{t=!1}),0))}globalThis.addEventListener("beforeunload",(()=>{n=!1,i()})),globalThis.addEventListener("blur",(()=>{n=!0,i()})),globalThis.addEventListener("focus",(()=>{t=!1})),document.addEventListener("pagehide",(()=>{n="hidden"===document.visibilityState,i()})),document.addEventListener("visibilitychange",(()=>{n=!0,"hidden"===document.visibilityState?i():t=!1}))})((e=>{if(!1===e&&Zt.lifecycle.loaded.value){const e=Date.now(),t=e-Zt.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(K.UNLOADED,{timeOnPage:t},{...n,originalTimestamp:ce(new Date(e))})}})):this.logger.warn(`${"RudderStackAnalytics"}${de}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`))}triggerBufferedLoadEvent(){const e=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[],t=(e=>{let t=[],n=0;for(;n0&&(t.shift(),this.load.apply(null,t))}ready(e){try{this.getAnalyticsInstance()?.ready(me(e))}catch(e){Ee(e)}}page(e,t,n,i,s){try{this.getAnalyticsInstance()?.page(j(me(e),me(t),me(n),me(i),me(s)))}catch(e){Ee(e)}}track(e,t,n,i){try{this.getAnalyticsInstance()?.track(_(me(e),me(t),me(n),me(i)))}catch(e){Ee(e)}}identify(e,t,n,i){try{this.getAnalyticsInstance()?.identify(H(me(e),me(t),me(n),me(i)))}catch(e){Ee(e)}}alias(e,t,n,i){try{this.getAnalyticsInstance()?.alias(F(me(e),me(t),me(n),me(i)))}catch(e){Ee(e)}}group(e,t,n,i){try{this.getAnalyticsInstance()?.group(G(me(e),me(t),me(n),me(i)))}catch(e){Ee(e)}}reset(e){try{this.getAnalyticsInstance()?.reset(me(e))}catch(e){Ee(e)}}getAnonymousId(e){try{return this.getAnalyticsInstance()?.getAnonymousId(me(e))}catch(e){return void Ee(e)}}setAnonymousId(e,t){try{this.getAnalyticsInstance()?.setAnonymousId(me(e),me(t))}catch(e){Ee(e)}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId()}catch(e){return void Ee(e)}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits()}catch(e){return void Ee(e)}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId()}catch(e){return void Ee(e)}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits()}catch(e){return void Ee(e)}}startSession(e){try{this.getAnalyticsInstance()?.startSession(me(e))}catch(e){Ee(e)}}endSession(){try{this.getAnalyticsInstance()?.endSession()}catch(e){Ee(e)}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId()}catch(e){return void Ee(e)}}setAuthToken(e){try{this.getAnalyticsInstance()?.setAuthToken(me(e))}catch(e){Ee(e)}}consent(e){try{this.getAnalyticsInstance()?.consent(me(e))}catch(e){Ee(e)}}}const{setDefaultInstanceKey:$s,getAnalyticsInstance:Cs,load:Os,ready:Ps,page:Ds,track:Rs,identify:Ns,alias:Ls,group:Ms,reset:Bs,getAnonymousId:xs,setAnonymousId:Us,getUserId:js,getUserTraits:_s,getGroupId:Hs,getGroupTraits:Fs,startSession:Gs,endSession:Ks,getSessionId:Vs,consent:Qs,setAuthToken:zs}=new ws;return e.alias=Ls,e.consent=Qs,e.endSession=Ks,e.getAnalyticsInstance=Cs,e.getAnonymousId=xs,e.getGroupId=Hs,e.getGroupTraits=Fs,e.getSessionId=Vs,e.getUserId=js,e.getUserTraits=_s,e.group=Ms,e.identify=Ns,e.load=Os,e.page=Ds,e.ready=Ps,e.reset=Bs,e.setAnonymousId=Us,e.setAuthToken=zs,e.setDefaultInstanceKey=$s,e.startSession=Gs,e.track=Rs,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({}); //# sourceMappingURL=rsa.min.js.map