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,x=e=>e.replace(/^\.+/,""),B=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=B(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=B(s.to)),T(s.from)?s.from=B(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=B(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",J="PluginsManager",W="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)=>`Failed to load 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.19.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},xe=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,[]))},Be=(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)}),(()=>{globalThis.clearTimeout(a),o(new Error(ge(t,e)))}),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)))}}));class je{constructor(e,t,n=1e4){this.errorHandler=e,this.logger=t,this.timeout=n,this.onError=this.onError.bind(this)}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=>{this.onError(e),a||r()}))}onError(e){this.errorHandler.onError(e,"ExternalSrcLoader")}}var _e=Symbol.for("preact-signals");function He(){if(Ve>1)Ve--;else{for(var e,t=!1;void 0!==Ke;){var n=Ke;for(Ke=void 0,Qe++;void 0!==n;){var i=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&Xe(n))try{n.c()}catch(n){t||(e=n,t=!0)}n=i}}if(Qe=0,Ve--,t)throw e}}function Fe(e){if(Ve>0)return e();Ve++;try{return e()}finally{He()}}var Ge=void 0,Ke=void 0,Ve=0,Qe=0,ze=0;function qe(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){this.v=e,this.i=0,this.n=void 0,this.t=void 0}function We(e){return new Je(e)}function Xe(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 Ze(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 Ye(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 et(e){Je.call(this,void 0),this.x=e,this.s=void 0,this.g=ze-1,this.f=4}function tt(e){var t=e.u;if(e.u=void 0,"function"==typeof t){Ve++;var n=Ge;Ge=void 0;try{t()}catch(t){throw e.f&=-2,e.f|=8,nt(e),t}finally{Ge=n,He()}}}function nt(e){for(var t=e.s;void 0!==t;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,tt(e)}function it(e){if(Ge!==this)throw new Error("Out-of-order effect");Ye(this),Ge=e,this.f&=-2,8&this.f&&nt(this),He()}function st(e){this.x=e,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}function rt(e){var t=new st(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){this.t!==e&&void 0===e.e&&(e.x=this.t,void 0!==this.t&&(this.t.e=e),this.t=e)},Je.prototype.U=function(e){if(void 0!==this.t){var t=e.e,n=e.x;void 0!==t&&(t.x=n,e.e=void 0),void 0!==n&&(n.e=t,e.x=void 0),e===this.t&&(this.t=n)}},Je.prototype.subscribe=function(e){var t=this;return rt((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=qe(this);return void 0!==e&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Qe>100)throw new Error("Cycle detected");this.v=e,this.i++,ze++,Ve++;try{for(var t=this.t;void 0!==t;t=t.x)t.t.N()}finally{He()}}}}),(et.prototype=new Je).h=function(){if(this.f&=-3,1&this.f)return!1;if(32==(36&this.f))return!0;if(this.f&=-5,this.g===ze)return!0;if(this.g=ze,this.f|=1,this.i>0&&!Xe(this))return this.f&=-2,!0;var e=Ge;try{Ze(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,Ye(this),this.f&=-2,!0},et.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)},et.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)}},et.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(et.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=qe(this);if(this.h(),void 0!==e&&(e.i=this.i),16&this.f)throw this.v;return this.v}}),st.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()}},st.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,tt(this),Ze(this),Ve++;var e=Ge;return Ge=this,it.bind(this,e)},st.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ke,Ke=this)},st.prototype.d=function(){this.f|=8,1&this.f||nt(this)};class ot{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 at={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5},lt="ERROR";const ut=new class{constructor(e="LOG",t="",n=console){this.minLogLevel=at[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<=at[e]&&this.logProvider[e.toLowerCase()]?.(...this.formatLogData(t))}setScope(e){this.scope=e||this.scope}setMinLogLevel(e){this.minLogLevel=at[e],E(this.minLogLevel)&&(this.minLogLevel=at.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 ct=function(e){return e.HANDLEDEXCEPTION="handledException",e.UNHANDLEDEXCEPTION="unhandledException",e.UNHANDLEDREJECTION="unhandledPromiseRejection",e}({});const dt=["localStorage","memoryStorage","cookieStorage","sessionStorage","none"],gt="cookieStorage",ht="Unable to process/parse source configuration response",pt="Failed to fetch the source config",vt=e=>`${e}${de}The provided callback parameter is not a function.`,ft=(e,t,n)=>`${e} due to timeout or no connection (${t?t.type:""}) at the client side for URL: ${n}`,yt={All:!0},mt="js-integrations",bt="plugins",kt=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_]*)?$"),It="modern",Et="https://cdn.rudderlabs.com",St="v3",Tt=`${Et}/${St}/${It}/${mt}`,At=`${Et}/${St}/${It}/${bt}`,wt="https://api.rudderstack.com",$t="v3",Ct="xhr",Ot={iubenda:"IubendaConsentManager",oneTrust:"OneTrustConsentManager",ketch:"KetchConsentManager",custom:"CustomConsentManager"},Pt={[$t]:"StorageEncryption",legacy:"StorageEncryptionLegacy"},Dt={[Ct]:"XhrQueue",beacon:"BeaconQueue"},Rt=We(g({configUrl:wt,loadIntegration:!0,sessions:{autoTrack:!0,timeout:De,cutOff:{enabled:!1}},sameSiteCookie:"Lax",polyfillIfRequired:!0,integrations:yt,useBeacon:!1,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:!0,lockPluginsVersion:!0,uaChTrackLevel:"none",plugins:[],useGlobalIntegrationsConfigInEvents:!1,bufferDataPlaneEventsUntilReady:!1,dataPlaneEventsBufferTimeout:1e4,storage:{encryption:{version:$t},migrate:!0,cookie:{}},sendAdblockPage:!1,sameDomainCookiesOnly:!1,secureCookie:!1,sendAdblockPageOptions:{},useServerSideCookies:!1})),Nt={userId:"",userTraits:{},anonymousId:"",groupId:"",groupTraits:{},initialReferrer:"",initialReferringDomain:"",sessionInfo:{},authToken:null},Lt={userId:We(Nt.userId),userTraits:We(Nt.userTraits),anonymousId:We(Nt.anonymousId),groupId:We(Nt.groupId),groupTraits:We(Nt.groupTraits),initialReferrer:We(Nt.initialReferrer),initialReferringDomain:We(Nt.initialReferringDomain),sessionInfo:We(Nt.sessionInfo),authToken:We(Nt.authToken)},Mt={isOnline:We(!0),storage:{isLocalStorageAvailable:We(!1),isCookieStorageAvailable:We(!1),isSessionStorageAvailable:We(!1)},isBeaconAvailable:We(!1),isLegacyDOM:We(!1),isUaCHAvailable:We(!1),isCryptoAvailable:We(!1),isIE11:We(!1),isAdBlocked:We(!1)},xt={isErrorReportingEnabled:We(!1),isMetricsReportingEnabled:We(!1),breadcrumbs:We([])},Bt=We(void 0),Ut={activeDataplaneUrl:We(void 0),integrationsCDNPath:We(Tt),pluginsCDNPath:We(At),sourceConfigUrl:We(void 0),status:We(void 0),initialized:We(!1),logLevel:We(lt),loaded:We(!1),readyCallbacks:We([]),writeKey:We(void 0),dataPlaneUrl:We(void 0)},jt={enabled:We(!1),initialized:We(!1),data:We({}),activeConsentManagerPluginName:We(void 0),preConsent:We({enabled:!1}),postConsent:We({}),resolutionStrategy:We("and"),provider:We(void 0),metadata:We(void 0)},_t={retries:We(0),dropped:We(0),sent:We(0),queued:We(0),triggered:We(0),metricsServiceUrl:We(void 0)},Ht={app:We({name:Se,namespace:"com.rudderlabs.javascript",version:Te,installType:"cdn"}),traits:We(null),library:We({name:Se,version:Te,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:We(null),device:We(null),network:We(null),os:We({name:"",version:""}),locale:We(null),screen:We({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),"ua-ch":We(void 0),timezone:We(void 0)},Ft={configuredDestinations:We([]),activeDestinations:We([]),loadOnlyIntegrations:We({}),failedDestinations:We([]),loadIntegration:We(!0),initializedDestinations:We([]),clientDestinationsReady:We(!1),integrationsConfig:We({})},Gt={toBeProcessedArray:We([]),readyCallbacksArray:We([])},Kt={ready:We(!1),loadedPlugins:We([]),failedPlugins:We([]),pluginsToLoadFromConfig:We([]),activePlugins:We([]),totalPluginsToLoad:We(0)},Vt={encryptionPluginName:We(void 0),migrate:We(!1),type:We(void 0),cookie:We(void 0),entries:We({}),trulyAnonymousTracking:We(!1)},Qt={isEnabledServerSideCookies:We(!1),dataServiceUrl:We(void 0)},zt={eventsQueuePluginName:We(void 0),deliveryEnabled:We(!0)},qt={enabled:We(!1),pageLifecycle:{enabled:We(!1),pageViewId:We(void 0),pageLoadedTimestamp:We(void 0)}},Jt={...g({capabilities:Mt,consents:jt,context:Ht,eventBuffer:Gt,lifecycle:Ut,loadOptions:Rt,metrics:_t,nativeDestinations:Ft,plugins:Kt,reporting:xt,session:Lt,source:Bt,storage:Vt,serverCookies:Qt,dataPlaneEvents:zt,autoTrack:qt})};function Wt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Xt,Zt={exports:{}},Yt={exports:{}};function en(){return Xt||(Xt=1,Yt.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 nn({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(on)}),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 nn({functionName:e});var t=/((.*".+"[^@]*)?[^@]*)(?:@)/,n=e.match(t),i=n&&n[1]?n[1]:void 0,s=this.extractLocation(e.replace(t,""));return new nn({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 nn({functionName:r,args:o,fileName:i[0],lineNumber:i[1],columnNumber:i[2],source:e})}),this)}})),Zt.exports);const ln=Wt(an),un="global code",cn=e=>k(e)?e:"";function dn(e,t,n,i){return{errorClass:cn(e),message:`${n}${cn(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)?un:n),lineNumber:e.lineNumber,columnNumber:e.columnNumber};var n;return t.lineNumber&&t.lineNumber>-1&&!t.file&&!t.method&&(t.file=un),t})(t);try{return"{}"===JSON.stringify(n)?e:e.concat(n)}catch{return e}}),[])}}const gn=(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},hn=(e,t)=>{try{return JSON.parse(e||"")}catch(e){t(Ie(e,"Failed to parse response data"))}},pn="The request failed",vn=[/Failed to fetch dynamically imported module: .*/],fn=[/Failed to load the script with the id .*/,/A timeout of \d+ ms occurred while trying to load the script with id .*/],yn=[new RegExp(`${pn}.*`),/A script with the id .* is already loaded\./],mn={headers:{Accept:"application/json","Content-Type":"application/json;charset=UTF-8"},method:"GET"},bn=(e,t,n)=>{const i=P(mn,t||{});return n&&(i.headers=P(i.headers,{Authorization:n})),i.url=e,i},kn=(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(ft(pn,t,e.url)),xhr:o,options:e})};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=pn,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=pn,u=e.url,`${l} for URL: ${u}`)),xhr:o,options:e})}var l,u}));const In=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 kn(bn(t,n,this.basicAuthHeader),i,this.logger);return{data:s?e.response:hn(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);kn(bn(n,i,this.basicAuthHeader),s,this.logger).then((e=>{o||t(r?e.response:hn(e.response,this.onError),e)})).catch((e=>{o||t(void 0,e)}))}onError(e){this.errorHandler?.onError(e,"HttpClient")}setAuthHeader(e,t=!1){const n=t?e:U(`${e}:`);this.basicAuthHeader=`Basic ${n}`}resetAuthHeader(){this.basicAuthHeader=void 0}}(ut),En=["www.test-host.com","localhost","127.0.0.1","[::1]"],Sn=["userId","userTraits","groupId","groupTraits","anonymousId","config","instance","eventBuffer","traits","authToken"],Tn=()=>{const e=globalThis.location.hostname;return!e||e&&En.includes(e)?"development":"production"},An=e=>{const t=ve(e,!1,Sn);return null!==t?JSON.parse(t):{}},wn=(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"}),$n=(e,t)=>({locale:e.value??"NA",userAgent:t.value??"NA",time:new Date}),Cn=(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 On=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(e,X,void 0,ct.UNHANDLEDEXCEPTION)})),globalThis.addEventListener("unhandledrejection",(e=>{this.onError(e,X,void 0,ct.UNHANDLEDREJECTION)}))}onError(e,t="",n="",i=ct.HANDLEDEXCEPTION){try{const s=((e,t)=>{switch(t){case ct.UNHANDLEDEXCEPTION:{const{error:t}=e;return t||e}case ct.UNHANDLEDREJECTION:return e.reason;case ct.HANDLEDEXCEPTION:default:return e}})(e,i),r=gn(s,this.logger);if(E(r))return;const o=n?`${n} - `:"",a=((e,t)=>{try{const n=ln.parse(e);return dn(e.name,e.message,t,n)}catch{return dn(e.name,e.message,t,[])}})(r,`${t}${de}${o}`),l=ke(r).includes(be);if(!l&&!(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]===mt||["rsa"].some((e=>n.startsWith(e)&&n.endsWith(".js")))})(a)&&i!==ct.HANDLEDEXCEPTION)return;if(Jt.reporting.isErrorReportingEnabled.value&&(e=>{const t=e.message;return vn.some((e=>e.test(t)))||fn.some((e=>e.test(t)))?t.includes(Et):!yn.some((e=>e.test(t)))})(a)){const e=((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:Tn(),type:c.value.installType},device:$n(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},...An(n)},user:wn(a,o,r,u)}]}})(a,{severity:"error",unhandled:i!==ct.HANDLEDEXCEPTION,severityReason:{type:i}},Jt);this.httpClient.getAsyncData({url:Jt.metrics.metricsServiceUrl.value,options:{method:"POST",data:Cn(e,Jt),sendRawData:!0},isRawResponse:!0})}(i===ct.HANDLEDEXCEPTION||l)&&this.logger.error(a.message)}catch(e){this.logger.error((e=>`${e}${de}Failed to handle the error.`)(X),e)}}leaveBreadcrumb(e){try{Jt.reporting.breadcrumbs.value=[...Jt.reporting.breadcrumbs.value,(t=e,{type:"manual",name:t,timestamp:new Date,metaData:{}})]}catch(e){this.onError(e,`${X}${de}Failed to log breadcrumb.`)}var t}}(In,ut);const Pn=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)}}(ut,{throws:!0}),Dn=e=>Boolean("cloud"!==e.config.connectionMode||!0===e.config.useNativeSDKToSend||!0===e.config.useNativeSDK),Rn=e=>e.filter(Dn),Nn=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],Ln=["Bugsnag","ErrorReporting"],Mn={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 xn(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]=xn(n[e],t[e]));return n}const Bn=e=>xn({},(globalThis.__federation_shared__||{}).default||{});function Un(e,t){if(!e?.default&&t){let t=Object.create(null);return t.default=e,t.__esModule=!0,t}return e}function jn(e,t){return async function(e){const t=Mn[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=Bn();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 _n=e=>{const t={};return e.forEach((e=>{if(Nn.includes(e)){const n=(e=>{switch(e){case"BeaconQueue":return()=>jn("rudderAnalyticsRemotePlugins","./BeaconQueue").then((e=>Un(e,!0)));case"CustomConsentManager":return()=>jn("rudderAnalyticsRemotePlugins","./CustomConsentManager").then((e=>Un(e,!0)));case"DeviceModeDestinations":return()=>jn("rudderAnalyticsRemotePlugins","./DeviceModeDestinations").then((e=>Un(e,!0)));case"DeviceModeTransformation":return()=>jn("rudderAnalyticsRemotePlugins","./DeviceModeTransformation").then((e=>Un(e,!0)));case"ExternalAnonymousId":return()=>jn("rudderAnalyticsRemotePlugins","./ExternalAnonymousId").then((e=>Un(e,!0)));case"GoogleLinker":return()=>jn("rudderAnalyticsRemotePlugins","./GoogleLinker").then((e=>Un(e,!0)));case"KetchConsentManager":return()=>jn("rudderAnalyticsRemotePlugins","./KetchConsentManager").then((e=>Un(e,!0)));case"IubendaConsentManager":return()=>jn("rudderAnalyticsRemotePlugins","./IubendaConsentManager").then((e=>Un(e,!0)));case"NativeDestinationQueue":return()=>jn("rudderAnalyticsRemotePlugins","./NativeDestinationQueue").then((e=>Un(e,!0)));case"OneTrustConsentManager":return()=>jn("rudderAnalyticsRemotePlugins","./OneTrustConsentManager").then((e=>Un(e,!0)));case"StorageEncryption":return()=>jn("rudderAnalyticsRemotePlugins","./StorageEncryption").then((e=>Un(e,!0)));case"StorageEncryptionLegacy":return()=>jn("rudderAnalyticsRemotePlugins","./StorageEncryptionLegacy").then((e=>Un(e,!0)));case"StorageMigrator":return()=>jn("rudderAnalyticsRemotePlugins","./StorageMigrator").then((e=>Un(e,!0)));case"XhrQueue":return()=>jn("rudderAnalyticsRemotePlugins","./XhrQueue").then((e=>Un(e,!0)));default:return}})(e);n&&(t[e]=n)}})),t},Hn=e=>_n?.(e)||{},Fn={};class Gn{constructor(e,t,n){this.engine=e,this.errorHandler=t,this.logger=n,this.onError=this.onError.bind(this)}init(){Jt.lifecycle.status.value="pluginsLoading",Ne("pluginsCDNPath",Jt.lifecycle.pluginsCDNPath.value),this.setActivePlugins(),this.registerLocalPlugins(),this.registerRemotePlugins(),this.attachEffects()}attachEffects(){rt((()=>{(0===Jt.plugins.activePlugins.value.length||Jt.plugins.loadedPlugins.value.length+Jt.plugins.failedPlugins.value.length===Jt.plugins.totalPluginsToLoad.value)&&Fe((()=>{Jt.plugins.ready.value=!0,Jt.lifecycle.status.value="pluginsReady"}))}))}getPluginsToLoadBasedOnConfig(){let e=Jt.plugins.pluginsToLoadFromConfig.value;if(!e)return[];e=e.filter((e=>!Ln.includes(e)||(this.logger.warn(((e,t)=>`${e}${de}${t} plugin is deprecated. Please exclude it from the load API options.`)(J,e)),!1)));const t=[{configurationStatus:()=>T(Jt.dataPlaneEvents.eventsQueuePluginName.value),configurationStatusStr:"Data plane events delivery is enabled",activePluginName:Jt.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(Dt),shouldAddMissingPlugins:!0},{configurationStatus:()=>Rn(Jt.nativeDestinations.configuredDestinations.value).length>0,configurationStatusStr:"Device mode destinations are connected to the source",supportedPlugins:["DeviceModeDestinations","NativeDestinationQueue"]},{configurationStatus:()=>Rn(Jt.nativeDestinations.configuredDestinations.value).some((e=>e.shouldApplyDeviceModeTransformation)),configurationStatusStr:"Device mode transformations are enabled for at least one destination",supportedPlugins:["DeviceModeTransformation"]},{configurationStatus:()=>T(Jt.consents.activeConsentManagerPluginName.value),configurationStatusStr:"Consent management is enabled",activePluginName:Jt.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(Ot)},{configurationStatus:()=>T(Jt.storage.encryptionPluginName.value),configurationStatusStr:"Storage encryption is enabled",activePluginName:Jt.storage.encryptionPluginName.value,supportedPlugins:Object.values(Pt)},{configurationStatus:()=>Jt.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.`})(J,e.configurationStatusStr,r,i)))}setActivePlugins(){const e=this.getPluginsToLoadBasedOnConfig(),t=[...Object.keys(Fn),...Nn],n=[],i=[];e.forEach((e=>{t.includes(e)?n.push(e):i.push(e)})),i.length>0&&this.logger.warn(`${J}${de}Ignoring unknown plugins: ${i.join(", ")}.`),Fe((()=>{Jt.plugins.totalPluginsToLoad.value=e.length,Jt.plugins.activePlugins.value=n,Jt.plugins.failedPlugins.value=i}))}registerLocalPlugins(){Object.values(Fn).forEach((e=>{b(e)&&Jt.plugins.activePlugins.value.includes(e().name)&&this.register([e()])}))}registerRemotePlugins(){const e=(t=Jt.plugins.activePlugins.value,{...Hn(t)});var t;Promise.all(Object.keys(e).map((async t=>{await e[t]().then((e=>this.register([e.default()]))).catch((e=>{Jt.plugins.failedPlugins.value=[...Jt.plugins.failedPlugins.value,t],this.onError(e,t)}))}))).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,Jt)}catch(t){Jt.plugins.failedPlugins.value=[...Jt.plugins.failedPlugins.value,e.name],this.onError(t)}}))}unregisterLocalPlugins(){Object.values(Fn).forEach((e=>{try{this.engine.unregister(e().name)}catch(e){this.onError(e)}}))}onError(e,t){this.errorHandler.onError(e,J,t)}}const Kn="cookieStorage",Vn="localStorage",Qn="sessionStorage",zn="memoryStorage",qn="none",Jn={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"},Wn="clientDataInCookie",Xn="clientDataInLocalStorage",Zn="clientDataInSessionStorage",Yn=["userId","userTraits","anonymousId","groupId","groupTraits","initialReferrer","initialReferringDomain","sessionInfo","authToken"],ei={[Kn]:Wn,[Vn]:Xn,[zn]:"clientDataInMemory",[Qn]:Zn},ti=(e,t)=>{try{return encodeURIComponent(e)}catch(e){return void t?.error("Failed to encode the cookie data.",e)}},ni=e=>{try{return decodeURIComponent(e)}catch(e){return}},ii=()=>(e=>{const t={},n=e.split(/\s*;\s*/);let i;return n[0]?(n.forEach((e=>{i=e.split("=");const n=i[0]?ni(i[0]):void 0;n&&(t[n]=i[1]?ni(i[1]):void 0)})),t):t})(globalThis.document.cookie),si=function(e,t,n,i){switch(arguments.length){case 4:case 3:case 2:return((e,t,n,i)=>{const s={...n||{}};let r=`${ti(e,i)}=${ti(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=>ii()[e])(e):ii();default:return ii()}},ri=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},oi=()=>{const e=`.${(e=>{const t=ri(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),hi={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)},pi=()=>{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},vi=e=>{const t=["QuotaExceededError","NS_ERROR_DOM_QUOTA_REACHED"].includes(e.name)||[22,1014].includes(e.code);return e instanceof DOMException&&t},fi=(e=Vn,t,n)=>{let i,s;const r=`${Q}${de}The "${e}" storage type is `;let o,a="unavailable",l=!0;try{switch(e){case zn:return!0;case Kn:i=t,s="test_rudder_cookie";break;case Vn:i=t??globalThis.localStorage,s="test_rudder_ls";break;case Qn: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,vi(e)&&(a="full")}return l||n?.warn(`${r}${a}.`,o),!1};const yi=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=fi(Vn),this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,t){di.set(e,t),this.length=di.len()}getItem(e){const t=di.get(e);return E(t)?null:t}removeItem(e){di.remove(e),this.length=di.len()}clear(){di.clear(),this.length=0}key(e){return this.keys()[e]??null}keys(){return di.keys()}}(ut);const mi=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=fi(Qn),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 Vn:return yi;case Qn:return mi;case zn:return ai;case Kn:return bi;default:return ai}},Ii=(e={},t={},n={},i={})=>{var s;(e=>{const t=bi.configure(e);Jt.storage.cookie.value={maxage:t.maxage,path:t.path,domain:t.domain,samesite:t.samesite,expires:t.expires,secure:t.secure}})(e),s=t,yi.configure(s),(e=>{ai.configure(e)})(n),(e=>{mi.configure(e)})(i)};class Ei{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=ki(zn);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){vi(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)):this.onError(Ie(n,(e=>`Failed to save the value for "${e}" to storage`)(e)))}}get(e){const t=this.createValidKey(e);let n;try{return t?(n=this.decrypt(this.engine.getItem(t)),S(n)?null:JSON.parse(n)):null}catch(t){return this.onError(new Error(`${(e=>`Failed to retrieve or parse data for "${e}" from storage`)(e)}: ${t.message}`)),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){this.errorHandler.onError(e,`Store ${this.id}`)}}class Si{stores={};isInitialized=!1;constructor(e,t,n){this.errorHandler=t,this.logger=n,this.pluginsManager=e}init(){if(this.isInitialized)return;const e=Jt.loadOptions.value,t={cookieStorageOptions:{samesite:e.sameSiteCookie,secure:e.secureCookie,domain:e.setCookieDomain,sameDomainCookiesOnly:e.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};Ii(R(P(t.cookieStorageOptions??{},Jt.storage.cookie?.value??{})),R(t.localStorageOptions),R(t.inMemoryStorageOptions),R(t.sessionStorageOptions)),this.initClientDataStores(),this.isInitialized=!0}initClientDataStores(){this.initializeStorageState();[zn,Vn,Kn,Qn].forEach((e=>{ki(e)?.isEnabled&&this.setStore({id:ei[e],name:ei[e],isEncrypted:!0,noCompoundKey:!0,type:e,errorHandler:this.errorHandler,logger:this.logger})}))}initializeStorageState(){let e=Jt.storage.type.value,t=Jt.loadOptions.value.storage?.entries;const n=Jt.consents.postConsent.value.storage;(T(n?.type)||T(n?.entries))&&(e=n?.type,t=n?.entries);let i=!0,s={};Yn.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=qn;break;case"session":"sessionInfo"!==t&&(n=qn);break;case"anonymousId":"anonymousId"!==t&&(n=qn)}return n})(Jt,n),u=l??a??e??gt,c=this.getResolvedStorageTypeForEntry(u,n);c!==qn&&(i=!1),s={...s,[n]:{type:c,key:Jn[o]}}})),Fe((()=>{Jt.storage.type.value=e,Jt.storage.entries.value=s,Jt.storage.trulyAnonymousTracking.value=i}))}getResolvedStorageTypeForEntry(e,t){let n=e;switch(e){case Vn:ki(Vn)?.isEnabled||(n=zn);break;case Qn:ki(Qn)?.isEnabled||(n=zn);break;case zn:case qn:break;default:n=ki(Kn)?.isEnabled?Kn:ki(Vn)?.isEnabled?Vn:ki(Qn)?.isEnabled?Qn:zn}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=ki(e.type);return this.stores[e.id]=new Ei(e,t,this.pluginsManager),this.stores[e.id]}getStore(e){return this.stores[e]}}const Ti=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}},Ai=(e,t)=>`${t?window.location.origin:(e=>{const{topDomain:t,protocol:n}=Ti(e);return`${n}//${t}`})(window.location.href)}/${e.startsWith("/")?e.substring(1):e}`,wi=e=>e?.endsWith("/")?wi(e.substring(0,e.length-1)):e,$i=e=>{try{return new URL(e).host}catch(e){return null}},Ci=e=>$i(e)??"",Oi=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},Pi=e=>{if(!k(e))return!1;try{return b(globalThis.URL)&&new URL(e),kt.test(e)}catch(e){return!1}},Di="none",Ri="immediate",Ni=e=>D(e)||Array.isArray(e),Li=(e,t)=>{let{provider:n}=e;const i=n?Ot[n]:void 0;var s;return n&&!i&&(t.error((s=Ot,`${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}},Mi=(e,t)=>{let n,i,s=[],r=[],o=!1,a=!0===e?.enabled;D(e)&&a&&(({provider:i,consentManagerPluginName:n}=Li(e,t)),Ni(e.allowedConsentIds)&&(s=e.allowedConsentIds,o=!0),Ni(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}},xi=e=>{var t;Jt.reporting.isErrorReportingEnabled.value=(t=e.source.config,!0===t?.statsCollection?.errors?.enabled&&!window.chrome?.runtime?.id),Jt.reporting.isMetricsReportingEnabled.value=(e=>!0===e?.statsCollection?.metrics?.enabled)(e.source.config)},Bi=e=>{const{useServerSideCookies:t,dataServiceEndpoint:n,storage:i,setCookieDomain:s,sameDomainCookiesOnly:r}=Jt.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}=Ti(window.location.href);return t===e})(x(i))||r,c=Ai(n??"rsaRequest",u);if(Pi(c)){o=wi(c);const t=$i(window.location.href),n=$i(c);t!==n&&(a={...a,samesite:"None",secure:!0}),!r&&u&&n!==x(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}},Ui=e=>{const{storage:t}=Jt.loadOptions.value;let n=t?.type;T(n)&&!(e=>"string"==typeof e&&dt.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: "${dt}". The default type "${n}" will be used instead.`)(z,n,gt)),n=gt);let i=t?.encryption?.version;const s=i&&Pt[i];var r,o;!E(i)&&E(s)?(e.warn((r=Pt,o=$t,`${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=$t):E(i)&&(i=$t);const a=t?.migrate,l=a&&i===$t;!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,$t));const{sscEnabled:u,finalDataServiceUrl:c,cookieOptions:d}=Bi(e);Fe((()=>{Jt.storage.type.value=n,Jt.storage.cookie.value=d,Jt.serverCookies.isEnabledServerSideCookies.value=u,Jt.serverCookies.dataServiceUrl.value=c,Jt.storage.encryptionPluginName.value=Pt[i],Jt.storage.migrate.value=l}))},ji=e=>{const{provider:t,consentManagerPluginName:n,initialized:i,enabled:s,consentsData:r}=Mi(Jt.loadOptions.value.consentManagement,e),o=Jt.loadOptions.value.preConsent;let a=o?.storage?.strategy??Di;var l,u;T(a)&&!["none","session","anonymousId"].includes(a)&&(a=Di,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 "${Di}" will be used instead.`)));let c=o?.events?.delivery??Ri;T(c)&&!["immediate","buffer"].includes(c)&&(c=Ri,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,Ri))),Fe((()=>{Jt.consents.activeConsentManagerPluginName.value=n,Jt.consents.initialized.value=i,Jt.consents.enabled.value=s,Jt.consents.data.value=r,Jt.consents.provider.value=t,Jt.consents.preConsent.value={enabled:!0===Jt.loadOptions.value.preConsent?.enabled&&!1===i&&!0===s,storage:{strategy:a},events:{delivery:c}}}))},_i=e=>{if(Jt.dataPlaneEvents.deliveryEnabled.value){const t="XhrQueue";let n=t;Jt.loadOptions.value.useBeacon&&(Jt.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((()=>{Jt.dataPlaneEvents.eventsQueuePluginName.value=n}))}},Hi=(e,t,n,i,s)=>{const r=new URLSearchParams({p:"cdn",v:Te,build:It,writeKey:t,lockIntegrationsVersion:n.toString(),lockPluginsVersion:i.toString()});let o=wt,a=r,l="/sourceConfig/",u="";if(Pi(e)){const t=new URL(e);wi(t.pathname).endsWith("/sourceConfig")||(t.pathname=`${wi(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}`},Fi=(e,t,n,i,s,r,o)=>{let a;if(r){if(!Pi(r))return o.error(`${z}${de}The base URL "${r}" for ${e} is not valid.`),null;a=wi(r)}else if(a=n,"cdn"===Jt.context.app.value.installType){const e=(()=>{const e=document.querySelector("script[data-rsa-write-key]");if(e&&e.dataset.rsaWriteKey===Jt.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(`/${St}/${It}/${t}$`),`/${i}/${It}/${t}`)),a};class Gi{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(){rt((()=>{this.logger.setMinLogLevel(Jt.lifecycle.logLevel.value)}))}init(){const{logLevel:e,configUrl:t,lockIntegrationsVersion:n,lockPluginsVersion:i,destSDKBaseURL:s,pluginsSDKBaseURL:r,integrations:o}=Jt.loadOptions.value,a=((e,t,n,i)=>Fi("integrations",mt,Tt,e,t,n,i))(Te,n,s,this.logger);if(I(a))return;let l;l=((e,t,n,i)=>Fi("plugins",bt,At,e,t,n,i))(Te,i,r,this.logger),null!==l&&(this.attachEffects(),Jt.lifecycle.activeDataplaneUrl.value=wi(Jt.lifecycle.dataPlaneUrl.value),Ui(this.logger),ji(this.logger),_i(this.logger),Fe((()=>{Jt.lifecycle.integrationsCDNPath.value=a,Jt.lifecycle.pluginsCDNPath.value=l,e&&(Jt.lifecycle.logLevel.value=e),Jt.lifecycle.sourceConfigUrl.value=Hi(t,Jt.lifecycle.writeKey.value,n,i,this.logger),Jt.metrics.metricsServiceUrl.value=`${Jt.lifecycle.activeDataplaneUrl.value}/rsaMetrics`,Jt.nativeDestinations.loadOnlyIntegrations.value=o})),this.getConfig())}onError(e,t){this.errorHandler.onError(e,z,t)}processConfig(e,t){if(!T(e))return void(T(t)?this.onError(t.error,pt):this.onError(new Error(pt)));let n;try{n=k(e)?JSON.parse(e):e}catch(e){return void this.onError(e,ht)}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(ht));if(!1===n.source.enabled)return void this.logger.error("The source is disabled. Please enable the source in the dashboard to send events.");xi(n);const i=n.source.destinations.length>0?(e=>{const t=[];return e.forEach((e=>{e.enabled&&!e.deleted&&t.push({id:e.id,displayName:e.destinationDefinition.displayName,config:e.config,shouldApplyDeviceModeTransformation:e.shouldApplyDeviceModeTransformation||!1,propagateEventsUntransformedOnError:e.propagateEventsUntransformedOnError||!1,userFriendlyId:`${e.destinationDefinition.displayName.replaceAll(" ","-")}___${e.id}`})})),t})(n.source.destinations):[];Fe((()=>{Jt.source.value={config:n.source.config,name:n.source.name,id:n.source.id,workspaceId:n.source.workspaceId},Jt.nativeDestinations.configuredDestinations.value=i,Jt.plugins.pluginsToLoadFromConfig.value=Jt.loadOptions.value.plugins??[],(e=>{let t,n=Jt.consents.resolutionStrategy.value;C(e.consentManagementMetadata)&&(Jt.consents.provider.value&&(n=e.consentManagementMetadata.providers.find((e=>e.provider===Jt.consents.provider.value))?.resolutionStrategy??Jt.consents.resolutionStrategy.value),t=e.consentManagementMetadata),"custom"===Jt.consents.provider.value&&(n=void 0),Fe((()=>{Jt.consents.metadata.value=g(t),Jt.consents.resolutionStrategy.value=n}))})(n),Jt.lifecycle.status.value="configured"}))}getConfig(){const e=Jt.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:Jt.lifecycle.sourceConfigUrl.value,options:{headers:{"Content-Type":void 0}},callback:this.processConfig});var t}}const Ki=()=>document?.referrer||"$direct",Vi=()=>{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=Ki();return{path:t,referrer:a,referring_domain:Ci(a),search:s,title:o,url:r,tab_url:n}},Qi=`https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=${Object.keys(hi).join("%2C")}`,zi="rudderstackPolyfill";class qi{constructor(e,t,n){this.httpClient=e,this.errorHandler=t,this.logger=n,this.externalSrcLoader=new je(this.errorHandler,this.logger),this.onError=this.onError.bind(this),this.onReady=this.onReady.bind(this)}init(){this.prepareBrowserCapabilities(),this.attachWindowListeners()}detectBrowserCapabilities(){Fe((()=>{Jt.capabilities.storage.isCookieStorageAvailable.value=fi(Kn,ki(Kn),this.logger),Jt.capabilities.storage.isLocalStorageAvailable.value=fi(Vn,void 0,this.logger),Jt.capabilities.storage.isSessionStorageAvailable.value=fi(Qn,void 0,this.logger),Jt.capabilities.isBeaconAvailable.value=!S(globalThis.navigator.sendBeacon)&&b(globalThis.navigator.sendBeacon),Jt.capabilities.isUaCHAvailable.value=gi(),Jt.capabilities.isCryptoAvailable.value=!S(globalThis.crypto)&&b(globalThis.crypto.getRandomValues),Jt.capabilities.isIE11.value=Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./)),Jt.capabilities.isOnline.value=globalThis.navigator.onLine,Jt.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})(),Jt.context.locale.value=E(globalThis.navigator)?null:globalThis.navigator.language??globalThis.navigator.browserLanguage,Jt.context.screen.value=pi(),Jt.context.timezone.value=(()=>{const e=/([A-Z]+[+-]\d+)/.exec((new Date).toString());return e?.[1]?e[1]:"NA"})(),gi()&&((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=>{Jt.context["ua-ch"].value=e}),Jt.loadOptions.value.uaChTrackLevel)})),rt((()=>{!0===Jt.loadOptions.value.sendAdblockPage&&void 0!==Jt.lifecycle.sourceConfigUrl.value&&(e=>{const t=new URL(Jt.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)=>{Jt.capabilities.isAdBlocked.value=void 0!==t?.error||t?.xhr?.responseURL!==n}})})(this.httpClient)}))}prepareBrowserCapabilities(){Jt.capabilities.isLegacyDOM.value=(()=>{const e=Object.keys(hi);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(Jt.loadOptions.value.polyfillIfRequired&&Jt.capabilities.isLegacyDOM.value&&Pi(t)){const e=t!==Jt.loadOptions.value.polyfillURL;if(e){const e=`RS_polyfillCallback_${Jt.lifecycle.writeKey.value}`,n=()=>{this.onReady(),delete globalThis[e]};globalThis[e]=n,t=`${t}&callback=${e}`}this.externalSrcLoader.loadJSFile({url:t,id:zi,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}.`)(zi,t)))}})}else this.onReady()}attachWindowListeners(){globalThis.addEventListener("offline",(()=>{Jt.capabilities.isOnline.value=!1})),globalThis.addEventListener("online",(()=>{Jt.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)}}((()=>{Jt.context.screen.value=pi()}),this))}onReady(){this.detectBrowserCapabilities(),Jt.lifecycle.status.value="browserCapabilitiesReady"}onError(e){this.errorHandler.onError(e,Q)}}const Ji=["integrations","anonymousId","originalTimestamp"],Wi=["library","consentManagement","userAgent","ua-ch","screen"],Xi=["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"],Zi=e=>"number"==typeof e&&!Number.isNaN(e),Yi=e=>Zi(e)&&e>=0&&Number.isInteger(e),es=e=>{const{cutOff:t}=e,n=Date.now();return Boolean(t?.enabled&&t.expiresAt&&n>t.expiresAt)},ts=e=>Boolean(!e.expiresAt||Date.now()>e.expiresAt)||es(e),ns=(e,t)=>{return!!(e&&Yi(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.`)(W,e,10)),!1);var n,i},is=(e,t)=>({id:ns(e,t)?e:Date.now(),sessionStart:void 0,manualTrack:!0}),ss=e=>Boolean(e===Kn||e===Vn||e===Qn||e===zn),rs=()=>ue(),os=e=>{const t=Vi(),n={};return Object.keys(t).forEach((i=>{n[i]=e?.[i]||t[i]})),n.initial_referrer=e?.initial_referrer||Jt.session.initialReferrer.value,n.initial_referring_domain=e?.initial_referring_domain||Jt.session.initialReferringDomain.value,n},as=(e,t,n)=>{C(e)&&Object.keys(e).forEach((e=>{(Xi.includes(e)||Xi.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,Xi))}))},ls=(e,t,n)=>{let i=e;return Object.keys(t).forEach((e=>{if(!Ji.includes(e)&&!Wi.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=>{Wi.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},us=(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=ls(e.context,t,n))},cs=(e,t,n,i)=>{const s={channel:"web",context:{traits:g(Jt.session.userTraits.value),sessionId:Jt.session.sessionInfo.value.id||void 0,sessionStart:Jt.session.sessionInfo.value.sessionStart||void 0,...Jt.consents.enabled.value&&{consentManagement:{deniedConsentIds:g(Jt.consents.data.value.deniedConsentIds),allowedConsentIds:g(Jt.consents.data.value.allowedConsentIds),provider:Jt.consents.provider.value,resolutionStrategy:Jt.consents.resolutionStrategy.value}},"ua-ch":Jt.context["ua-ch"].value,app:Jt.context.app.value,library:Jt.context.library.value,userAgent:Jt.context.userAgent.value,os:Jt.context.os.value,locale:Jt.context.locale.value,screen:Jt.context.screen.value,campaign:Oi(globalThis.location.href),page:os(n),timezone:Jt.context.timezone.value,...Jt.autoTrack.enabled.value&&{autoTrack:{...Jt.autoTrack.pageLifecycle.enabled.value&&{page:{pageViewId:Jt.autoTrack.pageLifecycle.pageViewId.value}}}}},originalTimestamp:ce(new Date),messageId:ue(),userId:e.userId||Jt.session.userId.value};ss(Jt.storage.entries.value.anonymousId?.type)?s.anonymousId=Jt.session.anonymousId.value:s.anonymousId=rs(),Jt.storage.trulyAnonymousTracking.value&&(s.context.trulyAnonymousTracking=!0),"identify"===e.type&&(s.context.traits=Jt.storage.entries.value.userTraits?.type!==qn?g(Jt.session.userTraits.value):e.context.traits),"group"===e.type&&((e.groupId||Jt.session.groupId.value)&&(s.groupId=e.groupId||Jt.session.groupId.value),(e.traits||Jt.session.groupTraits.value)&&(s.traits=Jt.storage.entries.value.groupTraits?.type!==qn?g(Jt.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),us(r,t,i),((e,t)=>{const{properties:n,traits:i,context:s}=e,{traits:r}=s;as(n,"properties",t),as(i,"traits",t),as(r,"context.traits",t)})(r,i),r.integrations=(e=>{let t;return t=Jt.loadOptions.value.useGlobalIntegrationsConfigInEvents?Jt.consents.postConsent.value.integrations??Jt.nativeDestinations.loadOnlyIntegrations.value:e||yt,g(t)})(r.integrations),r};class ds{constructor(e){this.logger=e}generatePageEvent(e,t,n,i){let s=n??{};s=((e,t)=>{const n=t?.page||{},i=e,s=Vi();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||Jt.session.initialReferrer.value),E(i.initial_referring_domain)&&(i.initial_referring_domain=n.initial_referring_domain||Jt.session.initialReferringDomain.value),i})(s,i);return cs({properties:s,name:t,category:e,type:"page"},i,s,this.logger)}generateTrackEvent(e,t,n){return cs({properties:t,event:e,type:"track"},n,void 0,this.logger)}generateIdentifyEvent(e,t,n){return cs({userId:e,type:"identify",context:{traits:t}},n,void 0,this.logger)}generateAliasEvent(e,t,n){const i=cs({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),cs(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 gs{constructor(e,t,n,i){this.eventRepository=e,this.userSessionManager=t,this.errorHandler=n,this.logger=i,this.eventFactory=new ds(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 hs{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}=Jt.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()??Nt.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=Nt.sessionInfo}else e=Nt.sessionInfo;Jt.session.sessionInfo.value=e,Jt.session.sessionInfo.value.autoTrack&&this.startOrRenewAutoTracking(Jt.session.sessionInfo.value)}setInitialReferrerInfo(){const e=this.getInitialReferrer(),t=this.getInitialReferringDomain();if(e&&t)this.setInitialReferrer(e),this.setInitialReferringDomain(t);else{const t=e||Ki();this.setInitialReferrer(t),this.setInitialReferringDomain(Ci(t))}}isPersistenceEnabledForStorageEntry(e){return ss(Jt.storage.entries.value[e]?.type)}migrateDataFromPreviousStorage(){const e=Jt.storage.entries.value,t=[Kn,Vn,Qn];Object.keys(e).forEach((n=>{const i=n,s=e[i]?.type,r=this.storeManager?.getStore(ei[s]);r&&t.forEach((e=>{const t=this.storeManager?.getStore(ei[e]);if(t&&e!==s){const e=t.get(Jn[i]);(e=>A(e)&&""!==e)(e)&&r.set(Jn[i],e),t.remove(Jn[i])}}))}))}migrateStorageIfNeeded(e){if(!Jt.storage.migrate.value)return;let t=e??[];if(0===t.length){[Wn,Xn,Zn].forEach((e=>{const n=this.storeManager?.getStore(e);n&&t.push(n)}))}Object.keys(Jn).forEach((e=>{const n=Jn[e];t.forEach((e=>{const t=this.pluginsManager?.invokeSingle("storage.migrate",n,e.engine,this.errorHandler,this.logger);S(t)||e.set(n,t)}))}))}getConfiguredSessionTrackingInfo(){let e,t=!1!==Jt.loadOptions.value.sessions.autoTrack;if(!t)return{autoTrack:t};const n=Jt.loadOptions.value.sessions?.timeout;Yi(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.`)(W,n,De)),e=De),0===e&&(this.logger.warn(`${W}${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.`)(W,e,1e4));return{timeout:e,autoTrack:t,cutOff:this.getCutOffInfo(e)}}getCutOffInfo(e){const t=Jt.loadOptions.value.sessions.cutOff;let n,i=!1;return!0===t.enabled&&(n=t.duration,i=!0,Yi(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.`)(W,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.`)(W,n,Pe)),n=Pe)),{enabled:i,duration:n}}onError(e,t){this.errorHandler.onError(e,W,t)}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:Jt.serverCookies.dataServiceUrl.value,options:{method:"POST",data:ve({reqType:"setCookies",workspaceId:Jt.source.value?.workspaceId,data:{options:{maxAge:Jt.storage.cookie.value?.maxage,path:Jt.storage.cookie.value?.path,domain:Jt.storage.cookie.value?.domain,sameSite:Jt.storage.cookie.value?.samesite,secure:Jt.storage.cookie.value?.secure,expires:Jt.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,"Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side."),e.forEach((e=>{t&&t(e.name,e.value)}))}}syncValueToStorage(e,t){const n=Jt.storage.entries.value,i=n[e]?.type;if(ss(i)){const s=this.storeManager?.getStore(ei[i]),r=n[e]?.key;t&&(k(t)||D(t))?Jt.serverCookies.isEnabledServerSideCookies.value&&i===Kn?(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(){Yn.forEach((e=>{rt((()=>{this.syncValueToStorage(e,Jt.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||rs()}else n=Nt.anonymousId;Jt.session.anonymousId.value=n}getAnonymousId(e){const t=Jt.storage.entries.value.anonymousId?.type;if(ss(t)){let t=Jt.session.anonymousId.value;if(t&&t!==Nt.anonymousId||(t=this.getEntryValue("anonymousId")),!t&&e){const n=this.pluginsManager?.invokeSingle("storage.getAnonymousId",ki,e);t=n}Jt.session.anonymousId.value=t||rs()}return Jt.session.anonymousId.value}getEntryValue(e){const t=Jt.storage.entries.value,n=t[e]?.type;if(ss(n)){const i=this.storeManager?.getStore(ei[n]);this.migrateStorageIfNeeded([i]);const s=t[e]?.key;return i?.get(s)??null}return null}getExternalAnonymousIdByCookieName(e){const t=ki(Kn);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()??Nt.sessionInfo;return e.autoTrack&&!ts(e)||e.manualTrack?e.id??null:null}refreshSession(){let e=this.getSessionInfo()??Nt.sessionInfo;(e.autoTrack||e.manualTrack)&&(e.autoTrack&&(this.startOrRenewAutoTracking(e),e=Jt.session.sessionInfo.value),void 0===e.sessionStart?e={...e,sessionStart:!0}:e.sessionStart&&(e={...e,sessionStart:!1})),Jt.session.sessionInfo.value=e,"readyExecuted"!==Jt.lifecycle.status.value&&this.syncValueToStorage("sessionInfo",e)}reset(e,t){const{session:n}=Jt,{manualTrack:i,autoTrack:s,timeout:r,cutOff:o}=n.sessionInfo.value;Fe((()=>{if(n.userId.value=Nt.userId,n.userTraits.value=Nt.userTraits,n.groupId.value=Nt.groupId,n.groupTraits.value=Nt.groupTraits,n.authToken.value=Nt.authToken,!0===e&&this.setAnonymousId(),!t)if(s){const e={...Nt.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){Jt.session.userId.value=this.isPersistenceEnabledForStorageEntry("userId")&&e?e:Nt.userId}setUserTraits(e){Jt.session.userTraits.value=this.isPersistenceEnabledForStorageEntry("userTraits")&&C(e)?P(Jt.session.userTraits.value??Nt.userTraits,e):Nt.userTraits}setGroupId(e){Jt.session.groupId.value=this.isPersistenceEnabledForStorageEntry("groupId")&&e?e:Nt.groupId}setGroupTraits(e){Jt.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry("groupTraits")&&C(e)?P(Jt.session.groupTraits.value??Nt.groupTraits,e):Nt.groupTraits}setInitialReferrer(e){Jt.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry("initialReferrer")&&e?e:Nt.initialReferrer}setInitialReferringDomain(e){Jt.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry("initialReferringDomain")&&e?e:Nt.initialReferringDomain}startOrRenewAutoTracking(e){let t=e;if(ts(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(es(t)&&(t.cutOff.expiresAt=void 0),t.cutOff){const e=(e=>{if(e?.enabled)return e.expiresAt??(Yi(e.duration)?Date.now()+e.duration:void 0)})(t.cutOff);t.cutOff.expiresAt=e}Jt.session.sessionInfo.value=t}start(e){Jt.session.sessionInfo.value=is(e,this.logger)}startManualTrackingInternal(){this.start(Date.now())}end(){Jt.session.sessionInfo.value=Nt.sessionInfo}setAuthToken(e){Jt.session.authToken.value=this.isPersistenceEnabledForStorageEntry("authToken")&&e?e:Nt.authToken}}const ps=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],vs="dataplaneEventsQueue",fs="destinationsEventsQueue",ys=(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},ms=(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(vt(n))};class bs{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(`${vs}.init`,Jt,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.dmtEventsQueue=this.pluginsManager.invokeSingle("transformEvent.init",Jt,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${fs}.init`,Jt,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger),rt((()=>{!0===Jt.nativeDestinations.clientDestinationsReady.value&&(this.destinationsEventsQueue?.start(),this.dmtEventsQueue?.start())}));const e=(e=>e.consents.preConsent.value.enabled&&"buffer"===e.consents.preConsent.value.events?.delivery)(Jt);let t;rt((()=>{const n=!0===Jt.loadOptions.value.bufferDataPlaneEventsUntilReady&&!1===Jt.nativeDestinations.clientDestinationsReady.value;!1!==Jt.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===Jt.loadOptions.value.bufferDataPlaneEventsUntilReady&&(t=globalThis.setTimeout((()=>{!0!==this.dataplaneEventsQueue?.scheduleTimeoutActive&&this.dataplaneEventsQueue?.start()}),Jt.loadOptions.value.dataPlaneEventsBufferTimeout))}resume(){!0!==this.dataplaneEventsQueue?.scheduleTimeoutActive&&(Jt.consents.postConsent.value.discardPreConsentEvents&&(this.dataplaneEventsQueue?.clear(),this.destinationsEventsQueue?.clear()),this.dataplaneEventsQueue?.start())}enqueue(e,t){const n=ys(e,Jt);this.pluginsManager.invokeSingle(`${vs}.enqueue`,Jt,this.dataplaneEventsQueue,n,this.errorHandler,this.logger);const i=g(e);this.pluginsManager.invokeSingle(`${fs}.enqueue`,Jt,this.destinationsEventsQueue,i,this.errorHandler,this.logger);const s=`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}${V}`;ms(t,[n],s,this.logger)}}const ks=e=>{const t=new CustomEvent(e,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:!0,cancelable:!0,composed:!0});globalThis.document.dispatchEvent(t)};class Is{constructor(){this.preloadBuffer=new ot,this.initialized=!1,this.errorHandler=On,this.logger=ut,this.externalSrcLoader=new je(this.errorHandler,this.logger),this.httpClient=In,this.httpClient.init(this.errorHandler),this.capabilitiesManager=new qi(this.httpClient,this.errorHandler,this.logger)}load(e,t,n={}){Jt.lifecycle.status.value||((e=>k(e)&&e.trim().length>0)(e)?(e=>Pi(e))(t)?(Fe((()=>{Jt.lifecycle.writeKey.value=g(e),Jt.lifecycle.dataPlaneUrl.value=g(t),Jt.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=ps),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),Zi(n.dataPlaneEventsBufferTimeout)||(n.dataPlaneEventsBufferTimeout=void 0),n.beaconQueueOptions=L(n.beaconQueueOptions),n.preConsent=L(n.preConsent),P(e,N(n))})(Jt.loadOptions.value,n),Jt.lifecycle.status.value="mounted"})),this.logger.setMinLogLevel(Jt.loadOptions.value.logLevel??lt),Ne("state",Jt,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(){rt((()=>{try{switch(Jt.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(Ie(e,t),te)}}))}onBrowserCapabilitiesReady(){xe(this),this.prepareInternalServices(),this.loadConfig()}onLoaded(){this.processBufferedEvents(),!0===Jt.consents.preConsent.value.enabled?Jt.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&&Be([...e],this)}}prepareInternalServices(){this.pluginsManager=new Gn(Pn,this.errorHandler,this.logger),this.storeManager=new Si(this.pluginsManager,this.errorHandler,this.logger),this.configManager=new Gi(this.httpClient,this.errorHandler,this.logger),this.userSessionManager=new hs(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventRepository=new bs(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventManager=new gs(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger)}loadConfig(){Jt.lifecycle.writeKey.value&&this.httpClient.setAuthHeader(Jt.lifecycle.writeKey.value),this.configManager?.init()}onPluginsReady(){this.storeManager?.init(),this.userSessionManager?.init(),Jt.consents.enabled.value&&!Jt.consents.initialized.value&&(this.pluginsManager?.invokeSingle("consentManager.init",Jt,this.logger),!1===Jt.consents.preConsent.value.enabled&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",Jt,this.storeManager,this.logger)),this.eventManager?.init(),Jt.lifecycle.status.value="initialized"}onConfigured(){this.pluginsManager?.init()}onInitialized(){this.processDataInPreloadBuffer();const e=Jt.loadOptions.value.onLoaded;ms(e,[globalThis.rudderanalytics],ee,this.logger),Fe((()=>{Jt.lifecycle.loaded.value=!0,Jt.lifecycle.status.value="loaded"})),this.initialized=!0,ks("RSA_Initialised")}onReady(){Jt.lifecycle.status.value="readyExecuted",Jt.eventBuffer.readyCallbacksArray.value.forEach((e=>{ms(e,[],Y,this.logger)})),ks("RSA_Ready")}processBufferedEvents(){let e=Jt.eventBuffer.toBeProcessedArray.value;for(;e.length>0;){const t=e.shift();if(Jt.eventBuffer.toBeProcessedArray.value=e,t){const e=t[0];b(this[e])&&this[e](...t.slice(1),!0)}e=Jt.eventBuffer.toBeProcessedArray.value}}loadDestinations(){if("destinationsLoading"===Jt.lifecycle.status.value||"destinationsReady"===Jt.lifecycle.status.value)return;this.pluginsManager?.invokeSingle("nativeDestinations.setActiveDestinations",Jt,this.pluginsManager,this.errorHandler,this.logger);const e=Jt.nativeDestinations.activeDestinations.value.length;0!==e?(Jt.lifecycle.status.value="destinationsLoading",this.pluginsManager?.invokeSingle("nativeDestinations.load",Jt,this.externalSrcLoader,this.errorHandler,this.logger),rt((()=>{(0===e||Jt.nativeDestinations.initializedDestinations.value.length+Jt.nativeDestinations.failedDestinations.value.length===e)&&Fe((()=>{Jt.lifecycle.status.value="destinationsReady",Jt.nativeDestinations.clientDestinationsReady.value=!0}))}))):Jt.lifecycle.status.value="destinationsReady"}onDestinationsReady(){"ready"!==Jt.lifecycle.status.value&&(Jt.lifecycle.status.value="ready")}ready(e,t=!1){const n="ready";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} invocation`),b(e)?"readyExecuted"===Jt.lifecycle.status.value?ms(e,[],Y,this.logger):Jt.eventBuffer.readyCallbacksArray.value=[...Jt.eventBuffer.readyCallbacksArray.value,e]:this.logger.error(vt(Y))):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]}page(e,t=!1){const n="page";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} event`),Jt.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===Jt.capabilities.isAdBlocked.value&&e.category!==Ae&&this.page(j(Ae,"ad-block page request",{path:"/ad-blocked"},Jt.loadOptions.value.sendAdblockPageOptions))):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]}track(e,t=!1){const n="track";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} event - ${e.name}`),Jt.metrics.triggered.value+=1,this.eventManager?.addEvent({type:n,name:e.name||void 0,properties:e.properties,options:e.options,callback:e.callback})):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]}identify(e,t=!1){const n="identify";if(!Jt.lifecycle.loaded.value)return void(Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]);this.errorHandler.leaveBreadcrumb(`New ${n} event`),Jt.metrics.triggered.value+=1;Boolean(e.userId&&Jt.session.userId.value&&e.userId!==Jt.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(!Jt.lifecycle.loaded.value)return void(Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]);this.errorHandler.leaveBreadcrumb(`New ${n} event`),Jt.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";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} event`),Jt.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})):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]}reset(e,t=!1){const n="reset";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} invocation, resetAnonymousId: ${e}`),this.userSessionManager?.reset(e)):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]}getAnonymousId(e){return this.userSessionManager?.getAnonymousId(e)}setAnonymousId(e,t,n=!1){const i="setAnonymousId";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${i} invocation`),this.userSessionManager?.setAnonymousId(e,t)):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[i,e,t]]}getUserId(){return Jt.session.userId.value}getUserTraits(){return Jt.session.userTraits.value}getGroupId(){return Jt.session.groupId.value}getGroupTraits(){return Jt.session.groupTraits.value}startSession(e,t=!1){const n="startSession";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${n} invocation`),this.userSessionManager?.start(e)):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[n,e]]}endSession(e=!1){const t="endSession";Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb(`New ${t} invocation`),this.userSessionManager?.end()):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,[t]]}getSessionId(){const e=this.userSessionManager?.getSessionId();return e??null}consent(e,t=!1){Jt.lifecycle.loaded.value?(this.errorHandler.leaveBreadcrumb("New consent invocation"),Fe((()=>{Jt.consents.preConsent.value={...Jt.consents.preConsent.value,enabled:!1},Jt.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:Jt.consents.enabled.value}))}return t})(e);const{initialized:t,consentsData:n}=Mi(Jt.consents.postConsent.value.consentManagement,this.logger);Jt.consents.initialized.value=t,Jt.consents.data.value=n})),Jt.consents.enabled.value&&!Jt.consents.initialized.value&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",Jt,this.storeManager,this.logger),this.storeManager?.initializeStorageState(),this.userSessionManager?.syncStorageDataToState(),this.eventManager?.resume(),this.loadDestinations(),this.sendTrackingEvents(t)):Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,["consent",e]]}sendTrackingEvents(e){if(Jt.consents.postConsent.value.trackConsent){const t=_("Consent Management Interaction");e?Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,["track",t]]:this.track(t)}if(Jt.consents.postConsent.value.sendPageEvent){const t=j();e?Jt.eventBuffer.toBeProcessedArray.value=[...Jt.eventBuffer.toBeProcessedArray.value,["page",t]]:this.page(t)}}setAuthToken(e){this.userSessionManager?.setAuthToken(e)}}class Es{static globalSingleton=null;analyticsInstances={};defaultAnalyticsKey="";logger=(()=>ut)();constructor(){try{if(Es.globalSingleton)return Es.globalSingleton;Es.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),Es.globalSingleton=this,Jt.autoTrack.pageLifecycle.pageViewId.value=ue(),Jt.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now(),this.triggerBufferedLoadEvent(),globalThis.rudderanalytics=this}catch(e){Ee(e)}}static initializeGlobalResources(){On.init(),bi.configure(),yi.configure(),mi.configure(),ai.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 Is),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??{};Jt.autoTrack.pageLifecycle.enabled.value=a,Jt.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&&Jt.lifecycle.loaded.value){const e=Date.now(),t=e-Jt.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:Ss,getAnalyticsInstance:Ts,load:As,ready:ws,page:$s,track:Cs,identify:Os,alias:Ps,group:Ds,reset:Rs,getAnonymousId:Ns,setAnonymousId:Ls,getUserId:Ms,getUserTraits:xs,getGroupId:Bs,getGroupTraits:Us,startSession:js,endSession:_s,getSessionId:Hs,consent:Fs,setAuthToken:Gs}=new Es;return e.alias=Ps,e.consent=Fs,e.endSession=_s,e.getAnalyticsInstance=Ts,e.getAnonymousId=Ns,e.getGroupId=Bs,e.getGroupTraits=Us,e.getSessionId=Hs,e.getUserId=Ms,e.getUserTraits=xs,e.group=Ds,e.identify=Os,e.load=As,e.page=$s,e.ready=ws,e.reset=Rs,e.setAnonymousId=Ls,e.setAuthToken=Gs,e.setDefaultInstanceKey=Ss,e.startSession=js,e.track=Cs,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({}); //# sourceMappingURL=rsa.min.js.map