1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,260936,e=>{"use strict";let t=(0,e.i(884109).createContext)(null);e.s(["ComplianceContext",0,t])},43808,e=>{"use strict";var t=e.i(884109),i=e.i(260936);e.s(["useCompliance",0,()=>{let e=(0,t.useContext)(i.ComplianceContext);if(!e)throw Error("useCompliance must be used within a ComplianceProvider");return e}])},583752,e=>{"use strict";var t=e.i(28722),i=e.i(604576),r=e.i(884109),s=e.i(234370),n=e.i(43808),a=e.i(851179),o=e.i(84110);class l{providers=[];initialized=!1;defaultProperties={};utmParams={};constructor(e){this.providers=e.providers.map(t=>new t.Provider(t.options,e.ComplianceService)),this.utmParams=(0,o.initializeUTMParams)()}canExecuteProvider(e){return a.logger.debug("Checking if provider can execute",{provider:e}),"always-load"===e.complianceBehavior||e.hasConsent}getEnabledProviders(){return a.logger.debug("Getting enabled providers"),this.providers.filter(e=>this.canExecuteProvider(e))}async initialize(e){if(this.initialized)return;e?.user?.member?.id&&(this.defaultProperties={member_user_id:e.user.member.id,account_id:e.user.member.account_id});let t=this.getEnabledProviders();await Promise.all(t.map(t=>t.init(e))),a.logger.debug("Analytics initialized"),this.initialized=!0}pageView(e,t){a.logger.debug("pageView",{name:e,properties:t}),this.getEnabledProviders().forEach(i=>i.pageView(e,t))}track(e,t){let i={...this.defaultProperties,...t};a.logger.debug("track",{event:e,properties:i}),this.getEnabledProviders().forEach(t=>t.track(e,i))}identify(e){a.logger.debug("identify",e),this.getEnabledProviders().forEach(t=>{e.userId?t.identify({userId:e.userId,traits:e.traits}):e.traits&&t.identify({traits:e.traits})})}reset(){a.logger.debug("Resetting analytics"),this.defaultProperties={},this.providers.forEach(e=>e.reset())}}var c=e.i(421355);function u(e){let[,t]=e;return void 0!==t}e.s(["AnalyticsProvider",0,function(e){let a,o,h,d,g,p=(0,i.c)(17),{config:f,children:m,user:y,experiments:v}=e,b=(0,s.usePathname)(),{instance:_}=(0,n.useCompliance)(),[S,k]=(0,r.useState)(null);return p[0]!==_||p[1]!==f||p[2]!==y?(a=()=>{if(!_)return;let e=new l({...f,ComplianceService:_});e.initialize({user:y}).then(()=>{k(e)})},p[0]=_,p[1]=f,p[2]=y,p[3]=a):a=p[3],p[4]!==_||p[5]!==f?(o=[f,_],p[4]=_,p[5]=f,p[6]=o):o=p[6],(0,r.useEffect)(a,o),p[7]!==S||p[8]!==v?(h=()=>{let e=v?Object.fromEntries(Object.entries(v).filter(u)):void 0;S?.pageView(void 0,{experiments:e})},p[7]=S,p[8]=v,p[9]=h):h=p[9],p[10]!==S||p[11]!==v||p[12]!==b?(d=[S,b,v],p[10]=S,p[11]=v,p[12]=b,p[13]=d):d=p[13],(0,r.useEffect)(h,d),p[14]!==m||p[15]!==S?(g=(0,t.jsx)(c.AnalyticsContext.Provider,{value:S,children:m}),p[14]=m,p[15]=S,p[16]=g):g=p[16],g}],583752)},170336,922310,e=>{"use strict";var t,i=((t={}).StrictlyNecessary="C0001",t.Performance="C0002",t.Functional="C0003",t.Targeting="C0004",t.Marketing="C0005",t);e.s(["ConsentLevel",()=>i],170336);var r=e.i(851179);class s{static instance=null;options;listeners=[];consentListeners={[i.StrictlyNecessary]:[],[i.Functional]:[],[i.Marketing]:[],[i.Performance]:[],[i.Targeting]:[]};providerName="oneTrust";constructor(e){this.options=e}static getInstance(){if(!s.instance)throw Error("ComplianceService must be initialized before use");return s.instance}static init(e){return s.instance||(s.instance=new s(e),s.instance.setupListeners(),r.logger.debug("Compliance initialized")),s.instance}checkConsent(e){if("interacted"===this.state)return window.OnetrustActiveGroups?.split(",").includes(e)}getConsent(){return Object.values(i).reduce((e,t)=>(e[t]=this.checkConsent(t),e),{})}loadListeners=[];onLoad(e){this.loadListeners.push(e)}addListener(e,t){"function"==typeof e?this.listeners.push(e):t&&this.consentListeners[e].push(t)}removeListener(e,t){if("function"==typeof e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1);return}if(!t)return;let i=this.consentListeners[e],r=i.indexOf(t);r>-1&&i.splice(r,1)}static acceptAll(){let e=window.OneTrust;e&&(s.updateAlertBox(),e.AllowAll())}static rejectAll(){let e=window.OneTrust;e&&(s.updateAlertBox(),e.RejectAll())}static toggleSettings(){let e=window.OneTrust;e&&e.ToggleInfoDisplay()}static updateAlertBox(){let e=window.OneTrust;
1e&&(e.SetAlertBoxClosed(),document.cookie=`OptanonAlertBoxClosed=${new Date().toISOString()} path=/ secure max-age=31536000`)}setupListeners(){window.addEventListener("oneTrustConsentInitialized",()=>{this.loadListeners.forEach(e=>e())}),window.addEventListener("oneTrustConsentChanged",()=>{Object.values(i).forEach(e=>{let t=this.checkConsent(e);this.notifyListeners(e,t)});let e=this.getConsent();this.listeners.forEach(t=>t(e))})}notifyListeners(e,t){this.consentListeners[e].forEach(e=>e(t))}get state(){let e=window.OneTrust;return e&&window.OnetrustActiveGroups?e.IsAlertBoxClosedAndValid()?"interacted":"initialized":"loading"}}e.s(["ComplianceService",0,s],922310)},127329,e=>{"use strict";function t(e){return null!=e&&"object"==typeof e&&!0===e["@@functional/placeholder"]}function i(e){return function i(r){return 0==arguments.length||t(r)?i:e.apply(this,arguments)}}function r(e){return function r(s,n){switch(arguments.length){case 0:return r;case 1:return t(s)?r:i(function(t){return e(s,t)});default:return t(s)&&t(n)?r:t(s)?i(function(t){return e(t,n)}):t(n)?i(function(t){return e(s,t)}):e(s,n)}}}function s(e){return function s(n,a,o){switch(arguments.length){case 0:return s;case 1:return t(n)?s:r(function(t,i){return e(n,t,i)});case 2:return t(n)&&t(a)?s:t(n)?r(function(t,i){return e(t,a,i)}):t(a)?r(function(t,i){return e(n,t,i)}):i(function(t){return e(n,a,t)});default:return t(n)&&t(a)&&t(o)?s:t(n)&&t(a)?r(function(t,i){return e(t,i,o)}):t(n)&&t(o)?r(function(t,i){return e(t,a,i)}):t(a)&&t(o)?r(function(t,i){return e(n,t,i)}):t(n)?i(function(t){return e(t,a,o)}):t(a)?i(function(t){return e(n,t,o)}):t(o)?i(function(t){return e(n,a,t)}):e(n,a,o)}}}function n(e,t){return Object.prototype.hasOwnProperty.call(t,e)}var a,o,l,c,u=i(function(e){return null===e?"Null":void 0===e?"Undefined":Object.prototype.toString.call(e).slice(8,-1)});function h(e){return"[object Object]"===Object.prototype.toString.call(e)}let d=Number.isInteger||function(e){return(0|e)===e};var g=function(){function e(){this.map={},this.length=0}return e.prototype.set=function(e,t){var i=this.hash(e),r=this.map[i];r||(this.map[i]=r=[]),r.push([e,t]),this.length+=1},e.prototype.hash=function(e){var t=[];for(var i in e)t.push(Object.prototype.toString.call(e[i]));return t.join()},e.prototype.get=function(e){if(this.length<=180){for(var t in this.map)for(var i=this.map[t],r=0;r<i.length;r+=1){var s=i[r];if(s[0]===e)return s[1]}return}var n=this.hash(e),i=this.map[n];if(i)for(var r=0;r<i.length;r+=1){var s=i[r];if(s[0]===e)return s[1]}},e}(),p=i(function(e){return null!=e&&"function"==typeof e.clone?e.clone():function e(t,i,r){if(r||(r=new g),n=typeof(s=t),null==s||"object"!=n&&"function"!=n)return t;var s,n,a=function(i){var s=r.get(t);if(s)return s;for(var n in r.set(t,i),t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=e(t[n],!0,r));return i};switch(u(t)){case"Object":return a(Object.create(Object.getPrototypeOf(t)));case"Array":return a(Array(t.length));case"Date":return new Date(t.valueOf());case"RegExp":return new RegExp(t.source,t.flags?t.flags:(t.global?"g":"")+(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.sticky?"y":"")+(t.unicode?"u":"")+(t.dotAll?"s":""));case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float32Array":case"Float64Array":case"BigInt64Array":case"BigUint64Array":return t.slice();default:return t}}(e)}),f=s(function(e,t,i){var r,s={};for(r in i=i||{},t=t||{})n(r,t)&&(s[r]=n(r,i)?e(r,t[r],i[r]):t[r]);for(r in i)n(r,i)&&!n(r,s)&&(s[r]=i[r]);return s}),m=s(function e(t,i,r){return f(function(i,r,s){return h(r)&&h(s)?e(t,r,s):t(i,r,s)},i,r)}),y=s(function(e,t,i){return m(function(t,i,r){return e(i,r)},t,i)}),v=r(function(e,t){for(var i=t,r=0;r<e.length;r+=1){if(null==i)return;var s=e[r];i=d(s)?function(e,t){var i=e<0?t.length+e:e;return"[object String]"===Object.prototype.toString.call(t)?t.charAt(i):t[i]}(s,i):i[s]}return i}),b=r(function(e,t){var i={};for(var r in t)e(t[r],r,t)&&(i[r]=t[r]);return i});let _=e=>"function"==typeof e&&!!(e.constructor&&e.call&&e.apply),S=e=>void 0!==e,k=e=>{let t;return null!=(t=e)},w=e=>{switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object E
1xception]":case"[object DOMException]":return!0;default:return e instanceof Error}},C=(e,t)=>v(t.split("."),e),P=e=>null!==e&&"[object Object]"===Object.prototype.toString.call(e),T=(e,t)=>{if(!Array.isArray(e)||!Array.isArray(t))return p(t);let i=p(e);return t.forEach((e,t)=>{let r;i[t]=Array.isArray(e)||null!==(r=e)&&"object"==typeof r&&!Array.isArray(r)?E(i[t],e):e}),i},E=(e,t)=>y(T,e,t),A=e=>P(e)&&Object.keys(e).length>0,I=e=>{let t=b(S,e);return Object.keys(t).forEach(e=>{let i=t[e];P(i)&&(t[e]=I(i))}),t},D=e=>{let t=b(k,e);return Object.keys(t).forEach(e=>{let i=t[e];P(i)&&(t[e]=D(i))}),t},O=e=>{if(A(e))return D(e)},R=(e,t)=>S(t)?S(e)?!0===e:t:!0===e,L=e=>{let t,i=e;if("string"!=typeof e&&null!=(t=e))try{i=JSON.stringify(e)}catch(e){i=null}return i},M=(e,t,i,r,s)=>{let n={category:e,name:t,properties:i,options:r,callback:void 0};_(s)&&(n.callback=s),_(r)&&(n.category=e,n.name=t,n.properties=i,n.options=void 0,n.callback=r),_(i)&&(n.category=e,n.name=t,n.properties=void 0,n.options=void 0,n.callback=i),_(t)&&(n.category=e,n.name=void 0,n.properties=void 0,n.options=void 0,n.callback=t),_(e)&&(n.category=void 0,n.name=void 0,n.properties=void 0,n.options=void 0,n.callback=e),P(e)?(n.name=void 0,n.category=void 0,n.properties=e,_(t)?n.options=void 0:n.options=t):P(t)&&(n.name=void 0,n.properties=t,_(i)?n.options=void 0:n.options=i),"string"==typeof e&&"string"!=typeof t&&(n.category=void 0,n.name=e),S(n.category)||(n.category=void 0),S(n.name)||(n.name=void 0),n.properties=n.properties?p(n.properties):{},S(n.options)?n.options=p(n.options):n.options=void 0;let a="string"==typeof n.name?n.name:n.properties.name,o="string"==typeof n.category?n.category:n.properties.category;return n.properties=E(P(n.properties)?n.properties:{},{...a&&{name:a},...o&&{category:o}}),n},$=(e,t,i,r)=>{let s={name:e,properties:t,options:i,callback:void 0};return _(r)&&(s.callback=r),_(i)&&(s.properties=t,s.options=void 0,s.callback=i),_(t)&&(s.properties=void 0,s.options=void 0,s.callback=t),s.properties=k(s.properties)?p(s.properties):{},S(s.options)?s.options=p(s.options):s.options=void 0,s},N=(e,t,i,r)=>{let s={userId:e,traits:t,options:i,callback:void 0};return _(r)&&(s.callback=r),_(i)&&(s.userId=e,s.traits=t,s.options=void 0,s.callback=i),_(t)&&(s.userId=e,s.traits=void 0,s.options=void 0,s.callback=t),(P(e)||null===e)&&(s.userId=null,s.traits=e,_(t)?s.options=void 0:s.options=t),s.userId=L(s.userId),P(s.traits)?s.traits=p(s.traits):s.traits=void 0,S(s.options)?s.options=p(s.options):s.options=void 0,s},U=(e,t,i,r)=>{let s={to:e,from:t,options:i,callback:void 0};return(_(r)&&(s.callback=r),_(i)&&(s.to=e,s.from=t,s.options=void 0,s.callback=i),_(t))?(s.to=e,s.from=void 0,s.options=void 0,s.callback=t):(P(t)||null===t)&&(s.to=e,s.from=void 0,s.options=t),S(s.to)&&(s.to=L(s.to)),S(s.from)?s.from=L(s.from):s.from=void 0,S(s.options)?s.options=p(s.options):s.options=void 0,s},x=(e,t,i,r)=>{let s={groupId:e,traits:t,options:i,callback:void 0};return _(r)&&(s.callback=r),_(i)&&(s.groupId=e,s.traits=t,s.options=void 0,s.callback=i),_(t)&&(s.groupId=e,s.traits=void 0,s.options=void 0,s.callback=t),(P(e)||null===e)&&(s.groupId=null,s.traits=e,_(t)?s.options=void 0:s.options=t),s.groupId=L(s.groupId),P(s.traits)?s.traits=p(s.traits):s.traits=void 0,S(s.options)?s.options=p(s.options):s.options=void 0,s},B=((V={}).LOADED="Page Loaded",V.UNLOADED="Page Unloaded",V),K="CapabilitiesManager",F="ConfigManager",j="EventManager",z="PluginsManager",q="UserSessionManager",H="ErrorHandler",Q="PluginEngine",G="ReadyAPI",W="AnalyticsCore";for(var V,J,X=[],Z=0;Z<256;Z++)X[Z]=(Z+256).toString(16).substring(1);for(var Y,ee=256,et=[];ee--;)et[ee]=(ee+256).toString(16).substring(1);let ei=()=>{let e;if(null!=(e=globalThis.crypto)&&_(globalThis.crypto.getRandomValues)){(!J||Z+16>4096)&&(J=crypto.getRandomValues(new Uint8Array(4096)),Z=0);for(var t,i=0,r="";i<16;i++)t=J[Z+i],6==i?r+=X[15&t|64]:8==i?r+=X[63&t|128]:r+=X[t],1&i&&i>1&&i<11&&(r+="-");return Z+=16,r}var s,n=0,a="";if(!Y||ee+16>256){for(Y=Array(n=256);n--;)Y[n]=256*Math.random()|0;n=ee=0}for(;n<16;n++)s=Y[ee+n],6==n?a+=et[15&s|64]:8==n?a+=et[63&s|128]:a+=et[s],1&n&&n>1&&n<11&&(a+="-");return ee++,a},er=(e,t)=>`Failed to load the script with the id "${e}" from URL "${t}".`,es="[Circular Reference]",en=(e,t,i,r)=>{try{let s;return JSON.stringify(e,(s=[],function(e,n){if(!i?.includes(e)){let i;if(!(t&&null==(i=n))){if("object"!=typeof n||null===n)return n;for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(n))return r?.warn(`JSONStringify:: A circular reference has been detected in the object and the property "${e}" has been dropped from the output.`),es;return s.push(n),n}}}))}catch(e){return r?.warn("Failed to convert the value to a JSON string.",e),null}},ea=(e,t)=>{let i=Array.isArray(e)?[]:{};for(let r in e)if(Object.hasOwnProperty.call(e,r)){let s=e[r],n=t.call(e,r,s);P(n)||Array.isArray(n)?i[r]=ea(n,t):i[r]=n}return i},eo=(e,t)=>{let i,r=(i=[],function(e,t){if("bigint"==typeof t)return"[BigInt]";for(;i.length>0&&i[i.length-1]!==this;)i.pop();return i.includes(t)?es:(i.push(t),t)}),s=r.call(e,"",e);return P(e)||Array.isArray(e)?ea(e,r):s},el="[SDK DISPATCHED ERROR]",ec=e=>{let{stack:t,stacktrace:i}=e,r=e["opera#sourceloc"],s=t??i??r;if(s&&"string"==typeof s)return s},eu=(e,t)=>
1{let i=e;return w(e)?i.message=`${t}: ${e.message}`:i=Error(`${t}: ${en(e)}`),i},eh=e=>{if(w(e)){let t=ec(e);if(t){let{stack:i,stacktrace:r}=e,s=e["opera#sourceloc"];switch(t){case i:e.stack=`${i} 2${el}`;break;case r:e.stacktrace=`${r} 3${el}`;break;default:e["opera#sourceloc"]=`${s} 4${el}`}}}globalThis.dispatchEvent(new ErrorEvent("error",{error:e,bubbles:!0,cancelable:!0,composed:!0}))},ed="RudderLabs JavaScript SDK",eg="3.16.1",ep="RudderJS-Initiated",ef="preloadedEventsBuffer",em="ajs_aid",ey="ajs_uid",ev="ajs_event",eb=1e4,e_=(e="app")=>{globalThis.RudderStackGlobals||(globalThis.RudderStackGlobals={}),globalThis.RudderStackGlobals[e]||(globalThis.RudderStackGlobals[e]={})},eS=(e,t,i="app")=>{e_(i),globalThis.RudderStackGlobals[i][e]=t},ek=(e,t="app")=>(e_(t),globalThis.RudderStackGlobals[t][e]),ew=(e,t)=>{let i={};return e.forEach((r,s)=>{s.startsWith(t)&&(i[s.substring(t.length)]=e.get(s))}),i},eC=(e,t)=>{let i,r=e.shift();if(_(t[r])){switch(r){case"page":i=M(...e);break;case"track":i=$(...e);break;case"identify":i=N(...e);break;case"alias":i=U(...e);break;case"group":i=x(...e);break;default:t[r](...e)}i&&t[r](i)}};class eP{constructor(e,t,i=1e4){this.errorHandler=e,this.logger=t,this.timeout=i,this.onError=this.onError.bind(this)}loadJSFile(e){let{url:t,id:i,timeout:r,async:s,callback:n,extraAttributes:a}=e,o=!_(n);((e,t,i,r=!0,s)=>new Promise((n,a)=>{document.getElementById(t)&&a(Error(`A script with the id "${t}" is already loaded. Skipping the loading of this script to prevent conflicts.`));try{let o;(e=>{let t=document.getElementsByTagName("head");if(t.length>0)return t[0]?.insertBefore(e,t[0]?.firstChild);let i=document.getElementsByTagName("script");if(i.length>0&&i[0]?.parentNode)return i[0]?.parentNode.insertBefore(e,i[0]);let r=document.createElement("head");r.appendChild(e);let s=document.getElementsByTagName("html")[0];s?.insertBefore(r,s.firstChild)})(((e,t,i=!0,r=null,s=null,n={})=>{let a=document.createElement("script");return a.type="text/javascript",a.onload=r,a.onerror=s,a.src=e,a.id=t,a.async=i,Object.keys(n).forEach(e=>{a.setAttribute(e,n[e])}),a.setAttribute("data-loader","RS_JS_SDK"),a})(e,t,r,()=>{globalThis.clearTimeout(o),n(t)},()=>{globalThis.clearTimeout(o),a(Error(er(t,e)))},s)),o=globalThis.setTimeout(()=>{a(Error(`A timeout of ${i} ms occurred while trying to load the script with id "${t}" from URL "${e}".`))},i)}catch(i){a(eu(i,er(t,e)))}}))(t,i,r||this.timeout,s,a).then(e=>{o||n(e)}).catch(e=>{this.onError(e),o||n()})}onError(e){this.errorHandler.onError(e,"ExternalSrcLoader")}}var eT=Symbol.for("preact-signals");function eE(){if(eO>1)eO--;else{for(var e,t=!1;void 0!==eD;){var i=eD;for(eD=void 0,eR++;void 0!==i;){var r=i.o;if(i.o=void 0,i.f&=-3,!(8&i.f)&&eU(i))try{i.c()}catch(i){t||(e=i,t=!0)}i=r}}if(eR=0,eO--,t)throw e}}function eA(e){if(eO>0)return e();eO++;try{return e()}finally{eE()}}var eI=void 0,eD=void 0,eO=0,eR=0,eL=0;function eM(e){if(void 0!==eI){var t=e.n;if(void 0===t||t.t!==eI)return t={i:0,S:e,p:eI.s,n:void 0,t:eI,e:void 0,x:void 0,r:t},void 0!==eI.s&&(eI.s.n=t),eI.s=t,e.n=t,32&eI.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=eI.s,t.n=void 0,eI.s.n=t,eI.s=t),t}}function e$(e){this.v=e,this.i=0,this.n=void 0,this.t=void 0}function eN(e){return new e$(e)}function eU(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 ex(e){for(var t=e.s;void 0!==t;t=t.n){var i=t.S.n;if(void 0!==i&&(t.r=i),t.S.n=t,t.i=-1,void 0===t.n){e.s=t;break}}}function eB(e){for(var t=e.s,i=void 0;void 0!==t;){var r=t.p;-1===t.i?(t.S.U(t),void 0!==r&&(r.n=t.n),void 0!==t.n&&(t.n.p=r)):i=t,t.S.n=t.r,void 0!==t.r&&(t.r=void 0),t=r}e.s=i}function eK(e){e$.call(this,void 0),this.x=e,this.s=void 0,this.g=eL-1,this.f=4}function eF(e){var t=e.u;if(e.u=void 0,"function"==typeof t){eO++;var i=eI;eI=void 0;try{t()}catch(t){throw e.f&=-2,e.f|=8,ej(e),t}finally{eI=i,eE()}}}function ej(e){for(var t=e.s;void 0!==t;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,eF(e)}function ez(e){if(eI!==this)throw Error("Out-of-order effect");eB(this),eI=e,this.f&=-2,8&this.f&&ej(this),eE()}function eq(e){this.x=e,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}function eH(e){var t=new eq(e);try{t.c()}catch(e){throw t.d(),e}return t.d.bind(t)}e$.prototype.brand=eT,e$.prototype.h=function(){return!0},e$.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)},e$.prototype.U=function(e){if(void 0!==this.t){var t=e.e,i=e.x;void 0!==t&&(t.x=i,e.e=void 0),void 0!==i&&(i.e=t,e.x=void 0),e===this.t&&(this.t=i)}},e$.prototype.subscribe=function(e){var t=this;return eH(function(){var i=t.value,r=eI;eI=void 0;try{e(i)}finally{eI=r}})},e$.prototype.valueOf=function(){return this.value},e$.prototype.toString=function(){return this.value+""},e$.prototype.toJSON=function(){return this.value},e$.prototype.peek=function(){var e=eI;eI=void 0;try{return this.value}finally{eI=e}},Object.defineProperty(e$.prototype,"value",{get:function(){var e=eM(this);return void 0!==e&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(eR>100)throw Error("Cycle detected");this.v=e,this.i++,eL++,eO++;try{for(var t=this.t;void 0!==t;t=t.x)t.t.N()}finally{eE()}}}}),(eK.prototype=new e$).h=function(){if(this.f&=-3,1&this.f)return!1;if(32==(36&this.f)||(this.f&=-5,this.g===eL))return!0;
4if(this.g=eL,this.f|=1,this.i>0&&!eU(this))return this.f&=-2,!0;var e=eI;try{ex(this),eI=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 eI=e,eB(this),this.f&=-2,!0},eK.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)}e$.prototype.S.call(this,e)},eK.prototype.U=function(e){if(void 0!==this.t&&(e$.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)}},eK.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(eK.prototype,"value",{get:function(){if(1&this.f)throw Error("Cycle detected");var e=eM(this);if(this.h(),void 0!==e&&(e.i=this.i),16&this.f)throw this.v;return this.v}}),eq.prototype.c=function(){var e=this.S();try{if(8&this.f||void 0===this.x)return;var t=this.x();"function"==typeof t&&(this.u=t)}finally{e()}},eq.prototype.S=function(){if(1&this.f)throw Error("Cycle detected");this.f|=1,this.f&=-9,eF(this),ex(this),eO++;var e=eI;return eI=this,ez.bind(this,e)},eq.prototype.N=function(){2&this.f||(this.f|=2,this.o=eD,eD=this)},eq.prototype.d=function(){this.f|=8,1&this.f||ej(this)};class eQ{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=[]}}let eG={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5},eW="ERROR",eV=new class{constructor(e="LOG",t="",i=console){this.minLogLevel=eG[e],this.scope=t,this.logProvider=i}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<=eG[e]&&this.logProvider[e.toLowerCase()]?.(...this.formatLogData(t))}setScope(e){this.scope=e||this.scope}setMinLogLevel(e){this.minLogLevel=eG[e],void 0===this.minLogLevel&&(this.minLogLevel=eG.LOG)}formatLogData(e){if(Array.isArray(e)&&e.length>0){let t="%c RS SDK";this.scope&&(t=`${t} - ${this.scope}`);let i="string"==typeof e[0]?e[0].trim():"",r=[t=`${t} %c ${i}`,"font-weight: bold; background: black; color: white;","font-weight: normal;"];return"string"!=typeof e[0]&&r.push(e[0]),r.push(...e.slice(1)),r}return e}},eJ=((a={}).HANDLEDEXCEPTION="handledException",a.UNHANDLEDEXCEPTION="unhandledException",a.UNHANDLEDREJECTION="unhandledPromiseRejection",a),eX=["localStorage","memoryStorage","cookieStorage","sessionStorage","none"],eZ="cookieStorage",eY="Unable to process/parse source configuration response",e0="Failed to fetch the source config",e1=e=>`${e}:: The provided callback parameter is not a function.`,e2={All:!0},e6="js-integrations",e3="plugins",e8=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_]*)?$"),e5="modern",e4="https://cdn.rudderlabs.com",e9=`${e4}/v3/${e5}/${e6}`,e7=`${e4}/v3/${e5}/${e3}`,te="https://api.rudderstack.com",tt={iubenda:"IubendaConsentManager",oneTrust:"OneTrustConsentManager",ketch:"KetchConsentManager",custom:"CustomConsentManager"},ti={v3:"StorageEncryption",legacy:"StorageEncryptionLegacy"},tr={xhr:"XhrQueue",beacon:"BeaconQueue"},ts=eN(p({configUrl:te,loadIntegration:!0,sessions:{autoTrack:!0,timeout:18e5},sameSiteCookie:"Lax",polyfillIfRequired:!0,integrations:e2,useBeacon:!1,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:!0,lockPluginsVersion:!0,uaChTrackLevel:"none",plugins:[],useGlobalIntegrationsConfigInEvents:!1,bufferDataPlaneEventsUntilReady:!1,dataPlaneEventsBufferTimeout:1e4,storage:{encryption:{version:"v3"},migrate:!0,cookie:{}},sendAdblockPage:!1,sameDomainCookiesOnly:!1,secureCookie:!1,sendAdblockPageOptions:{},useServerSideCookies:!1})),tn={},ta={},to={},tl={autoTrack:!0,timeout:18e5},tc={userId:eN(""),userTraits:eN(tn),anonymousId:eN(""),groupId:eN(""),groupTraits:eN(ta),initialReferrer:eN(""),initialReferringDomain:eN(""),sessionInfo:eN(to),authToken:eN(null)},tu={isOnline:eN(!0),storage:{isLocalStorageAvailable:eN(!1),isCookieStorageAvailable:eN(!1),isSessionStorageAvailable:eN(!1)},isBeaconAvailable:eN(!1),isLegacyDOM:eN(!1),isUaCHAvailable:eN(!1),isCryptoAvailable:eN(!1),isIE11:eN(!1),isAdBlocked:eN(!1)},th={isErrorReportingEnabled:eN(!1),isMetricsReportingEnabled:eN(!1),breadcrumbs:eN([])},td=eN(void 0),tg={activeDataplaneUrl:eN(void 0),integrationsCDNPath:eN(e9),pluginsCDNPath:eN(e7),sourceConfigUrl:eN(void 0),status:eN(void 0),initialized:eN(!1),logLevel:eN(eW),loaded:eN(!1),readyCallbacks:eN([]),writeKey:eN(void 0),dataPlaneUrl:eN(void 0)},tp={enabled:eN(!1),initialized:eN(!1),data:eN({}),activeConsentManagerPluginName:eN(void 0),preConsent:eN({enabled:!1}),postConsent:eN({}),resolutionStrategy:eN("and"),provider:eN(void 0),metadata:eN(void 0)},tf={retries:eN(0),dropped:eN(0),sent:eN(0),queued:eN(0),triggered:eN(0),metricsServiceUrl:eN(void 0)},tm={app:eN({name:ed,namespace:"com.rudderlabs.javascript",version:eg,installType:"npm"}),traits:eN(null),library:eN({name:ed,version:eg,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:eN(null),device:eN(null),network:eN(null),os:eN({name:"",version:""}),locale:eN(null),screen:eN({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),"ua-ch":eN(void 0),timezone:eN(void 0)},ty={configuredDestinations:eN([]),activeDestinations:eN([]),loadOnlyIntegrations:eN({}),failedDestinations:eN([]),loadIntegration:eN(!0),initializedDestinations:eN([]),clientDestinationsReady:eN(!1),integrationsConfig:eN({})},tv={...p({capabilities:tu,consents:tp,context:tm,eventBuffer:{toBeProcessedArray:eN([]),readyCallbacksArray:eN([])},lifecycle:tg,loadOptions:ts,metrics:tf,nativeDestinations:ty,plugins:{ready:eN(!1),loadedPlugins:eN([]),failedPlugins:eN([]),pluginsToLoadFromConfig:eN([]),activePlugins:eN([]),totalPluginsToLoad:eN(0)},reporting:th,session:tc,source:td,storage:{encryptionPluginName:eN(void 0),migrate:eN(!1),type:eN(void 0),cookie:eN(void 0),entries:eN({}),trulyAnonymousTracking:eN(!1)},serverCookies:{isEnabledServerSideCookies:eN(!1),dataServiceUrl:eN(void 0)},dataPlaneEvents:{eventsQueuePluginName:eN(void 0),deliveryEnabled:eN(!0)},autoTrack:{enabled:eN(!1),pageLifecycle:{enabled:eN(!1),visitId:eN(void 0),pageLoadedTimestamp:eN(void 0)}}})};
4function tb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t_={exports:{}},tS={exports:{}};tS.exports,t_.exports;let tk=tb(function(){var e,t,i,r;if(l)return t_.exports;return l=1,e=o?tS.exports:(o=1,tS.exports=function(){function e(e){return e.charAt(0).toUpperCase()+e.substring(1)}function t(e){return function(){return this[e]}}var i=["isConstructor","isEval","isNative","isToplevel"],r=["columnNumber","lineNumber"],s=["fileName","functionName","source"],n=i.concat(r,s,["args"],["evalOrigin"]);function a(t){if(t)for(var i=0;i<n.length;i++)void 0!==t[n[i]]&&this["set"+e(n[i])](t[n[i]])}a.prototype={getArgs:function(){return this.args},setArgs:function(e){if("[object Array]"!==Object.prototype.toString.call(e))throw TypeError("Args must be an Array");this.args=e},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(e){if(e instanceof a)this.evalOrigin=e;else if(e instanceof Object)this.evalOrigin=new a(e);else throw TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var e=this.getFileName()||"",t=this.getLineNumber()||"",i=this.getColumnNumber()||"",r=this.getFunctionName()||"";return this.getIsEval()?e?"[eval] ("+e+":"+t+":"+i+")":"[eval]:"+t+":"+i:r?r+" ("+e+":"+t+":"+i+")":e+":"+t+":"+i}},a.fromString=function(e){var t=e.indexOf("("),i=e.lastIndexOf(")"),r=e.substring(0,t),s=e.substring(t+1,i).split(","),n=e.substring(i+1);if(0===n.indexOf("@"))var o=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(n,""),l=o[1],c=o[2],u=o[3];return new a({functionName:r,args:s||void 0,fileName:l,lineNumber:c||void 0,columnNumber:u||void 0})};for(var o=0;o<i.length;o++)a.prototype["get"+e(i[o])]=t(i[o]),a.prototype["set"+e(i[o])]=function(e){return function(t){this[e]=!!t}}(i[o]);for(var l=0;l<r.length;l++)a.prototype["get"+e(r[l])]=t(r[l]),a.prototype["set"+e(r[l])]=function(e){return function(t){if(!(!isNaN(parseFloat(t))&&isFinite(t)))throw TypeError(e+" must be a Number");this[e]=Number(t)}}(r[l]);for(var c=0;c<s.length;c++)a.prototype["get"+e(s[c])]=t(s[c]),a.prototype["set"+e(s[c])]=function(e){return function(t){this[e]=String(t)}}(s[c]);return a}(),tS.exports),t=/(^|@)\S+:\d+/,i=/^\s*at .*(\S+:\d+|\(native\))/m,r=/^(eval@)?(\[native code])?$/,t_.exports={parse:function(e){if(void 0!==e.stacktrace||void 0!==e["opera#sourceloc"])return this.parseOpera(e);if(e.stack&&e.stack.match(i))return this.parseV8OrIE(e);if(e.stack)return this.parseFFOrSafari(e);throw Error("Cannot parse given Error object")},extractLocation:function(e){if(-1===e.indexOf(":"))return[e];var t=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(e.replace(/[()]/g,""));return[t[1],t[2]||void 0,t[3]||void 0]},parseV8OrIE:function(t){return t.stack.split("\n").filter(function(e){return!!e.match(i)},this).map(function(t){t.indexOf("(eval ")>-1&&(t=t.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var i=t.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),r=i.match(/ (\(.+\)$)/);i=r?i.replace(r[0],""):i;var s=this.extractLocation(r?r[1]:i);return new e({functionName:r&&i||void 0,fileName:["eval","<anonymous>"].indexOf(s[0])>-1?void 0:s[0],lineNumber:s[1],columnNumber:s[2],source:t})},this)},parseFFOrSafari:function(t){return t.stack.split("\n").filter(function(e){return!e.match(r)},this).map(function(t){if(t.indexOf(" > eval")>-1&&(t=t.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===t.indexOf("@")&&-1===t.indexOf(":"))return new e({functionName:t});var i=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=t.match(i),s=r&&r[1]?r[1]:void 0,n=this.extractLocation(t.replace(i,""));return new e({functionName:s,fileName:n[0],lineNumber:n[1],columnNumber:n[2],source:t})},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(t){for(var i=/Line (\d+).*script (?:in )?(\S+)/i,r=t.message.split("\n"),s=[],n=2,a=r.length;n<a;n+=2){var o=i.exec(r[n]);o&&s.push(new e({fileName:o[2],lineNumber:o[1],source:r[n]}))}return s},parseOpera10:function(t){for(var i=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,r=t.stacktrace.split("\n"),s=[],n=0,a=r.length;n<a;n+=2){var o=i.exec(r[n]);o&&s.push(new e({functionName:o[3]||void 0,fileName:o[2],lineNumber:o[1],source:r[n]}))}return s},parseOpera11:function(i){return i.stack.split("\n").filter(function(e){return!!e.match(t)&&!e.match(/^Error created at/)},this).map(function(t){var i,r=t.split("@"),s=this.extractLocation(r.pop()),n=r.shift()||"",a=n.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0;return n.match(/\(([^)]*)\)/)&&(i=n.replace(/^[^(]+\(([^)]*)\)$/,"$1")),new e({functionName:a,args:void 0===i||"[arguments not available]"===i?void 0:i.split(","),fileName:s[0],lineNumber:s[1],columnNumber:s[2],source:t})},this)}},t_.exports}()),tw="global code",tC=e=>"string"==typeof e?e:"";function tP(e,t,i,r){return{errorClass:tC(e),message:`${i}${tC(t)}`,type:"browserjs",stacktrace:r.reduce((e,t)=>
4{var i;let r,s=((r={file:t.fileName,method:S(i=t.functionName)&&/^global code$/i.test(i)?tw:i,lineNumber:t.lineNumber,columnNumber:t.columnNumber}).lineNumber&&r.lineNumber>-1&&!r.file&&!r.method&&(r.file=tw),r);try{if("{}"===JSON.stringify(s))return e;return e.concat(s)}catch{return e}},[])}}let tT=(e,t)=>{try{return JSON.parse(e||"")}catch(e){t(eu(e,"Failed to parse response data"))}},tE="The request failed",tA=[/Failed to fetch dynamically imported module: .*/],tI=[/Failed to load the script with the id .*/,/A timeout of \d+ ms occurred while trying to load the script with id .*/],tD=[RegExp(`${tE}.*`),/A script with the id .* is already loaded\./],tO={headers:{Accept:"application/json","Content-Type":"application/json;charset=UTF-8"},method:"GET"},tR=(e,t,i)=>{let r=E(tO,t||{});return i&&(r.headers=E(r.headers,{Authorization:i})),r.url=e,r},tL=(e,t=eb,i)=>new Promise((r,s)=>{let n;if(!0===e.sendRawData)n=e.data;else if(null===(n=en(e.data,!1,[],i)))return void s({error:Error("Failed to prepare data for the request."),undefined,options:e});let a=new XMLHttpRequest,o=t=>{let i;s({error:Error((i=e.url,`${tE} due to timeout or no connection (${t?t.type:""}) at the client side for URL: ${i}`)),xhr:a,options:e})};a.ontimeout=o,a.onerror=o,a.onload=()=>{if(a.status>=200&&a.status<400)r({response:a.responseText,xhr:a,options:e});else{let t,i,r,n;s({error:Error((t=a.status,i=a.statusText,r=e.url,n=a.responseText,`${tE} with status ${t} (${i}) for URL: ${r}. Response: ${n.trim()}`)),xhr:a,options:e})}},a.open(e.method,e.url,!0),!0===e.withCredentials&&(a.withCredentials=!0),a.timeout=t,Object.keys(e.headers).forEach(t=>{e.headers[t]&&a.setRequestHeader(t,e.headers[t])});try{a.send(n)}catch(i){let t;s({error:eu(i,(t=e.url,`${tE} for URL: ${t}`)),xhr:a,options:e})}}),tM=new class{constructor(e){this.logger=e,this.onError=this.onError.bind(this)}init(e){this.errorHandler=e}async getData(e){let{url:t,options:i,timeout:r,isRawResponse:s}=e;try{let e=await tL(tR(t,i,this.basicAuthHeader),r,this.logger);return{data:s?e.response:tT(e.response,this.onError),details:e}}catch(e){return{data:void 0,details:e}}}getAsyncData(e){let{callback:t,url:i,options:r,timeout:s,isRawResponse:n}=e,a=!_(t);tL(tR(i,r,this.basicAuthHeader),s,this.logger).then(e=>{a||t(n?e.response:tT(e.response,this.onError),e)}).catch(e=>{a||t(void 0,e)})}onError(e){this.errorHandler?.onError(e,"HttpClient")}setAuthHeader(e,t=!1){let i,r=t?e:(i=`${e}:`,globalThis.btoa(Array.from(new TextEncoder().encode(i),e=>String.fromCodePoint(e)).join("")));this.basicAuthHeader=`Basic ${r}`}resetAuthHeader(){this.basicAuthHeader=void 0}}(eV),t$=["www.test-host.com","localhost","127.0.0.1","[::1]"],tN=["userId","userTraits","groupId","groupTraits","anonymousId","config","instance","eventBuffer","traits","authToken"],tU=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,H,void 0,eJ.UNHANDLEDEXCEPTION)}),globalThis.addEventListener("unhandledrejection",e=>{this.onError(e,H,void 0,eJ.UNHANDLEDREJECTION)})}onError(e,t="",i="",r=eJ.HANDLEDEXCEPTION){try{let s,n=((e,t)=>{switch(t){case eJ.UNHANDLEDEXCEPTION:{let{error:t}=e;return t||e}case eJ.UNHANDLEDREJECTION:return e.reason;case eJ.HANDLEDEXCEPTION:default:return e}})(e,r),a=((e,t)=>{let i;if(w(e)&&"string"==typeof ec(e))i=e;else{let r;t.warn((r=en(e),`${H}:: Ignoring a non-error: ${r}.`)),i=void 0}return i})(n,this.logger);if(void 0===a)return;let o=i?`${i} - `:"",l=`${t}:: ${o}`,c=((e,t)=>{try{let i=tk.parse(e);return tP(e.name,e.message,t,i)}catch{return tP(e.name,e.message,t,[])}})(a,l),u=ec(a).includes(el);if(!u&&!(e=>{let t=e.stacktrace[0]?.file;if(!t||"string"!=typeof t)return!1;let i=t.substring(t.lastIndexOf("/")+1),r=t.split("/");return r[r.length-2]===e6||["rsa"].some(e=>i.startsWith(e)&&i.endsWith(".js"))})(c)&&r!==eJ.HANDLEDEXCEPTION)return;if(tv.reporting.isErrorReportingEnabled.value&&(s=c.message,tA.some(e=>e.test(s))||tI.some(e=>e.test(s))?s.includes(e4):!tD.some(e=>e.test(s)))){let e={severity:"error",unhandled:r!==eJ.HANDLEDEXCEPTION,severityReason:{type:r}},t=((e,t,i)=>{let r,s,{context:n,lifecycle:a,session:o,source:l,reporting:c,autoTrack:u}=i,{app:h,locale:d,userAgent:g,timezone:f,screen:m,library:y}=n;return{payloadVersion:"5",notifier:{name:"RudderStack JavaScript SDK",version:h.value.version,url:"__REPOSITORY_URL__"},events:[{exceptions:[p(e)],severity:t.severity,unhandled:t.unhandled,severityReason:t.severityReason,app:{version:h.value.version,releaseStage:(r=globalThis.location.hostname)&&t$.includes(r)?"development":"production",type:h.value.installType},device:{locale:d.value??"NA",userAgent:g.value??"NA",time:new Date},request:{url:globalThis.location.href.split("?")[0],clientIp:"[NOT COLLECTED]"}
4,breadcrumbs:p(c.breadcrumbs.value),context:e.message,metaData:{app:{snippetVersion:y.value.snippetVersion},device:{...m.value,timezone:f.value},...(s=en(i,!1,tN),null!==s?JSON.parse(s):{})},user:{id:`${l.value?.id??a.writeKey.value}..${o.sessionInfo.value.id??"NA"}..${u.pageLifecycle.visitId.value??"NA"}`,name:l.value?.name??"NA"}}]}})(c,e,tv);this.httpClient.getAsyncData({url:tv.metrics.metricsServiceUrl.value,options:{method:"POST",data:en({version:"1",message_id:ei(),source:{name:"js",sdk_version:tv.context.app.value.version,write_key:tv.lifecycle.writeKey.value,install_type:tv.context.app.value.installType},errors:t}),sendRawData:!0},isRawResponse:!0})}(r===eJ.HANDLEDEXCEPTION||u)&&this.logger.error(c.message)}catch(e){this.logger.error(`${H}:: Failed to handle the error.`,e)}}leaveBreadcrumb(e){try{tv.reporting.breadcrumbs.value=[...tv.reporting.breadcrumbs.value,{type:"manual",name:e,timestamp:new Date,metaData:{}}]}catch(e){this.onError(e,`${H}:: Failed to log breadcrumb.`)}}}(tM,eV),tx=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){let t=`${Q}:: Plugin name is missing.`;if(!this.config.throws)return void this.logger.error(t,e);throw Error(t)}if(this.byName[e.name]){let t,i=(t=e.name,`${Q}:: Plugin "${t}" already exists.`);if(!this.config.throws)return void this.logger.error(i);throw Error(i)}this.cache={},this.plugins=this.plugins.slice();let i=this.plugins.length;this.plugins.forEach((t,r)=>{t.deps?.includes(e.name)&&(i=Math.min(i,r))}),this.plugins.splice(i,0,e),this.byName[e.name]=e,_(e.initialize)&&e.initialize(t)}unregister(e){let t=this.byName[e];if(!t){let t=`${Q}:: Plugin "${e}" not found.`;if(!this.config.throws)return void this.logger.error(t);throw Error(t)}let i=this.plugins.indexOf(t);if(-1===i){let t=`${Q}:: Plugin "${e}" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.`;if(!this.config.throws)return void this.logger.error(t);throw Error(t)}this.cache={},delete this.byName[e],this.plugins=this.plugins.slice(),this.plugins.splice(i,1)}getPlugin(e){return this.byName[e]}getPlugins(e){let t=e??".";return this.cache[t]||(this.cache[t]=this.plugins.filter(e=>{if(e.deps?.some(e=>!this.byName[e])){let t,i=e.deps.filter(e=>!this.byName[e]);return this.logger.error((t=e.name,`${Q}:: Plugin "${t}" could not be loaded because some of its dependencies "${i}" do not exist.`)),!1}return"."===t||!!C(e,t)})),this.cache[t]}processRawPlugins(e){e(this.plugins),this.cache={}}invoke(e,t=!0,...i){let r=e;if(!r)throw Error("Failed to invoke plugin because the extension point name is missing.");let s=r.startsWith("!"),n=this.config.throws??r.endsWith("!");if(!(r=r.replace(/(^!|!$)/g,"")))throw Error("Failed to invoke plugin because the extension point name is invalid.");let a=r.split(".");a.pop();let o=a.join(".");return(t?this.getPlugins(r):[this.getPlugins(r)[0]]).map(e=>{let t=C(e,r);if(!_(t)||s)return t;try{return t.apply(C(e,o),i)}catch(s){let t,i;if(n)throw s;this.logger.error((t=r,i=e.name,`${Q}:: Failed to invoke the "${t}" extension point of plugin "${i}".`),s)}return null})}invokeSingle(e,...t){return this.invoke(e,!1,...t)[0]}invokeMultiple(e,...t){return this.invoke(e,!0,...t)}}(eV,{throws:!0}),tB=e=>"cloud"!==e.config.connectionMode||!0===e.config.useNativeSDKToSend||!0===e.config.useNativeSDK,tK=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],tF=["Bugsnag","ErrorReporting"],tj={rudderAnalyticsRemotePlugins:{url:()=>Promise.resolve(window.RudderStackGlobals&&window.RudderStackGlobals.app&&window.RudderStackGlobals.app.pluginsCDNPath?`${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js`:"https://cdn.rudderlabs.com/v3/modern/plugins//rsa-plugins.js"),format:"esm",from:"vite"}};async function tz(e){let t=tj[e];return t.inited?t.lib:["esm","systemjs"].includes(t.format)?new Promise((e,i)=>{("function"==typeof t.url?t.url:()=>Promise.resolve(t.url))().then(r=>{import(r).then(i=>{if(!t.inited){let e=function e(t,i){let r=Object.assign(t,i);for(let t of Object.keys(r))"object"==typeof r[t]&&"object"==typeof i[t]&&(r[t]=e(r[t],i[t]));return r}({},(globalThis.__federation_shared__||{}).default||{});i.init(e),t.lib=i,t.lib.init(e),t.inited=!0}e(t.lib)}).catch(i)})}):void 0}function tq(e,t){if(!e?.default&&t){let t=Object.create(null);return t.default=e,t.__esModule=!0,t}return e}function tH(e,t){return tz(e).then(e=>e.get(t).then(e=>e()))}let tQ=e=>{let t={};
4return e.forEach(e=>{if(tK.includes(e)){let i=(e=>{switch(e){case"BeaconQueue":return()=>tH("rudderAnalyticsRemotePlugins","./BeaconQueue").then(e=>tq(e,!0));case"CustomConsentManager":return()=>tH("rudderAnalyticsRemotePlugins","./CustomConsentManager").then(e=>tq(e,!0));case"DeviceModeDestinations":return()=>tH("rudderAnalyticsRemotePlugins","./DeviceModeDestinations").then(e=>tq(e,!0));case"DeviceModeTransformation":return()=>tH("rudderAnalyticsRemotePlugins","./DeviceModeTransformation").then(e=>tq(e,!0));case"ExternalAnonymousId":return()=>tH("rudderAnalyticsRemotePlugins","./ExternalAnonymousId").then(e=>tq(e,!0));case"GoogleLinker":return()=>tH("rudderAnalyticsRemotePlugins","./GoogleLinker").then(e=>tq(e,!0));case"KetchConsentManager":return()=>tH("rudderAnalyticsRemotePlugins","./KetchConsentManager").then(e=>tq(e,!0));case"IubendaConsentManager":return()=>tH("rudderAnalyticsRemotePlugins","./IubendaConsentManager").then(e=>tq(e,!0));case"NativeDestinationQueue":return()=>tH("rudderAnalyticsRemotePlugins","./NativeDestinationQueue").then(e=>tq(e,!0));case"OneTrustConsentManager":return()=>tH("rudderAnalyticsRemotePlugins","./OneTrustConsentManager").then(e=>tq(e,!0));case"StorageEncryption":return()=>tH("rudderAnalyticsRemotePlugins","./StorageEncryption").then(e=>tq(e,!0));case"StorageEncryptionLegacy":return()=>tH("rudderAnalyticsRemotePlugins","./StorageEncryptionLegacy").then(e=>tq(e,!0));case"StorageMigrator":return()=>tH("rudderAnalyticsRemotePlugins","./StorageMigrator").then(e=>tq(e,!0));case"XhrQueue":return()=>tH("rudderAnalyticsRemotePlugins","./XhrQueue").then(e=>tq(e,!0));default:return}})(e);i&&(t[e]=i)}}),t},tG=()=>({}),tW={...tG()};class tV{constructor(e,t,i){this.engine=e,this.errorHandler=t,this.logger=i,this.onError=this.onError.bind(this)}init(){tv.lifecycle.status.value="pluginsLoading",eS("pluginsCDNPath",tv.lifecycle.pluginsCDNPath.value),this.setActivePlugins(),this.registerLocalPlugins(),this.registerRemotePlugins(),this.attachEffects()}attachEffects(){eH(()=>{(0===tv.plugins.activePlugins.value.length||tv.plugins.loadedPlugins.value.length+tv.plugins.failedPlugins.value.length===tv.plugins.totalPluginsToLoad.value)&&eA(()=>{tv.plugins.ready.value=!0,tv.lifecycle.status.value="pluginsReady"})})}getPluginsToLoadBasedOnConfig(){let e=tv.plugins.pluginsToLoadFromConfig.value;return e?(e=e.filter(e=>{if(tF.includes(e))return this.logger.warn(`${z}:: ${e} plugin is deprecated. Please exclude it from the load API options.`),!1;return!0}),[{configurationStatus:()=>S(tv.dataPlaneEvents.eventsQueuePluginName.value),configurationStatusStr:"Data plane events delivery is enabled",activePluginName:tv.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(tr),shouldAddMissingPlugins:!0},{configurationStatus:()=>tv.nativeDestinations.configuredDestinations.value.filter(tB).length>0,configurationStatusStr:"Device mode destinations are connected to the source",supportedPlugins:["DeviceModeDestinations","NativeDestinationQueue"]},{configurationStatus:()=>tv.nativeDestinations.configuredDestinations.value.filter(tB).some(e=>e.shouldApplyDeviceModeTransformation),configurationStatusStr:"Device mode transformations are enabled for at least one destination",supportedPlugins:["DeviceModeTransformation"]},{configurationStatus:()=>S(tv.consents.activeConsentManagerPluginName.value),configurationStatusStr:"Consent management is enabled",activePluginName:tv.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(tt)},{configurationStatus:()=>S(tv.storage.encryptionPluginName.value),configurationStatusStr:"Storage encryption is enabled",activePluginName:tv.storage.encryptionPluginName.value,supportedPlugins:Object.values(ti)},{configurationStatus:()=>tv.storage.migrate.value,configurationStatusStr:"Storage migration is enabled",supportedPlugins:["StorageMigrator"]}].forEach(t=>{t.configurationStatus()?(e=e.filter(t.activePluginName?e=>!(e!==t.activePluginName&&t.supportedPlugins.includes(e)):e=>S(e)),this.addMissingPlugins(t,!1,e)):e=e.filter(void 0!==t.basePlugins?e=>!(t.basePlugins.includes(e)||t.supportedPlugins.includes(e)):e=>!t.supportedPlugins.includes(e))}),[...Object.keys(tG()),...e]):[]}addMissingPlugins(e,t,i){let r=e.shouldAddMissingPlugins||t,s=(e.activePluginName?[...e.basePlugins||[],e.activePluginName]:[...e.supp
4ortedPlugins]).filter(e=>!i.includes(e));if(s.length>0){var n;let t,a,o;r&&i.push(...s),this.logger.warn((n=e.configurationStatusStr,a=(t=1===s.length)?` '${s[0]}' plugin was`:` ['${s.join("', '")}'] plugins were`,o=`${z}:: ${n}, but${a} not configured to load.`,r?`${o} So, ${t?"the plugin":"those plugins"} will be loaded automatically.`:`${o} Ignore if this was intentional. Otherwise, consider adding ${t?"it":"them"} to the 'plugins' load API option.`))}}setActivePlugins(){let e=this.getPluginsToLoadBasedOnConfig(),t=[...Object.keys(tW),...tK],i=[],r=[];e.forEach(e=>{t.includes(e)?i.push(e):r.push(e)}),r.length>0&&this.logger.warn(`${z}:: Ignoring unknown plugins: ${r.join(", ")}.`),eA(()=>{tv.plugins.totalPluginsToLoad.value=e.length,tv.plugins.activePlugins.value=i,tv.plugins.failedPlugins.value=r})}registerLocalPlugins(){Object.values(tW).forEach(e=>{_(e)&&tv.plugins.activePlugins.value.includes(e().name)&&this.register([e()])})}registerRemotePlugins(){let e,t={...(e=tv.plugins.activePlugins.value,tQ?.(e)||{})};Promise.all(Object.keys(t).map(async e=>{await t[e]().then(e=>this.register([e.default()])).catch(t=>{tv.plugins.failedPlugins.value=[...tv.plugins.failedPlugins.value,e],this.onError(t,e)})})).catch(e=>{this.onError(e)})}invokeMultiple(e,...t){try{return this.engine.invokeMultiple(e,...t)}catch(t){return this.onError(t,e),[]}}invokeSingle(e,...t){try{return this.engine.invokeSingle(e,...t)}catch(t){return this.onError(t,e),null}}register(e){e.forEach(e=>{try{this.engine.register(e,tv)}catch(t){tv.plugins.failedPlugins.value=[...tv.plugins.failedPlugins.value,e.name],this.onError(t)}})}unregisterLocalPlugins(){Object.values(tW).forEach(e=>{try{this.engine.unregister(e().name)}catch(e){this.onError(e)}})}onError(e,t){this.errorHandler.onError(e,z,t)}}let tJ="cookieStorage",tX="localStorage",tZ="sessionStorage",tY="memoryStorage",t0="none",t1={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"},t2="clientDataInCookie",t6="clientDataInLocalStorage",t3="clientDataInSessionStorage",t8=["userId","userTraits","anonymousId","groupId","groupTraits","initialReferrer","initialReferringDomain","sessionInfo","authToken"],t5={[tJ]:t2,[tX]:t6,[tY]:"clientDataInMemory",[tZ]:t3},t4=(e,t)=>{try{return encodeURIComponent(e)}catch(e){t?.error("Failed to encode the cookie data.",e);return}},t9=e=>{try{return decodeURIComponent(e)}catch(e){return}},t7=()=>{let e,t,i;return t={},(i=globalThis.document.cookie.split(/\s*;\s*/))[0]&&i.forEach(i=>{let r=(e=i.split("="))[0]?t9(e[0]):void 0;r&&(t[r]=e[1]?t9(e[1]):void 0)}),t},ie=function(e,t,i,r){switch(arguments.length){case 4:case 3:case 2:let s={...i||{}},n=`${t4(e,r)}=${t4(t,r)}`;null===t&&(s.maxage=-1),s.maxage&&(s.expires=new Date(+new Date+s.maxage)),s.path&&(n+=`; path=${s.path}`),s.domain&&(n+=`; domain=${s.domain}`),s.expires&&(n+=`; expires=${s.expires.toUTCString()}`),s.samesite&&(n+=`; samesite=${s.samesite}`),s.secure&&(n+="; secure"),globalThis.document.cookie=n;return;case 1:if(e)return t7()[e];return t7();default:return t7()}},it=new class{isEnabled=!0;length=0;data={};constructor(e){this.options={enabled:!0},this.logger=e}configure(e){return this.options=E(this.options,e??{}),this.isEnabled=!!this.options.enabled,this.options}setItem(e,t){return this.data[e]=t,this.length=Object.keys(this.data).length,t}getItem(e){return e in this.data?this.data[e]:null}removeItem(e){return e in this.data&&delete this.data[e],this.length=Object.keys(this.data).length,null}clear(){this.data={},this.length=0}key(e){return this.keys()[e]??null}keys(){return Object.keys(this.data)}}(eV);var ii={exports:{}};ii.exports;let ir=tb(c?ii.exports:(c=1,ii.exports=function(){function e(e){return e=JSON.stringify(e),!!/^\{[\s\S]*\}$/.test(e)}function t(e){if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}}function i(e){return"[object Function]"===({}).toString.call(e)}var r=function(e){var t="_Is_Incognit";try{e||(e=window.localStorage),e.setItem(t,"yes"),e.removeItem(t)}catch(t){var i={};i._data={},i.setItem=function(e,t){return i._data[e]=String(t)},i.getItem=function(e){return i._data.hasOwnProperty(e)?i._data[e]:void 0},i.removeItem=function(e){return delete i._data[e]},i.clear=function(){return i._data={}},e=i}finally{"yes"===e.getItem(t)&&e.removeItem(t)}return e}();function s(){if(!(this instanceof s))return new s}s.prototype={set:function(t,i){if(t&&!e(t))r.setItem(t,void 0===i||"function"==typeof i?i+"":JSON.stringify(i));else if(e(t))for(var s in t)this.set(s,t[s]);return this},get:function(e){if(void 0===e){var i={};return this.forEach(function(e,t){return i[e]=t}),i}if("?"===e.charAt(0))return this.has(e.substr(1));var s=arguments;if(s.length>1){for(var n={},a=0,o=s.length;a<o;
4a++){var l=t(r.getItem(s[a]));this.has(s[a])&&(n[s[a]]=l)}return n}return t(r.getItem(e))},clear:function(){return r.clear(),this},remove:function(e){var t=this.get(e);return r.removeItem(e),t},has:function(e){return({}).hasOwnProperty.call(this.get(),e)},keys:function(){var e=[];return this.forEach(function(t){e.push(t)}),e},forEach:function(e){for(var t=0,i=r.length;t<i;t++){var s=r.key(t);e(s,this.get(s))}return this},search:function(e){for(var t=this.keys(),i={},r=0,s=t.length;r<s;r++)t[r].indexOf(e)>-1&&(i[t[r]]=this.get(t[r]));return i},len:function(){return r.length}};var n=null;function a(t,r){var o=arguments,l=null;if(n||(n=s()),0===o.length)return n.get();if(1===o.length){if("string"==typeof t)return n.get(t);if(e(t))return n.set(t)}if(2===o.length&&"string"==typeof t){if(!r)return n.remove(t);if(r&&"string"==typeof r)return n.set(t,r);r&&i(r)&&(l=null,l=r(t,n.get(t)),a.set(t,l))}if(2===o.length&&"[object Array]"===Object.prototype.toString.call(t)&&i(r))for(var c=0,u=t.length;c<u;c++)l=r(t[c],n.get(t[c])),a.set(t[c],l);return a}for(var o in s.prototype)a[o]=s.prototype[o];return a}
4(),ii.exports)),is=()=>{let e;return null!=(e=globalThis.navigator.userAgentData)},ia={URL:()=>!_(globalThis.URL)||!_(globalThis.URLSearchParams),Promise:()=>!_(globalThis.Promise),"Number.isNaN":()=>!_(globalThis.Number.isNaN),"Number.isInteger":()=>!_(globalThis.Number.isInteger),"Array.from":()=>!_(globalThis.Array.from),"Array.prototype.find":()=>!_(globalThis.Array.prototype.find),"Array.prototype.includes":()=>!_(globalThis.Array.prototype.includes),"String.prototype.endsWith":()=>!_(globalThis.String.prototype.endsWith),"String.prototype.startsWith":()=>!_(globalThis.String.prototype.startsWith),"String.prototype.includes":()=>!_(globalThis.String.prototype.includes),"String.prototype.replaceAll":()=>!_(globalThis.String.prototype.replaceAll),"String.fromCodePoint":()=>!_(globalThis.String.fromCodePoint),"Object.entries":()=>!_(globalThis.Object.entries),"Object.values":()=>!_(globalThis.Object.values),"Object.assign":()=>!_(globalThis.Object.assign),"Object.fromEntries":()=>!_(globalThis.Object.fromEntries),"Element.prototype.dataset":()=>{let e;return(e=globalThis.document.createElement("div")).setAttribute("data-a-b","c"),!e.dataset||"c"!==e.dataset.aB},TextEncoder:()=>!_(globalThis.TextEncoder)||!_(globalThis.TextDecoder),requestAnimationFrame:()=>!_(globalThis.requestAnimationFrame)||!_(globalThis.cancelAnimationFrame),CustomEvent:()=>!_(globalThis.CustomEvent),"navigator.sendBeacon":()=>!_(globalThis.navigator.sendBeacon),ArrayBuffer:()=>!_(globalThis.Uint8Array),Set:()=>!_(globalThis.Set),atob:()=>!_(globalThis.atob)},io=()=>({width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight}),il=e=>{let t=["QuotaExceededError","NS_ERROR_DOM_QUOTA_REACHED"].includes(e.name)||[22,1014].includes(e.code);return e instanceof DOMException&&t},ic=(e=tX,t,i)=>{let r,s,n,a=`${K}:: The "${e}" storage type is `,o="unavailable",l=!0;try{switch(e){case tY:return!0;case tJ:r=t,s="test_rudder_cookie";break;case tX:r=t??globalThis.localStorage,s="test_rudder_ls";break;case tZ:r=t??globalThis.sessionStorage,s="test_rudder_ss";break;default:return!1}if(r&&(r.setItem(s,"true"),r.getItem(s)))return r.removeItem(s),!0;l=!1}catch(e){l=!1,n=e,il(e)&&(o="full")}return l||i?.warn(`${a}${o}.`,n),!1},iu=new class{isSupportAvailable=!0;isEnabled=!0;length=0;constructor(e){this.options={enabled:!0},this.logger=e}configure(e){return this.options=E(this.options,e??{}),this.isSupportAvailable=ic(tX),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,t){ir.set(e,t),this.length=ir.len()}getItem(e){let t=ir.get(e);return void 0===t?null:t}removeItem(e){ir.remove(e),this.length=ir.len()}clear(){ir.clear(),this.length=0}key(e){return this.keys()[e]??null}keys(){return ir.keys()}}(eV),ih=new class{isSupportAvailable=!0;isEnabled=!0;length=0;constructor(e){this.options={enabled:!0},this.logger=e}configure(e){return this.options=E(this.options,e??{}),this.isSupportAvailable=ic(tZ),this.isSupportAvailable&&(this.store=globalThis.sessionStorage),this.isEnabled=!!(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;let t=this.store.getItem(e);return void 0===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(){let e=[];
4if(!this.store)return e;for(let t=0;t<this.store.length;t+=1){let i=this.store.key(t);null!==i&&e.push(i)}return e}}(eV),id=new class{isSupportAvailable=!0;isEnabled=!0;length=0;constructor(e){this.logger=e}configure(e){let t;return this.options||(this.options={maxage:31536e6,path:"/",domain:(t=`.${(e=>{let t=(e=>{let t,i="function"!=typeof globalThis.URL?((t=document.createElement("a")).href=e,t.hostname):new URL(e).hostname,r=i?.split(".")??[],s=r[r.length-1],n=[];if(4===r.length&&s&&s===parseInt(s,10).toString())return n;if(r.length<=1)return r[0]&&-1!==r[0].indexOf("localhost")?["localhost"]:n;for(let e=r.length-2;e>=0;e-=1)n.push(r.slice(e).join("."));return n})(e);for(let e=0;e<t.length;e+=1){let i=t[e],r="__tld__",s={domain:`${-1!==i.indexOf("localhost")?"":"."}${i}`};if(ie(r,1,s),ie(r))return ie(r,null,s),i}return""})(globalThis.location.href)}`)&&"."!==t?t:void 0,samesite:"Lax",enabled:!0}),this.options=E(this.options,e??{}),this.options.sameDomainCookiesOnly&&delete this.options.domain,this.isSupportAvailable=ic(tJ,this),this.isEnabled=!!(this.options.enabled&&this.isSupportAvailable),this.options}setItem(e,t){return ie(e,t,this.options,this.logger),this.length=Object.keys(ie()).length,!0}getItem(e){let t=ie(e);return void 0===t?null:t}removeItem(e){let t=this.setItem(e,null);return this.length=Object.keys(ie()).length,t}clear(){}key(e){return this.keys()[e]??null}keys(){return Object.keys(ie())}}(eV),ig=e=>{switch(e){case tX:return iu;case tZ:return ih;case tY:return it;case tJ:return id;default:return it}};class ip{constructor(e,t,i){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=i}createValidKey(e){let t,{name:i,id:r,validKeys:s,noKeyValidation:n,noCompoundKey:a}=this;return n?a?e:[i,r,e].join("."):(Object.values(s).forEach(s=>{s===e&&(t=a?e:[i,r,e].join("."))}),t)}swapQueueStoreToInMemoryEngine(){let{name:e,id:t,validKeys:i,noCompoundKey:r}=this,s=ig(tY);
4Object.keys(i).forEach(n=>{let a=this.get(i[n]),o=r?n:[e,t,n].join(".");s.setItem(o,a),this.remove(n)}),this.engine=s}set(e,t){let i=this.createValidKey(e);if(i)try{this.engine.setItem(i,this.encrypt(en(t,!1,[],this.logger)))}catch(i){if(il(i)){let i;this.logger.warn((i=`Store ${this.id}`,`${i}:: The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`)),this.swapQueueStoreToInMemoryEngine(),this.set(e,t)}else this.onError(eu(i,`Failed to save the value for "${e}" to storage`))}}get(e){let t,i=this.createValidKey(e);try{if(!i)return null;if(t=this.decrypt(this.engine.getItem(i)),null==t)return null;return JSON.parse(t)}catch(i){return this.onError(Error(`Failed to retrieve or parse data for "${e}" from storage: ${i.message}`)),"string"==typeof t&&t.startsWith("RudderEncrypt:")&&this.logger.warn(`The cookie data for ${e} seems to be encrypted using SDK versions < v3. The data is dropped. This can potentially stem from using SDK versions < v3 on other sites or web pages that can share cookies with this webpage. We recommend using the same SDK (v3) version everywhere or avoid disabling the storage data migration.`),null}}remove(e){let t=this.createValidKey(e);t&&this.engine.removeItem(t)}getOriginalEngine(){return this.originalEngine}decrypt(e){return null==e?null:this.crypto(e,"decrypt")}encrypt(e){return this.crypto(e,"encrypt")}crypto(e,t){if(!this.isEncrypted||!e||"string"!=typeof e||""===e.replace(/^\s+|\s+$/gm,""))return e;let i=`storage.${t}`,r=this.pluginsManager?this.pluginsManager.invokeSingle(i,e):e;return void 0===r?e:r??""}onError(e){this.errorHandler.onError(e,`Store ${this.id}`)}}class im{stores={};isInitialized=!1;constructor(e,t,i){this.errorHandler=t,this.logger=i,this.pluginsManager=e}init(){if(this.isInitialized)return;let e=tv.loadOptions.value,t={cookieStorageOptions:{samesite:e.sameSiteCookie,secure:e.secureCookie,domain:e.setCookieDomain,sameDomainCookiesOnly:e.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};((e={},t={},i={},r={})=>{let s;s=id.configure(e),tv.storage.cookie.value={maxage:s.maxage,path:s.path,domain:s.domain,samesite:s.samesite,expires:s.expires,secure:s.secure},iu.configure(t),it.configure(i),ih.configure(r)})(I(E(t.cookieStorageOptions??{},tv.storage.cookie?.value??{})),I(t.localStorageOptions),I(t.inMemoryStorageOptions),I(t.sessionStorageOptions)),this.initClientDataStores(),this.isInitialized=!0}initClientDataStores(){this.initializeStorageState(),[tY,tX,tJ,tZ].forEach(e=>{ig(e)?.isEnabled&&this.setStore({id:t5[e],name:t5[e],isEncrypted:!0,noCompoundKey:!0,type:e,errorHandler:this.errorHandler,logger:this.logger})})}initializeStorageState(){let e=tv.storage.type.value,t=tv.loadOptions.value.storage?.entries,i=tv.consents.postConsent.value.storage;(S(i?.type)||S(i?.entries))&&(e=i?.type,t=i?.entries);let r=!0,s={};t8.forEach(i=>{let n=t?.[i]?.type,a=((e,t)=>{let i;if(e.consents.preConsent.value.enabled)switch(e.consents.preConsent.value.storage?.strategy){case"none":i=t0;break;case"session":"sessionInfo"!==t&&(i=t0);break;case"anonymousId":"anonymousId"!==t&&(i=t0)}return i})(tv,i)??n??e??eZ,o=this.getResolvedStorageTypeForEntry(a,i);o!==t0&&(r=!1),s={...s,[i]:{type:o,key:t1[i]}}}),eA(()=>{tv.storage.type.value=e,tv.storage.entries.value=s,tv.storage.trulyAnonymousTracking.value=r})}getResolvedStorageTypeForEntry(e,t){let i,r=e;switch(e){case tX:ig(tX)?.isEnabled||(r=tY);break;case tZ:ig(tZ)?.isEnabled||(r=tY);break;case tY:case t0:break;default:r=ig(tJ)?.isEnabled?tJ:ig(tX)?.isEnabled?tX:ig(tZ)?.isEnabled?tZ:tY}return r!==e&&this.logger.warn((i=r,`StoreManager:: The storage type "${e}" is not available for entry "${t}". The SDK will initialize the entry with "${i}" storage type instead.`)),r}setStore(e){let t=ig(e.type);return this.stores[e.id]=new ip(e,t,this.pluginsManager),this.stores[e.id]}getStore(e){return this.stores[e]}}let iy=e=>{let{host:t,protocol:i}=new URL(e),r=t.split(".");return{topDomain:r.length>2?`${r[r.length-2]}.${r[r.length-1]}`:t,protocol:i}},iv=e=>e?.endsWith("/")?iv(e.substring(0,e.length-1)):e,ib=e=>{try{return new URL(e).host}catch(e){return null}},i_=e=>{if("string"!=typeof e)return!1;try{return _(globalThis.URL)&&new URL(e),e8.test(e)}catch(e){return!1}},iS="none",ik="immediate",iw=e=>A(e)||Array.isArray(e),iC=(e,t)=>{let i,r,s=[],n=[],a=!1,o=e?.enabled===!0;A(e)&&o&&({provider:r,consentManagerPluginName:i}=((e,t)=>{let{provider:i}=e,r=i?tt[i]:void 0;if(i&&!r){let e;t.error((e=i,`${F}:: The consent manager "${e}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(tt)}".`)),i=void 0}return{provider:i,consentManagerPluginName:r}})(e,t),iw(e.allowedConsentIds)&&(s=e.allowedConsentIds,a=!0),iw(e.deniedConsentIds)&&(n=e.deniedConsentIds,a=!0));let l={allowedConsentIds:s,deniedConsentIds:n};return o=o&&!!i,{provider:r,consentManagerPluginName:i,initialized:a,enabled:o,consentsData:l}},iP=(e,t,i,r,s,n,a)=>{let o;if(n){if(!i_(n))return a.error(`${F}:: The base URL "${n}" for ${e}
4 is not valid.`),null;o=iv(n)}else if(o=i,"cdn"===tv.context.app.value.installType){let e=(()=>{let e=document.querySelector("script[data-rsa-write-key]");if(e&&e.dataset.rsaWriteKey===tv.lifecycle.writeKey.value)return e.src;let t=document.getElementsByTagName("script"),i=/(?:^|\/)rsa(\.min)?\.js$/;for(let e of t){let t=e.getAttribute("src");if(t&&i.test(t))return t}})();e&&(o=e.split("/").slice(0,-1).concat(t).join("/"))}return s&&(o=o.replace(RegExp(`/v3/${e5}/${t}$`),`/${r}/${e5}/${t}`)),o};class iT{constructor(e,t,i){this.errorHandler=t,this.logger=i,this.httpClient=e,this.onError=this.onError.bind(this),this.processConfig=this.processConfig.bind(this)}attachEffects(){eH(()=>{this.logger.setMinLogLevel(tv.lifecycle.logLevel.value)})}init(){let e,{logLevel:t,configUrl:i,lockIntegrationsVersion:r,lockPluginsVersion:s,destSDKBaseURL:n,pluginsSDKBaseURL:a,integrations:o}=tv.loadOptions.value,l=iP("integrations",e6,e9,eg,r,n,this.logger);null!==l&&null!==(e=iP("plugins",e3,e7,eg,s,a,this.logger))&&(this.attachEffects(),tv.lifecycle.activeDataplaneUrl.value=iv(tv.lifecycle.dataPlaneUrl.value),(e=>{let t,i,{storage:r}=tv.loadOptions.value,s=r?.type;if(S(s)&&!("string"==typeof(t=s)&&eX.includes(t))){let t;e.warn((t=s,`${F}:: The storage type "${t}" is not supported. Please choose one of the following supported types: "${eX}". The default type "${eZ}" will be used instead.`)),s=eZ}let n=r?.encryption?.version,a=n&&ti[n];if(void 0===n||void 0!==a)void 0===n&&(n="v3");else{let t;e.warn((t=n,`${F}:: The storage encryption version "${t}" is not supported. Please choose one of the following supported versions: "${Object.keys(ti)}". The default version "v3" will be used instead.`)),n="v3"}let o=r?.migrate,l=o&&"v3"===n;!0===o&&l!==o&&e.warn((i=n,`${F}:: The storage data migration has been disabled because the configured storage encryption version (${i}) is not the latest (v3). To enable storage data migration, please update the storage encryption version to the latest version.`));let{sscEnabled:c,finalDataServiceUrl:u,cookieOptions:h}=(e=>{let t,{useServerSideCookies:i,dataServiceEndpoint:r,storage:s,setCookieDomain:n,sameDomainCookiesOnly:a}=tv.loadOptions.value,o=s?.cookie,l=!1;if(i){var c;let s,u;l=i;let h=o.domain??n,d=S(h)&&!(e=>{let{topDomain:t}=iy(window.location.href);return t===e})(h.replace(/^\.+/,""))||a,g=(c=r??"rsaRequest",s=d?window.location.origin:(e=>{let{topDomain:t,protocol:i}=iy(e);return`${i}//${t}`})(window.location.href),u=c.startsWith("/")?c.substring(1):c,`${s}/${u}`);if(i_(g)){t=iv(g);let i=ib(window.location.href),r=ib(g);(i!==r&&(o={...o,samesite:"None",secure:!0}),!a&&d&&r!==h.replace(/^\.+/,""))&&(l=!1,e.warn(`${F}:: The provided cookie domain (${h}) does not match the current webpage's domain (${r}). Hence, the cookies will be set client-side.`))}else l=!1}return{sscEnabled:l,cookieOptions:o,finalDataServiceUrl:t}})(e);eA(()=>{tv.storage.type.value=s,tv.storage.cookie.value=h,tv.serverCookies.isEnabledServerSideCookies.value=c,tv.serverCookies.dataServiceUrl.value=u,tv.storage.encryptionPluginName.value=ti[n],tv.storage.migrate.value=l})})(this.logger),(e=>{let{provider:t,consentManagerPluginName:i,initialized:r,enabled:s,consentsData:n}=iC(tv.loadOptions.value.consentManagement,e),a=tv.loadOptions.value.preConsent,o=a?.storage?.strategy??iS;if(S(o)&&!["none","session","anonymousId"].includes(o)){let t;o=iS,e.warn((t=a?.storage?.strategy,`${F}:: The pre-consent storage strategy "${t}" is not supported. Please choose one of the following supported strategies: "none, session, anonymousId". The default strategy "${iS}" will be used instead.`))}let l=a?.events?.delivery??ik;if(S(l)&&!["immediate","buffer"].includes(l)){let t;l=ik,e.warn((t=a?.events?.delivery,`${F}:: The pre-consent events delivery type "${t}" is not supported. Please choose one of the following supported types: "immediate, buffer". The default type "${ik}" will be used instead.`))}eA(()=>{tv.consents.activeConsentManagerPluginName.value=i,tv.consents.initialized.value=r,tv.consents.enabled.value=s,tv.consents.data.value=n,tv.consents.provider.value=t,tv.consents.preConsent.value={enabled:tv.loadOptions.value.preConsent?.enabled===!0&&!1===r&&!0===s,storage:{strategy:o},events:{delivery:l}}})})(this.logger),(e=>{if(tv.dataPlaneEvents.deliveryEnabled.value){let t="XhrQueue",i=t;if(tv.loadOptions.value.useBeacon)if(tv.capabilities.isBeaconAvailable.value)i="BeaconQueue";else i=t,e.warn(`${F}:: The Beacon API is not supported by your browser. The events will be sent using XHR instead.`);eA(()=>{tv.dataPlaneEvents.eventsQueuePluginName.value=i})}})(this.logger),eA(()=>{tv.lifecycle.integrationsCDNPath.value=l,tv.lifecycle.pluginsCDNPath.value=e,t&&(tv.lifecycle.logLevel.value=t),tv.lifecycle.sourceConfigUrl.value=((e,t,i,r,s)=>{let n=new URLSearchParams({p:"npm",v:eg,build:e5,writeKey:t,lockIntegrationsVersion:i.toString(),lockPluginsVersion:r.toString()}),a=te,o=n,l="/sourceConfig/",c="";if(i_(e)){let t=new URL(e);iv(t.pathname).endsWith("/sourceConfig")||(t.pathname=`${iv(t.pathname)}
4/sourceConfig/`),t.pathname=t.pathname.replace(/\/{2,}/g,"/"),n.forEach((e,i)=>{null===t.searchParams.get(i)&&t.searchParams.set(i,e)}),a=t.origin,l=t.pathname,o=t.searchParams,c=t.hash}else s.warn(`${F}:: The provided source config URL "${e}" is invalid. Using the default source config URL instead.`);return`${a}${l}?${o}${c}`})(i,tv.lifecycle.writeKey.value,r,s,this.logger),tv.metrics.metricsServiceUrl.value=`${tv.lifecycle.activeDataplaneUrl.value}/rsaMetrics`,tv.nativeDestinations.loadOnlyIntegrations.value=o}),this.getConfig())}onError(e,t){this.errorHandler.onError(e,F,t)}processConfig(e,t){var i,r;let s,n,a,o,l,c;if(!S(e))return void(S(t)?this.onError(t.error,e0):this.onError(Error(e0)));try{s="string"==typeof e?JSON.parse(e):e}catch(e){this.onError(e,eY);return}if(!(P(n=s)&&P(n.source)&&null!=(c=n.source.id)&&P(n.source.config)&&Array.isArray(n.source.destinations)))return void this.onError(Error(eY));if(!1===s.source.enabled)return void this.logger.error("The source is disabled. Please enable the source in the dashboard to send events.");i=s,tv.reporting.isErrorReportingEnabled.value=(a=i.source.config,a?.statsCollection?.errors?.enabled===!0&&!window.chrome?.runtime?.id),tv.reporting.isMetricsReportingEnabled.value=(o=i.source.config,o?.statsCollection?.metrics?.enabled===!0);let u=s.source.destinations.length>0?(r=s.source.destinations,l=[],r.forEach(e=>{e.enabled&&!e.deleted&&l.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}`})}),l):[];eA(()=>{var e;let t,i;tv.source.value={config:s.source.config,name:s.source.name,id:s.source.id,workspaceId:s.source.workspaceId},tv.nativeDestinations.configuredDestinations.value=u,tv.plugins.pluginsToLoadFromConfig.value=tv.loadOptions.value.plugins??[],e=s,i=tv.consents.resolutionStrategy.value,P(e.consentManagementMetadata)&&(tv.consents.provider.value&&(i=e.consentManagementMetadata.providers.find(e=>e.provider===tv.consents.provider.value)?.resolutionStrategy??tv.consents.resolutionStrategy.value),t=e.consentManagementMetadata),"custom"===tv.consents.provider.value&&(i=void 0),eA(()=>{tv.consents.metadata.value=p(t),tv.consents.resolutionStrategy.value=i}),tv.lifecycle.status.value="configured"})}getConfig(){let e=tv.loadOptions.value.getSourceConfig;if(e){if(!_(e))return void this.logger.error(`${F}:: The "getSourceConfig" load API option must be a function that returns valid source configuration data.`);let t=e();t instanceof Promise?t.then(e=>this.processConfig(e)).catch(e=>{this.onError(e,"SourceConfig")}):this.processConfig(t)}else this.httpClient.getAsyncData({url:tv.lifecycle.sourceConfigUrl.value,options:{headers:{"Content-Type":void 0}},callback:this.processConfig})}}let iE=()=>document?.referrer||"$direct",iA=()=>{let e=(()=>{let e=document.getElementsByTagName("link"),t="";for(let i=0;e[i];i+=1){let r=e[i];if("canonical"===r.getAttribute("rel")&&!t){t=r.getAttribute("href")??"";break}}return t})(),t=globalThis.location.pathname,{href:i}=globalThis.location,r=i,{search:s}=globalThis.location;if(e)try{let i=new URL(e);r=""===i.search?e+s:e,t=i.pathname}catch(e){}let n=(e=>{let t=e;try{let i=new URL(e);t=i.origin+i.pathname+i.search}catch(e){}return t})(r),{title:a}=document,o=iE();return{path:t,referrer:o,referring_domain:ib(o)??"",search:s,title:a,url:n,tab_url:i}},iI=`https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=${Object.keys(ia).join("%2C")}`,iD="rudderstackPolyfill";class iO{constructor(e,t,i){this.httpClient=e,this.errorHandler=t,this.logger=i,this.externalSrcLoader=new eP(this.errorHandler,this.logger),this.onError=this.onError.bind(this),this.onReady=this.onReady.bind(this)}init(){this.prepareBrowserCapabilities(),this.attachWindowListeners()}detectBrowserCapabilities(){eA(()=>{let e,t,i;tv.capabilities.storage.isCookieStorageAvailable.value=ic(tJ,ig(tJ),this.logger),tv.capabilities.storage.isLocalStorageAvailable.value=ic(tX,void 0,this.logger),tv.capabilities.storage.isSessionStorageAvailable.value=ic(tZ,void 0,this.logger),tv.capabilities.isBeaconAvailable.value=null!=(t=globalThis.navigator.sendBeacon)&&_(globalThis.navigator.sendBeacon),tv.capabilities.isUaCHAvailable.value=is(),tv.capabilities.isCryptoAvailable.value=null!=(i=globalThis.crypto)&&_(globalThis.crypto.getRandomValues),tv.capabilities.isIE11.value=!!globalThis.navigator.userAgent.match(/Trident.*rv:11\./),tv.capabilities.isOnline.value=globalThis.navigator.onLine,tv.context.userAgent.value=(()=>
4{if(void 0===globalThis.navigator)return null;let{userAgent:e}=globalThis.navigator,{brave:t}=globalThis.navigator;if(t&&Object.getPrototypeOf(t).isBrave){let t=e.match(/(chrome)\/([\w.]+)/i);t&&(e=`${e} Brave/${t[2]}`)}return e})(),tv.context.locale.value=void 0===globalThis.navigator?null:globalThis.navigator.language??globalThis.navigator.browserLanguage,tv.context.screen.value=io(),tv.context.timezone.value=(e=/([A-Z]+[+-]\d+)/.exec(new Date().toString()),e?.[1]?e[1]:"NA"),is()&&((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=>{tv.context["ua-ch"].value=e},tv.loadOptions.value.uaChTrackLevel)}),eH(()=>{var e;let t,i;!0===tv.loadOptions.value.sendAdblockPage&&void 0!==tv.lifecycle.sourceConfigUrl.value&&(e=this.httpClient,t=new URL(tv.lifecycle.sourceConfigUrl.value),i=`${t.origin}${t.pathname}?view=ad`,e.getAsyncData({url:i,options:{method:"HEAD",headers:{"Content-Type":void 0}},isRawResponse:!0,callback:(e,t)=>{tv.capabilities.isAdBlocked.value=t?.error!==void 0||t?.xhr?.responseURL!==i}}))})}prepareBrowserCapabilities(){tv.capabilities.isLegacyDOM.value=(()=>{let e=Object.keys(ia),t=!1;for(let i=0;i<e.length;i++){let r=ia[e[i]];if(_(r)&&r()){t=!0;break}}return t})();let e=tv.loadOptions.value.polyfillURL,t=iI;if(k(e))if(i_(e))t=e;else this.logger.warn(`${K}:: The provided polyfill URL "${e}" is invalid. The default polyfill URL will be used instead.`);if(tv.loadOptions.value.polyfillIfRequired&&tv.capabilities.isLegacyDOM.value&&i_(t)){let e=t!==tv.loadOptions.value.polyfillURL;if(e){let e=`RS_polyfillCallback_${tv.lifecycle.writeKey.value}`,i=()=>{this.onReady(),delete globalThis[e]};globalThis[e]=i,t=`${t}&callback=${e}`}this.externalSrcLoader.loadJSFile({url:t,id:iD,async:!0,timeout:1e4,callback:i=>{if(i)e||this.onReady();else{let e;this.onError(Error((e=t,`Failed to load the polyfill script with ID "${iD}" from URL ${e}.`)))}}})}else this.onReady()}attachWindowListeners(){globalThis.addEventListener("offline",()=>{tv.capabilities.isOnline.value=!1}),globalThis.addEventListener("online",()=>{tv.capabilities.isOnline.value=!0}),globalThis.addEventListener("resize",function(e,t,i=250){let r;return(...s)=>{globalThis.clearTimeout(r),r=globalThis.setTimeout(()=>{e.apply(t,s)},i)}}(()=>{tv.context.screen.value=io()},this))}onReady(){this.detectBrowserCapabilities(),tv.lifecycle.status.value="browserCapabilitiesReady"}onError(e){this.errorHandler.onError(e,K)}}let iR=["integrations","anonymousId","originalTimestamp"],iL=["library","consentManagement","userAgent","ua-ch","screen"],iM=["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"],i$=e=>"number"==typeof e&&!Number.isNaN(e),iN=e=>i$(e)&&e>=0&&Number.isInteger(e),iU=e=>{let t=Date.now();return!!(!e||t>e)},ix=e=>e===tJ||e===tX||e===tZ||e===tY,iB=(e,t,i)=>{P(e)&&Object.keys(e).forEach(e=>{(iM.includes(e)||iM.includes(e.toLowerCase()))&&i.warn(`${j}:: The "${e}" property defined under "${t}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${iM}).`)})},iK=(e,t,i,r)=>{var s;let n,a,o={channel:"web",context:{traits:p(tv.session.userTraits.value),sessionId:tv.session.sessionInfo.value.id||void 0,sessionStart:tv.session.sessionInfo.value.sessionStart||void 0,...tv.consents.enabled.value&&{consentManagement:{deniedConsentIds:p(tv.consents.data.value.deniedConsentIds),allowedConsentIds:p(tv.consents.data.value.allowedConsentIds),provider:tv.consents.provider.value,resolutionStrategy:tv.consents.resolutionStrategy.value}},"ua-ch":tv.context["ua-ch"].value,app:tv.context.app.value,library:tv.context.library.value,userAgent:tv.context.userAgent.value,os:tv.context.os.value,locale:tv.context.locale.value,screen:tv.context.screen.value,campaign:(e=>{let t={};try{let i=new URL(e),r="utm_";
4i.searchParams.forEach((e,i)=>{if(i.startsWith(r)){let s=i.substring(r.length);"campaign"===s&&(s="name"),t[s]=e}})}catch(e){}return t})(globalThis.location.href),page:(n=iA(),a={},Object.keys(n).forEach(e=>{a[e]=i?.[e]||n[e]}),a.initial_referrer=i?.initial_referrer||tv.session.initialReferrer.value,a.initial_referring_domain=i?.initial_referring_domain||tv.session.initialReferringDomain.value,a),timezone:tv.context.timezone.value,...tv.autoTrack.enabled.value&&{autoTrack:{...tv.autoTrack.pageLifecycle.enabled.value&&{page:{visitId:tv.autoTrack.pageLifecycle.visitId.value}}}}},originalTimestamp:new Date().toISOString(),messageId:ei(),userId:e.userId||tv.session.userId.value};ix(tv.storage.entries.value.anonymousId?.type)?o.anonymousId=tv.session.anonymousId.value:o.anonymousId=ei(),tv.storage.trulyAnonymousTracking.value&&(o.context.trulyAnonymousTracking=!0),"identify"===e.type&&(o.context.traits=tv.storage.entries.value.userTraits?.type!==t0?p(tv.session.userTraits.value):e.context.traits),"group"===e.type&&((e.groupId||tv.session.groupId.value)&&(o.groupId=e.groupId||tv.session.groupId.value),(e.traits||tv.session.groupTraits.value)&&(o.traits=tv.storage.entries.value.groupTraits?.type!==t0?p(tv.session.groupTraits.value):e.traits));let l=E(e,o);return void 0===l.event&&(l.event=null),void 0===l.properties&&(l.properties=null),((e,t,i)=>{if(P(t)){var r;let s;t.anonymousId&&"string"==typeof t.anonymousId&&(e.anonymousId=t.anonymousId),A(t.integrations)&&(e.integrations=t.integrations),t.originalTimestamp&&"string"==typeof t.originalTimestamp&&(e.originalTimestamp=t.originalTimestamp),r=e.context,s=r,Object.keys(t).forEach(e=>{if(!iR.includes(e)&&!iL.includes(e))if("context"!==e)s=E(s,{[e]:t[e]});else if(void 0!==t[e]&&P(t[e])){let i={};Object.keys(t[e]).forEach(r=>{iL.includes(r)||(i[r]=t[e][r])}),s=E(s,{...i})}else i.warn(`${j}:: Please make sure that the "context" property in the event API's "options" argument is a valid object literal with key-value pairs.`)}),e.context=s}})(l,t,r),((e,t)=>{let{properties:i,traits:r,context:s}=e,{traits:n}=s;iB(i,"properties",t),iB(r,"traits",t),iB(n,"context.traits",t)})(l,r),s=l.integrations,l.integrations=p(tv.loadOptions.value.useGlobalIntegrationsConfigInEvents?tv.consents.postConsent.value.integrations??tv.nativeDestinations.loadOnlyIntegrations.value:s||e2),l};class iF{constructor(e){this.logger=e}generatePageEvent(e,t,i,r){var s,n;let a,o,l=i??{};return iK({properties:(s=l,n=r,a=n?.page||{},Object.keys(o=iA()).forEach(e=>{void 0===s[e]&&(s[e]=a[e]||o[e])}),void 0===s.initial_referrer&&(s.initial_referrer=a.initial_referrer||tv.session.initialReferrer.value),void 0===s.initial_referring_domain&&(s.initial_referring_domain=a.initial_referring_domain||tv.session.initialReferringDomain.value),l=s),name:t,category:e,type:"page"},r,l,this.logger)}generateTrackEvent(e,t,i){return iK({properties:t,event:e,type:"track"},i,void 0,this.logger)}generateIdentifyEvent(e,t,i){return iK({userId:e,type:"identify",context:{traits:t}},i,void 0,this.logger)}generateAliasEvent(e,t,i){let r=iK({previousId:t,type:"alias"},i,void 0,this.logger);return r.userId=e??r.userId,r}generateGroupEvent(e,t,i){let r={type:"group"};return e&&(r.groupId=e),t&&(r.traits=t),iK(r,i,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 ij{constructor(e,t,i,r){this.eventRepository=e,this.userSessionManager=t,this.errorHandler=i,this.logger=r,this.eventFactory=new iF(this.logger)}init(){this.eventRepository.init()}resume(){this.eventRepository.resume()}addEvent(e){this.userSessionManager.refreshSession();let t=this.eventFactory.create(e);this.eventRepository.enqueue(t,e.callback)}}class iz{constructor(e,t,i,r,s){this.storeManager=t,this.pluginsManager=e,this.logger=s,this.errorHandler=r,this.httpClient=i,this.onError=this.onError.bind(this),this.serverSideCookieDebounceFuncs={}}init(){this.syncStorageDataToState(),this.registerEffects()}syncStorageDataToState(){let e;this.migrateStorageIfNeeded(),this.migrateDataFromPreviousStorage(),this.setUserId(this.getUserId()),this.setUserTraits(this.getUserTraits()),this.setGroupId(this.getGroupId()),this.setGroupTraits(this.getGroupTraits());let{externalAnonymousIdCookieName:t,anonymousIdOptions:i}=tv.loadOptions.value;k(t)&&"string"==typeof t&&(e=this.getExternalAnonymousIdByCookieName(t)),this.setAnonymousId(e??this.getAnonymousId(i)),this.setAuthToken(this.getAuthToken()),this.setInitialReferrerInfo(),this.configureSessionTracking()}configureSessionTracking(){let e=this.getSessionInfo();if(this.isPersistenceEnabledForStorageEntry("sessionInfo")){let t=this.getConfiguredSessionTrackingInfo(),i=e??tl;(e={...i,...t,autoTrack:t.autoTrack&&!0!==i.manualTrack}).autoTrack||!0===e.manualTrack||(e=to)}else e=to;tv.session.sessionInfo.value=e,tv.session.sessionInfo.value.autoTrack&&this.startOrRenewAutoTracking(tv.session.sessionInfo.value)}setInitialReferrerInfo(){let e=this.getInitialReferrer(),t=this.getInitialReferringDomain();if(e&&t)this.setInitialReferrer(e),this.setInitialReferringDomain(t);else{let t=e||iE();this.setInitialReferrer(t),this.setInitialReferringDomain(ib(t)??"")}}isPersistenceEnabledForStorageEntry(e){return ix(tv.storage.entries.value[e]?.type)}migrateDataFromPreviousStorage(){let e=tv.storage.entries.value,t=[tJ,tX,tZ];Object.keys(e).forEach(i=>
4{let r=e[i]?.type,s=this.storeManager?.getStore(t5[r]);s&&t.forEach(e=>{let t=this.storeManager?.getStore(t5[e]);if(t&&e!==r){let e=t.get(t1[i]);k(e)&&""!==e&&s.set(t1[i],e),t.remove(t1[i])}})})}migrateStorageIfNeeded(){if(!tv.storage.migrate.value)return;let e=[];[t2,t6,t3].forEach(t=>{let i=this.storeManager?.getStore(t);i&&e.push(i)}),Object.keys(t1).forEach(t=>{let i=t1[t];e.forEach(e=>{let t=this.pluginsManager?.invokeSingle("storage.migrate",i,e.engine,this.errorHandler,this.logger);null==t||e.set(i,t)})})}getConfiguredSessionTrackingInfo(){let e,t,i=tv.loadOptions.value.sessions?.autoTrack!==!1;if(!i)return{autoTrack:i};let r=tv.loadOptions.value.sessions?.timeout;if(iN(r))t=r;else this.logger.warn(`${q}:: The session timeout value "${r}" is not a number. The default timeout of 1800000 ms will be used instead.`),t=18e5;0===t&&(this.logger.warn(`${q}:: 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.`),i=!1);return t>0&&t<1e4&&this.logger.warn((e=t,`${q}:: The session timeout value ${e} ms is less than the recommended minimum of 10000 ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`)),{timeout:t,autoTrack:i}}onError(e,t){this.errorHandler.onError(e,q,t)}getEncryptedCookieData(e,t){let i=[];return e.forEach(e=>{let r=t?.encrypt(en(e.value,!1,[],this.logger));k(r)&&i.push({name:e.name,value:r})}),i}makeRequestToSetCookie(e,t){this.httpClient?.getAsyncData({url:tv.serverCookies.dataServiceUrl.value,options:{method:"POST",data:en({reqType:"setCookies",workspaceId:tv.source.value?.workspaceId,data:{options:{maxAge:tv.storage.cookie.value?.maxage,path:tv.storage.cookie.value?.path,domain:tv.storage.cookie.value?.domain,sameSite:tv.storage.cookie.value?.samesite,secure:tv.storage.cookie.value?.secure,expires:tv.storage.cookie.value?.expires},cookies:e}}),sendRawData:!0,withCredentials:!0},isRawResponse:!0,callback:t})}setServerSideCookies(e,t,i){try{let r=this.getEncryptedCookieData(e,i);r.length>0&&this.makeRequestToSetCookie(r,(r,s)=>{if(s?.xhr?.status===200)e.forEach(e=>{let r=i?.get(e.name),s=en(e.value,!1,[]);if(en(r,!1,[])!==s){let i;this.logger.error((i=e.name,`The server failed to set the ${i} cookie. As a fallback, the cookies will be set client side.`)),t&&t(e.name,e.value)}});else{let i;this.logger.error((i=s?.xhr?.status,`The server responded with status ${i} while setting the cookies. As a fallback, the cookies will be set client side.`)),e.forEach(e=>{t&&t(e.name,e.value)})}})}catch(i){this.onError(i,"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){let i=tv.storage.entries.value,r=i[e]?.type;if(ix(r)){let s=this.storeManager?.getStore(t5[r]),n=i[e]?.key;t&&("string"==typeof t||A(t))?tv.serverCookies.isEnabledServerSideCookies.value&&r===tJ?(this.serverSideCookieDebounceFuncs[e]&&globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[e]),this.serverSideCookieDebounceFuncs[e]=globalThis.setTimeout(()=>{this.setServerSideCookies([{name:n,value:t}],(e,t)=>{s?.set(e,t)},s)},10)):s?.set(n,t):s?.remove(n)}}registerEffects(){t8.forEach(e=>{eH(()=>{this.syncValueToStorage(e,tv.session[e].value)})})}setAnonymousId(e,t){let i=e;"string"==typeof e&&i||(i=void 0),this.isPersistenceEnabledForStorageEntry("anonymousId")?(!i&&t&&(i=this.pluginsManager?.invokeSingle("userSession.anonymousIdGoogleLinker",t)),i=i||ei()):i="",tv.session.anonymousId.value=i}getAnonymousId(e){if(ix(tv.storage.entries.value.anonymousId?.type)){let t=this.getEntryValue("anonymousId");!t&&e&&(t=this.pluginsManager?.invokeSingle("storage.getAnonymousId",ig,e)),tv.session.anonymousId.value=t||ei()}return tv.session.anonymousId.value}getEntryValue(e){let t=tv.storage.entries.value,i=t[e]?.type;if(ix(i)){let r=this.storeManager?.getStore(t5[i]),s=t[e]?.key;return r?.get(s)??null}return null}getExternalAnonymousIdByCookieName(e){let t=ig(tJ);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(){let e=this.getSessionInfo()??to;return e.autoTrack&&!iU(e.expiresAt)||e.manualTrack?e.id??null:null}refreshSession(){let e=this.getSessionInfo()??to;(e.autoTrack||e.manualTrack)&&(e.autoTrack&&(this.startOrRenewAutoTracking(e),e=tv.session.sessionInfo.value),void 0===e.sessionStart?e={...e,sessionStart:!0}:e.sessionStart&&(e={...e,sessionStart:!1})),tv.session.sessionInfo.value=e,"readyExecuted"!==tv.lifecycle.status.value&&this.syncValueToStorage("sessionInfo",e)}reset(e,t){let{session:i}=tv,{manualTrack:r,autoTrack:s}=i.sessionInfo.value;eA(()=>{i.userId.value="",i.userTraits.value=tn,i.groupId.value="",i.groupTraits.value=ta,i.authToken.value=null,!0===e&&this.setAnonymousId(),!t&&(s?(i.sessionInfo.value=to,this.startOrRenewAutoTracking(i.sessionInfo.value)):r&&this.startManualTrackingInternal())})}setUserId(e){tv.session.userId.value=this.isPersistenceEnabledForStorageEntry("userId")&&e?e:""}setUserTraits(e){tv.session.userTraits.value=this.isPersistenceEnabledForStorageEntry("userTraits")&&P(e)?E(tv.session.userTraits.value??tn,e):tn}setGroupId(e){tv.session.groupId.value=this.isPersistenceEnabledForStorageEntry("groupId")&&e?e:""}setGroupTraits(e){tv.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry("groupTraits")&&P(e)?E(tv.session.groupTraits.value??ta,e):ta}setInitialReferrer(e){tv.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry("initialReferrer")&&e?e:""}setInitialReferringDomain(e){tv.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry("initialReferringDomain")&&e?e:""}startOrRenewAutoTracking(e){if(iU(e.expiresAt)){var t;let i,r;tv.session.sessionInfo.value=(t=e.timeout,i=Date.now(),{id:i,expiresAt:i+(r=t||18e5),timeout:r,sessionStart:void 0,autoTrack:!0})}else{let t=Date.now(),i=e.timeout;tv.session.sessionInfo.value=E(e,{expiresAt:t+i})}}start(e){tv.session.sessionInfo.value={id:((e,t)=>{if(!e||!iN(e)||!(e.toString().length>=10))return t.warn(`${q}:: The provided session ID (${e}) is either invalid, not a positive integer, or not at least "10" digits long. A new session ID will be auto-generated instead.`),!1;return!0})(e,this.logger)?e:Date.now(),sessionStart:void 0,manualTrack:!0}}startManualTrackingInternal(){this.start(Date.now())}end(){tv.session.sessionInfo.value=to}setAuthToken(e){tv.session.authToken.value=this.isPersistenceEnabledForStorageEntry("authToken")&&e?e:null}}let iq=["BeaconQueue","CustomConsentManager","DeviceModeDestinations","DeviceModeTransformation","ExternalAnonymousId","GoogleLinker","IubendaConsentManager","KetchConsentManager","NativeDestinationQueue","OneTrustConsentManager","StorageEncryption","StorageEncryptionLegacy","StorageMigrator","XhrQueue"],iH="dataplaneEventsQueue",iQ="destinationsEventsQueue",iG=(e,t,i,r)=>{if(S(e))if(_(e))try{e(...t)}catch(e){r.error(`${i}:: The callback threw an exception`,e)}else r.error(e1(i))};class iW{constructor(e,t,i,r,s){this.pluginsManager=e,this.errorHandler=r,this.httpClient=i,this.logger=s,this.storeManager=t}init(){let e;this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${iH}.init`,tv,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.dmtEventsQueue=this.pluginsManager.invokeSingle("transformEvent.init",tv,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger),this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${iQ}.init`,tv,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger),eH(()=>{!0===tv.nativeDestinations.clientDestinationsReady.value&&(this.destinationsEventsQueue?.start(),this.dmtEventsQueue?.start())});let t=tv.consents.preConsent.value.enabled&&tv.consents.preConsent.value.events?.delivery==="buffer"&&(tv.consents.preConsent.value.storage?.strategy==="session"||tv.consents.preConsent.value.storage?.strategy==="none");eH(()=>{let i=!0===tv.loadOptions.value.bufferDataPlaneEventsUntilReady&&!1===tv.nativeDestinations.clientDestinationsReady.value;!1!==tv.nativeDestinations.activeDestinations.value.some(e=>"hybrid"===e.config.connectionMode||!0===e.config.useNativeSDKToSend)&&!1!==i||t||this.dataplaneEventsQueue?.scheduleTimeoutActive===!0||(globalThis.clearTimeout(e),this.dataplaneEventsQueue?.start())}),!0===tv.loadOptions.value.bufferDataPlaneEventsUntilReady&&(e=globalThis.setTimeout(()=>{this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&this.dataplaneEventsQueue?.start()},tv.loadOptions.value.dataPlaneEventsBufferTimeout))}resume(){this.dataplaneEventsQueue?.scheduleTimeoutActive!==!0&&(tv.consents.postConsent.value.discardPreConsentEvents&&(this.dataplaneEventsQueue?.clear(),this.destinationsEventsQueue?.clear()),this.dataplaneEventsQueue?.start())}enqueue(e,t){let i,r,s,n,a=(i=p(e),r=tv.nativeDestinations.integrationsConfig.value,s=e.integrations,n=Object.keys(s).filter(e=>!0!==s[e]||!r[e]).reduce((e,t)=>
4{let i=p(e);return i[t]=s[t],i},{}),i.integrations=E(r,n),i);this.pluginsManager.invokeSingle(`${iH}.enqueue`,tv,this.dataplaneEventsQueue,a,this.errorHandler,this.logger);let o=p(e);this.pluginsManager.invokeSingle(`${iQ}.enqueue`,tv,this.destinationsEventsQueue,o,this.errorHandler,this.logger),iG(t,[a],`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}API`,this.logger)}}let iV=e=>{let t=new CustomEvent(e,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:!0,cancelable:!0,composed:!0});globalThis.document.dispatchEvent(t)};class iJ{constructor(){this.preloadBuffer=new eQ,this.initialized=!1,this.errorHandler=tU,this.logger=eV,this.externalSrcLoader=new eP(this.errorHandler,this.logger),this.httpClient=tM,this.httpClient.init(this.errorHandler),this.capabilitiesManager=new iO(this.httpClient,this.errorHandler,this.logger)}load(e,t,i={}){if(!tv.lifecycle.status.value){let r;if(!("string"==typeof(r=e)&&r.trim().length>0))return void this.logger.error(`${W}:: The write key "${e}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`);if(!i_(t))return void this.logger.error(`${W}:: 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.`);eA(()=>{var r;let s;tv.lifecycle.writeKey.value=p(e),tv.lifecycle.dataPlaneUrl.value=p(t),tv.loadOptions.value=(r=tv.loadOptions.value,"string"!=typeof(s=p(i)).setCookieDomain&&(s.setCookieDomain=void 0),["Strict","Lax","None"].includes(s.sameSiteCookie)||(s.sameSiteCookie=void 0),s.secureCookie=R(s.secureCookie,r.secureCookie),s.sameDomainCookiesOnly=R(s.sameDomainCookiesOnly,r.sameDomainCookiesOnly),["none","default","full"].includes(s.uaChTrackLevel)||(s.uaChTrackLevel=void 0),s.integrations=O(s.integrations),Array.isArray(s.plugins)||(s.plugins=iq),s.useGlobalIntegrationsConfigInEvents=R(s.useGlobalIntegrationsConfigInEvents,r.useGlobalIntegrationsConfigInEvents),s.bufferDataPlaneEventsUntilReady=R(s.bufferDataPlaneEventsUntilReady,r.bufferDataPlaneEventsUntilReady),s.sendAdblockPage=R(s.sendAdblockPage,r.sendAdblockPage),s.useServerSideCookies=R(s.useServerSideCookies,r.useServerSideCookies),"string"!=typeof s.dataServiceEndpoint&&(s.dataServiceEndpoint=void 0),s.sendAdblockPageOptions=O(s.sendAdblockPageOptions),s.loadIntegration=R(s.loadIntegration,r.loadIntegration),A(s.storage)?(s.storage.migrate=R(s.storage.migrate,r.storage?.migrate),s.storage.cookie=O(s.storage.cookie),s.storage.encryption=O(s.storage.encryption),s.storage=D(s.storage)):s.storage=void 0,s.destinationsQueueOptions=O(s.destinationsQueueOptions),s.queueOptions=O(s.queueOptions),s.lockIntegrationsVersion=R(s.lockIntegrationsVersion,r.lockIntegrationsVersion),s.lockPluginsVersion=R(s.lockPluginsVersion,r.lockPluginsVersion),i$(s.dataPlaneEventsBufferTimeout)||(s.dataPlaneEventsBufferTimeout=void 0),s.beaconQueueOptions=O(s.beaconQueueOptions),s.preConsent=O(s.preConsent),E(r,D(s))),tv.lifecycle.status.value="mounted"}),this.logger.setMinLogLevel(tv.loadOptions.value.logLevel??eW),eS("state",tv,e),this.startLifecycle()}}startLifecycle(){eH(()=>{try{switch(tv.lifecycle.status.value){case"mounted":this.onMounted();break;case"browserCapabilitiesReady":this.onBrowserCapabilitiesReady();break;case"configured":this.onConfigured();break;case"pluginsLoading":case"destinationsLoading":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){this.errorHandler.onError(eu(e,"Failed to load the SDK"),W)}})}onBrowserCapabilitiesReady(){let e;((e=[])=>{let t=new URLSearchParams(globalThis.location.search);t.get(ev)&&e.unshift(["track",t.get(ev),ew(t,"ajs_prop_")]),t.get(ey)&&e.unshift(["identify",t.get(ey),ew(t,"ajs_trait_")]),t.get(em)&&e.unshift(["setAnonymousId",t.get(em)])})(e=ek(ef)||[]),e.length>0&&(this.enqueuePreloadBufferEvents(e),eS(ef,[])),this.prepareInternalServices(),this.loadConfig()}onLoaded(){this.processBufferedEvents(),!0===tv.consents.preConsent.value.enabled?tv.lifecycle.status.value="ready":this.loadDestinations()}onMounted(){this.capabilitiesManager.init()}
4enqueuePreloadBufferEvents(e){Array.isArray(e)&&e.forEach(e=>this.preloadBuffer.enqueue(p(e)))}processDataInPreloadBuffer(){for(;this.preloadBuffer.size()>0;){let e=this.preloadBuffer.dequeue();e&&eC([...e],this)}}prepareInternalServices(){this.pluginsManager=new tV(tx,this.errorHandler,this.logger),this.storeManager=new im(this.pluginsManager,this.errorHandler,this.logger),this.configManager=new iT(this.httpClient,this.errorHandler,this.logger),this.userSessionManager=new iz(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventRepository=new iW(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger),this.eventManager=new ij(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger)}loadConfig(){tv.lifecycle.writeKey.value&&this.httpClient.setAuthHeader(tv.lifecycle.writeKey.value),this.configManager?.init()}onPluginsReady(){this.storeManager?.init(),this.userSessionManager?.init(),tv.consents.enabled.value&&!tv.consents.initialized.value&&(this.pluginsManager?.invokeSingle("consentManager.init",tv,this.logger),!1===tv.consents.preConsent.value.enabled&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",tv,this.storeManager,this.logger)),this.eventManager?.init(),tv.lifecycle.status.value="initialized"}onConfigured(){this.pluginsManager?.init()}onInitialized(){this.processDataInPreloadBuffer(),iG(tv.loadOptions.value.onLoaded,[globalThis.rudderanalytics],"LoadAPI",this.logger),eA(()=>{tv.lifecycle.loaded.value=!0,tv.lifecycle.status.value="loaded"}),this.initialized=!0,iV("RSA_Initialised")}onReady(){tv.lifecycle.status.value="readyExecuted",tv.eventBuffer.readyCallbacksArray.value.forEach(e=>{iG(e,[],G,this.logger)}),iV("RSA_Ready")}processBufferedEvents(){let e=tv.eventBuffer.toBeProcessedArray.value;for(;e.length>0;){let t=e.shift();if(tv.eventBuffer.toBeProcessedArray.value=e,t){let e=t[0];_(this[e])&&this[e](...t.slice(1),!0)}e=tv.eventBuffer.toBeProcessedArray.value}}loadDestinations(){if(tv.nativeDestinations.clientDestinationsReady.value)return;this.pluginsManager?.invokeSingle("nativeDestinations.setActiveDestinations",tv,this.pluginsManager,this.errorHandler,this.logger);let e=tv.nativeDestinations.activeDestinations.value.length;if(0===e){tv.lifecycle.status.value="destinationsReady";return}tv.lifecycle.status.value="destinationsLoading",this.pluginsManager?.invokeSingle("nativeDestinations.load",tv,this.externalSrcLoader,this.errorHandler,this.logger),eH(()=>{(0===e||tv.nativeDestinations.initializedDestinations.value.length+tv.nativeDestinations.failedDestinations.value.length===e)&&eA(()=>{tv.lifecycle.status.value="destinationsReady",tv.nativeDestinations.clientDestinationsReady.value=!0})})}onDestinationsReady(){"ready"!==tv.lifecycle.status.value&&(tv.lifecycle.status.value="ready")}ready(e,t=!1){let i="ready";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}(this.errorHandler.leaveBreadcrumb(`New ${i} invocation`),_(e))?"readyExecuted"===tv.lifecycle.status.value?iG(e,[],G,this.logger):tv.eventBuffer.readyCallbacksArray.value=[...tv.eventBuffer.readyCallbacksArray.value,e]:this.logger.error(e1(G))}page(e,t=!1){let i="page";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}this.errorHandler.leaveBreadcrumb(`New ${i} event`),tv.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===tv.capabilities.isAdBlocked.value&&e.category!==ep&&this.page(M(ep,"ad-block page request",{path:"/ad-blocked"},tv.loadOptions.value.sendAdblockPageOptions))}track(e,t=!1){let i="track";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}this.errorHandler.leaveBreadcrumb(`New ${i} event - ${e.name}`),tv.metrics.triggered.value+=1,this.eventManager?.addEvent({type:i,name:e.name||void 0,properties:e.properties,options:e.options,callback:e.callback})}identify(e,t=!1){let i="identify";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}this.errorHandler.leaveBreadcrumb(`New ${i} event`),tv.metrics.triggered.value+=1,e.userId&&tv.session.userId.value&&e.userId!==tv.session.userId.value&&this.reset(),null!==e.userId&&this.userSessionManager?.setUserId(e.userId),this.userSessionManager?.setUserTraits(e.traits),this.eventManager?.addEvent({type:i,userId:e.userId,traits:e.traits,options:e.options,callback:e.callback})}alias(e,t=!1){let i="alias";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}this.errorHandler.leaveBreadcrumb(`New ${i} event`),tv.metrics.triggered.value+=1;let r=e.from??this.userSessionManager?.getUserId()??this.userSessionManager?.getAnonymousId();this.eventManager?.addEvent({type:i,to:e.to,from:r,options:e.options,callback:e.callback})}group(e,t=!1){let i="group";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}this.errorHandler.leaveBreadcrumb(`New ${i} event`),tv.metrics.triggered.value+=1,null!==e.groupId&&this.userSessionManager?.setGroupId(e.groupId),this.userSessionManager?.setGroupTraits(e.traits),this.eventManager?.addEvent({type:i,groupId:e.groupId,traits:e.traits,options:e.options,callback:e.callback})}reset(e,t=!1){let i="reset";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}this.errorHandler.leaveBreadcrumb(`New ${i} invocation, resetAnonymousId: ${e}`),this.userSessionManager?.reset(e)}getAnonymousId(e){return this.userSessionManager?.getAnonymousId(e)}setAnonymousId(e,t,i=!1){let r="setAnonymousId";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[r,e,t]];return}this.errorHandler.leaveBreadcrumb(`New ${r} invocation`),this.userSessionManager?.setAnonymousId(e,t)}getUserId(){return tv.session.userId.value}getUserTraits(){return tv.session.userTraits.value}getGroupId(){return tv.session.groupId.value}getGroupTraits(){return tv.session.groupTraits.value}startSession(e,t=!1){let i="startSession";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[i,e]];return}this.errorHandler.leaveBreadcrumb(`New ${i} invocation`),this.userSessionManager?.start(e)}endSession(e=!1){let t="endSession";if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,[t]];return}this.errorHandler.leaveBreadcrumb(`New ${t} invocation`),this.userSessionManager?.end()}getSessionId(){return this.userSessionManager?.getSessionId()??null}consent(e,t=!1){if(!tv.lifecycle.loaded.value){tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,["consent",e]];return}this.errorHandler.leaveBreadcrumb("New consent invocation"),eA(()=>{tv.consents.preConsent.value={...tv.consents.preConsent.value,enabled:!1},tv.consents.postConsent.value=(e=>{let t={sendPageEvent:!1,trackConsent:!1,discardPreConsentEvents:!1};if(P(e)){let i=p(e);t.storage=i.storage,A(i.integrations)&&(t.integrations=i.integrations),t.discardPreConsentEvents=!0===i.discardPreConsentEvents,t.sendPageEvent=!0===i.sendPageEvent,t.trackConsent=!0===i.trackConsent,A(i.consentManagement)&&(t.consentManagement=E(i.consentManagement,{enabled:tv.consents.enabled.value}))}return t})(e);let{initialized:t,consentsData:i}=iC(tv.consents.postConsent.value.consentManagement,this.logger);tv.consents.initialized.value=t,tv.consents.data.value=i}),tv.consents.enabled.value&&!tv.consents.initialized.value&&this.pluginsManager?.invokeSingle("consentManager.updateConsentsInfo",tv,this.storeManager,this.logger),this.storeManager?.initializeStorageState(),this.userSessionManager?.syncStorageDataToState(),this.eventManager?.resume(),this.loadDestinations(),this.sendTrackingEvents(t)}sendTrackingEvents(e){if(tv.consents.postConsent.value.trackConsent){let t=$("Consent Management Interaction");e?tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,["track",t]]:this.track(t)}if(tv.consents.postConsent.value.sendPageEvent){let t=M();e?tv.eventBuffer.toBeProcessedArray.value=[...tv.eventBuffer.toBeProcessedArray.value,["page",t]]:this.page(t)}}setAuthToken(e){this.userSessionManager?.setAuthToken(e)}}class iX{static globalSingleton=null;analyticsInstances={};defaultAnalyticsKey="";logger=eV;constructor(){try{if(iX.globalSingleton)return iX.globalSingleton;iX.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.get
4SessionId=this.getSessionId.bind(this),this.setAuthToken=this.setAuthToken.bind(this),this.consent=this.consent.bind(this),iX.globalSingleton=this,tv.autoTrack.pageLifecycle.visitId.value=ei(),tv.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now(),this.triggerBufferedLoadEvent(),globalThis.rudderanalytics=this}catch(e){eh(e)}}static initializeGlobalResources(){tU.init(),id.configure(),iu.configure(),ih.configure(),it.configure()}setDefaultInstanceKey(e){"string"==typeof e&&e&&(this.defaultAnalyticsKey=e)}getAnalyticsInstance(e){try{let t,i=e;return t=i,"string"==typeof t&&i||(i=this.defaultAnalyticsKey),this.analyticsInstances[i]||(this.analyticsInstances[i]=new iJ),this.analyticsInstances[i]}catch(e){eh(e);return}}load(e,t,i){try{let r,s;if(this.analyticsInstances[e])return;this.setDefaultInstanceKey(e);let n=ek(ef);this.trackPageLifecycleEvents(n,i),r=n.filter(e=>"consent"===e[0]),s=n.filter(e=>"consent"!==e[0]),n.splice(0,n.length,...r,...s),eS(ef,p(n)),this.getAnalyticsInstance(e)?.load(e,t,eo(i))}catch(e){eh(e)}}trackPageLifecycleEvents(e,t){let{autoTrack:i,useBeacon:r}=t??{},{enabled:s=!1,options:n={},pageLifecycle:a}=i??{},{events:o=[B.LOADED,B.UNLOADED],enabled:l=s,options:c=n}=a??{};tv.autoTrack.pageLifecycle.enabled.value=l,tv.autoTrack.enabled.value=s||l,l&&(this.trackPageLoadedEvent(o,c,e),this.setupPageUnloadTracking(o,r,c))}trackPageLoadedEvent(e,t,i){(0===e.length||e.includes(B.LOADED))&&i.unshift(["track",B.LOADED,{},{...t,originalTimestamp:new Date(tv.autoTrack.pageLifecycle.pageLoadedTimestamp.value).toISOString()}])}setupPageUnloadTracking(e,t,i){(0===e.length||e.includes(B.UNLOADED))&&(!0===t?(e=>{let t=!1,i=!1;function r(){t||(t=!0,e(i),setTimeout(()=>{t=!1},0))}globalThis.addEventListener("beforeunload",()=>{i=!1,r()}),globalThis.addEventListener("blur",()=>{i=!0,r()}),globalThis.addEventListener("focus",()=>{t=!1}),document.addEventListener("pagehide",()=>{i="hidden"===document.visibilityState,r()}),document.addEventListener("visibilitychange",()=>{i=!0,"hidden"===document.visibilityState?r():t=!1})})(e=>{if(!1===e&&tv.lifecycle.loaded.value){let e=Date.now(),t=e-tv.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(B.UNLOADED,{visitDuration:t},{...i,originalTimestamp:new Date(e).toISOString()})}}):this.logger.warn('RudderStackAnalytics:: Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.'))}triggerBufferedLoadEvent(){let e=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[],t=(e=>{let t=[],i=0;for(;i<e.length;){if(e[i]&&"load"===e[i][0]){t=p(e[i]),e.splice(i,1);break}i+=1}return t})(e);eS(ef,p([...e])),t.length>0&&(t.shift(),this.load.apply(null,t))}ready(e){try{this.getAnalyticsInstance()?.ready(eo(e))}catch(e){eh(e)}}page(e,t,i,r,s){try{this.getAnalyticsInstance()?.page(M(eo(e),eo(t),eo(i),eo(r),eo(s)))}catch(e){eh(e)}}track(e,t,i,r){try{this.getAnalyticsInstance()?.track($(eo(e),eo(t),eo(i),eo(r)))}catch(e){eh(e)}}identify(e,t,i,r){try{this.getAnalyticsInstance()?.identify(N(eo(e),eo(t),eo(i),eo(r)))}catch(e){eh(e)}}alias(e,t,i,r){try{this.getAnalyticsInstance()?.alias(U(eo(e),eo(t),eo(i),eo(r)))}catch(e){eh(e)}}group(e,t,i,r){try{this.getAnalyticsInstance()?.group(x(eo(e),eo(t),eo(i),eo(r)))}catch(e){eh(e)}}reset(e){try{this.getAnalyticsInstance()?.reset(eo(e))}catch(e){eh(e)}}getAnonymousId(e){try{return this.getAnalyticsInstance()?.getAnonymousId(eo(e))}catch(e){eh(e);return}}setAnonymousId(e,t){try{this.getAnalyticsInstance()?.setAnonymousId(eo(e),eo(t))}catch(e){eh(e)}}getUserId(){try{return this.getAnalyticsInstance()?.getUserId()}catch(e){eh(e);return}}getUserTraits(){try{return this.getAnalyticsInstance()?.getUserTraits()}catch(e){eh(e);return}}getGroupId(){try{return this.getAnalyticsInstance()?.getGroupId()}catch(e){eh(e);return}}getGroupTraits(){try{return this.getAnalyticsInstance()?.getGroupTraits()}catch(e){eh(e);return}}startSession(e){try{this.getAnalyticsInstance()?.startSession(eo(e))}catch(e){eh(e)}}endSession(){try{this.getAnalyticsInstance()?.endSession()}catch(e){eh(e)}}getSessionId(){try{return this.getAnalyticsInstance()?.getSessionId()}catch(e){eh(e);return}}setAuthToken(e){try{this.getAnalyticsInstance()?.setAuthToken(eo(e))}catch(e){eh(e)}}consent(e){try{this.getAnalyticsInstance()?.consent(eo(e))}catch(e){eh(e)}}}var iZ=e.i(170336),iY=e.i(851179),i0=e.i(922310);class i1{options;ComplianceService;consentedByDefault=!1;complianceBehavior="conditional";consentListener=e=>this.onConsentChange(!!e[this.requiredConsent]);constructor(e,t){this.options=e,this.ComplianceService=t,t.addListener(this.consentListener)}get hasConsent(){return i0.ComplianceService.getInstance().checkConsent(this.requiredConsent)??this.consentedByDefault}reset(){this.ComplianceService.removeListener(this.consentListener)}}var i2=e.i(568757);class i6 extends i1{name="rudderstack";requiredConsent=iZ.ConsentLevel.Targeting;complianceBehavior="always-load";consentedByDefault=!0;analytics;eventMap=i2.ANALYTICS_EVENT_MAP;
4async init(){if(this.analytics)return;let e=new iX,t=()=>{this.options.writeKey&&this.options.dataPlaneUrl?e.load(this.options.writeKey,this.options.dataPlaneUrl,{storage:{type:"localStorage"},consentManagement:{enabled:!0,provider:this.ComplianceService.providerName},pluginsSDKBaseURL:this.options.pluginsURL,destSDKBaseURL:this.options.destSDKBaseURL,configUrl:this.options.configUrl}):iY.logger.warn("rudderstack not initialized: missing writeKey or dataPlaneUrl")};"loading"===this.ComplianceService.state?this.ComplianceService.onLoad(()=>{iY.logger.debug("rudderstack loaded after compliance initialization"),t()}):t(),this.analytics=e,iY.logger.debug("rudderstack initialized",this.options)}pageView(e,t){iY.logger.debug("rudderstack pageView",{name:e,properties:t,url:window.location.href}),this.analytics?.page(e,t)}track(e,t){iY.logger.debug("rudderstack track",{event:e,properties:t}),this.analytics?.track(e,t)}identify(e){e.userId?this.analytics?.identify(e.userId.toString(),e.traits):e.traits&&this.analytics?.identify(e.traits)}onConsentChange(e){iY.logger.debug("rudderstack onConsentChange",{hasConsent:e}),this.analytics?.consent({trackConsent:!0,storage:{type:"localStorage"}})}reset(){iY.logger.debug("rudderstack reset"),super.reset(),this.analytics?.reset()}}e.s(["RudderStackProvider",0,i6],127329)},204186,e=>{"use strict";e.i(401853);var t,i,r=e.i(28722),s=e.i(604576),n=e.i(548271),a=e.i(52066);let o=["[Stytch]"],l=(...e)=>console.warn(...o,...e),c=(...e)=>console.error(...o,...e),u="bootstrap",h=()=>({displayWatermark:!1,projectName:null,cnameDomain:null,emailDomains:["stytch.com"],captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1,pkceRequiredForSso:!1,slugPattern:null,createOrganizationEnabled:!1,passwordConfig:null,runDFPProtectedAuth:!1,rbacPolicy:null,siweRequiredForCryptoWallets:!1,vertical:null});class d{_publicToken;_networkClient;_dataLayer;_bootstrapDataPromise;constructor(e,t,i){this._publicToken=e,this._networkClient=t,this._dataLayer=i,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:`/projects/bootstrap/${this._publicToken}`,method:"GET"}).then(d.mapBootstrapData).then(e=>(this._dataLayer.setItem(u,JSON.stringify(e)),e)).catch(e=>(c(e),h()))}static mapBootstrapData(e){let t=null!==e.password_config?{ludsComplexity:e.password_config.luds_complexity,ludsMinimumCount:e.password_config.luds_minimum_count}:null;return{projectName:e.project_name,displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,emailDomains:e.email_domains,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth,pkceRequiredForSso:e.pkce_required_for_sso,slugPattern:e.slug_pattern,createOrganizationEnabled:e.create_organization_enabled,passwordConfig:t,runDFPProtectedAuth:e.dfp_protected_auth_enabled??!1,dfpProtectedAuthMode:e.dfp_protected_auth_mode,rbacPolicy:e.rbac_policy??null,siweRequiredForCryptoWallets:e.siwe_required_for_crypto_wallets,vertical:e.vertical}}getSync(){let e=this._dataLayer.getItem(u);if(null===e)return h();try{return JSON.parse(e)}catch{return h()}}getAsync(){return this._bootstrapDataPromise}}let g={};async function p(e,t){var i,r;return void 0!==g[e]||(g[e]=(i=e,r=t,new Promise((e,t)=>{var s;let n,a=function(e){let t=document.querySelectorAll(`script[src="${e}"]`);if(t[0])return t[0]}(i);if(a&&"true"===a.dataset.loaded)try{e(r())}catch(e){return t(Error(`${i} already loaded, but module was not found in global scope: ${e}`))}let o=(s=i,(n=document.createElement("script")).setAttribute("src",s),n.setAttribute("async","true"),n.setAttribute("defer","true"),document.head.appendChild(n),n);o.addEventListener("load",()=>{o.dataset.loaded="true";try{e(r())}catch(e){t(Error(`${i} was loaded, but module was not found in global scope: ${e}`))}}),o.addEventListener("error",e=>{t(Error(`${i} could not be loaded: ${e}`))})}))),g[e]}class f{bootstrapPromise;state;constructor(e){this.bootstrapPromise=e,this.state=e.then(async e=>{let t;return e.captchaSettings.enabled?{configured:!0,captchaClient:await (t=e.captchaSettings.siteKey,p(`https://www.google.com/recaptcha/enterprise.js?render=${t}`,()=>window.grecaptcha.enterprise)),siteKey:e.captchaSettings.siteKey}:{configured:!1}})}executeRecaptcha=async()=>{let{captchaClient:e,configured:t,siteKey:i}=await this.state;if(t)return await new Promise(t=>e.ready(t)),e.execute(i,{action:"LOGIN"})}}let m="https://accounts.google.com/gsi",y=`${m}/client`,v="It looks like you're creating multiple copies of the Stytch client. This behavior is unsupported, and unintended side effects may occur. Make sure you are creating the Stytch client at the global level, and not inside a component's render function.";
4class b extends Error{details;constructor(e,t){super(e+"\n"+t),this.message=e+"\n"+t,this.name="SDKAPIUnreachableError",this.details=t,Object.setPrototypeOf(this,b.prototype)}}class _ extends Error{constructor(e,t){super(),this.name="StytchSDKUsageError",this.message=`Invalid call to ${e} 5`+t}}class S extends Error{constructor(e){super(),this.name="StytchSDKSchemaError";const t=e.body?.map(e=>`${e.dataPath}: ${e.message}`).join("\n");this.message=`[400] Request does not match expected schema 6${t}`}}class k extends Error{error_type;error_message;error_url;request_id;status_code;error_details;constructor(e){super(),this.name="StytchSDKAPIError";const{status_code:t,error_type:i,error_message:r,error_url:s,request_id:n,error_details:a}=e;this.error_type=i,this.error_message=r,this.error_url=s,this.request_id=n,this.status_code=t,this.error_details=a,this.message=`[${t}] ${i} 7${r} 8See ${s} for more information. 9`+(n?`request_id: ${n} 10`:"")+(this.error_details?`Details: 11`+JSON.stringify(this.error_details)+"\n":"")}}let w=["unauthorized_credentials","user_unauthenticated","invalid_secret_authentication","session_not_found"];class C extends Error{constructor(e,t){super(t),this.name=e}}class P extends C{constructor(e){super("StytchAPIUnreachableError",e),Object.setPrototypeOf(this,P.prototype)}}class T extends C{constructor(e){const t=e.body?.map(e=>`${e.dataPath}: ${e.message}`).join("\n");super("StytchAPISchemaError",`Request does not match expected schema 12${t}`)}}class E extends C{error_type;error_message;error_url;request_id;status_code;error_details;constructor(e){const{status_code:t,error_type:i,error_message:r,error_url:s,request_id:n,error_details:a}=e;super("StytchAPIError",`[${t}] ${i} 13${r} 14See ${s} for more information. 15`+(n?`request_id: ${n} 16`:"")+(a?`Details: 17`+JSON.stringify(a)+"\n":"")),this.error_type=i,this.error_message=r,this.error_url=s,this.request_id=n,this.status_code=t,this.error_details=a}static from(e){return e instanceof E?e:e&&"object"==typeof e&&"number"==typeof e.status_code&&"string"==typeof e.error_type&&"string"==typeof e.error_message&&"string"==typeof e.error_url?new E({status_code:e.status_code,error_type:e.error_type,error_message:e.error_message,error_url:e.error_url,request_id:"string"==typeof e.request_id?e.request_id:void 0,error_details:"object"==typeof e.error_details?e.error_details:void 0}):new E({status_code:400,error_type:"unknown_error",error_message:e instanceof Error?e.message:"Unknown error: "+String(e),error_url:"",request_id:void 0,error_details:void 0})}}class A{static inflate(e,t){let i=new e(t);return Object.assign(i,t),Object.setPrototypeOf(i,e.prototype),i}static unmarshall(e){if("name"in e)switch(e.name){case"SDKAPIUnreachableError":return A.inflate(b,e);case"StytchSDKSchemaError":return A.inflate(S,e);case"StytchAPIUnreachableError":return A.inflate(P,e);case"StytchAPISchemaError":return A.inflate(T,e);case"StytchSDKAPIError":return A.inflate(k,e);case"StytchAPIError":return A.inflate(E,e);case"TypeError":return A.inflate(TypeError,e);case"SyntaxError":return A.inflate(SyntaxError,e);case"ReferenceError":return A.inflate(ReferenceError,e);case"RangeError":return A.inflate(RangeError,e);case"EvalError":return A.inflate(EvalError,e);case"URIError":return A.inflate(URIError,e)}return A.inflate(Error,e)}}class I{iframeURL;frame;constructor(e){this.iframeURL=e,this.createIframe()}createIframe(){let e=document.querySelector(`[src~="${this.iframeURL}"]`);if(e?l(v):((e=document.createElement("iframe")).src=this.iframeURL,e.style.position="absolute",e.style.width="0",e.style.height="0",e.style.border="0",e.role="none",document.body.appendChild(e)),"true"===e.dataset.loaded){this.frame=Promise.resolve(e);return}this.frame=new Promise(t=>{e.addEventListener("load",()=>{e.dataset.loaded="true",t(e)},{once:!0})})}async call(e,t){let i=await this.frame,r=new MessageChannel;return new Promise((s,n)=>{r.port1.onmessage=e=>{let t=e.data;r.port1.close(),t.success?s(t.payload):n(A.unmarshall(t.error))},i.contentWindow?.postMessage({method:e,args:t},this.iframeURL,[r.port2])})}}class D{iframeURL;_frameClient;constructor(e){this.iframeURL=e}get frameClient(){return this._frameClient=this._frameClient??new I(this.iframeURL),this._frameClient}call(e,t){return this.frameClient.call(e,[t])}oneTapStart=e=>this.call("oneTapStart",e);oneTapSubmit=e=>this.call("oneTapSubmit",e);parsedPhoneNumber=e=>this.call("parsedPhoneNumber",e);getExamplePhoneNumber=e=>this.call("getExamplePhoneNumber",e)}
17for(var O=new Uint8Array(16),R=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,L=[],M=0;M<256;++M)L.push((M+256).toString(16).substr(1));function $(e,t,r){var s=(e=e||{}).random||(e.rng||function(){if(!i&&!(i="u">typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"u">typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(O)})();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(L[e[t+0]]+L[e[t+1]]+L[e[t+2]]+L[e[t+3]]+"-"+L[e[t+4]]+L[e[t+5]]+"-"+L[e[t+6]]+L[e[t+7]]+"-"+L[e[t+8]]+L[e[t+9]]+"-"+L[e[t+10]]+L[e[t+11]]+L[e[t+12]]+L[e[t+13]]+L[e[t+14]]+L[e[t+15]]).toLowerCase();if(!("string"==typeof i&&R.test(i)))throw TypeError("Stringified UUID is invalid");return i}(s)}class N{maxBatchSize;logEventURL;batch;constructor(e){this.maxBatchSize=e.maxBatchSize,this.logEventURL=e.logEventURL,setInterval(this.flush.bind(this),e.intervalDurationMs),this.batch=[]}logEvent(e,t){this.batch.push({telemetry:e,event:t}),this.batch.length>=this.maxBatchSize&&this.flush()}async flush(){if(!this.batch.length)return;let e=this.batch;this.batch=[];try{await fetch(this.logEventURL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}}}var U=((t={}).RequiredCaptcha="CAPTCHA required",t);class x extends Error{type;constructor(e){super(e),this.type=e}}async function B({method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:n,retryCallback:a}){let o={method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:n};try{return await K(o)}catch(e){if(e instanceof x)return o=await a(e,o),await K(o);throw e}}async function K({method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:n}){let a,o,l={Authorization:i,"Content-Type":"application/json","X-SDK-Client":r};s&&(l["X-SDK-Parent-Host"]=s);let c={method:e,headers:l,body:n&&JSON.stringify(n),credentials:"include"};try{a=await fetch(t,c)}catch(e){if("Failed to fetch"===e.message)throw new P("Unable to contact our servers.");throw e}if(a.status<=299)try{return(await a.json()).data}catch{throw new P("Invalid JSON response from our servers.")}if(200!==a.status&&a.headers.get("content-type")?.includes("application/json")){let e;try{e=await a.json()}catch{throw new P("Invalid or no response from server")}if("body"in e||"params"in e||"query"in e)throw new T(e);throw new E(e)}try{o=await a.text()}catch{throw new P("Invalid response from our servers.")}if(o.includes("Captcha required"))throw new x("CAPTCHA required");throw new P("Invalid response from our servers.")}async function F({method:e,finalURL:t,basicAuthHeader:i,xSDKClientHeader:r,xSDKParentHostHeader:s,body:n}){let a={...n||{},__Authorization:i,"__X-SDK-Client":r};s&&(a["__X-SDK-Parent-Host"]=s);let o=Object.entries(a).map(([e,t])=>{let i=document.createElement("input");return i.type="hidden",i.name=e,i.value=t,i}),l=document.createElement("form");l.method=e,l.action=t,l.append(...o),document.body.appendChild(l),l.submit()}class j{_publicToken;_subscriptionDataLayer;additionalTelemetryDataFn;eventLogger;baseURL;constructor(e,t,i,r,s){this._publicToken=e,this._subscriptionDataLayer=t,this.additionalTelemetryDataFn=s,this.baseURL=i,(e=>e.includes("public-token-test"))(e)&&(this.baseURL=r),this.eventLogger=new N({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}updateSessionToken=()=>null;logEvent({name:e,details:t,error:i={}}){this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:e,details:t,error_code:i.error_code,error_description:i.error_description,http_status_code:i.http_status_code})}createTelemetryBlob(){return{event_id:`event-id-${$()}`,app_session_id:`app-session-id-${$()}`,persistent_id:`persistent-id-${$()}`,client_sent_at:new Date().toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,...this.additionalTelemetryDataFn(),app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"0.0.0"}}}async fetchSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),n=window.btoa(JSON.stringify(this.createTelemetryBlob())),a=window.location.origin;return K({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:n,xSDKParentHostHeader:a})}async submitFormSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),n=window.btoa(JSON.stringify(this.createTelemetryBlob())),a=window.location.origin;return F({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:n,xSDKParentHostHeader:a})}async retriableFetchSDK({url:e,body:t,method:i,retryCallback:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,n="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),a=window.btoa(JSON.stringify(this.createTelemetryBlob())),o=window.location.origin;return B({basicAuthHeader:n,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:a,xSDKParentHostHeader:o,retryCallback:r})}buildSDKUrl(e){return`${this.baseURL}
17/sdk/v1${e}`}}function z(e){let t=e.toString(16);return 1===t.length&&(t="0"+t),t}class q{_dataLayer;namespace;constructor(e,t){this._dataLayer=e,this.namespace=t}key(){return`PKCE_VERIFIER:${this.namespace}`}async startPKCETransaction(){let e=await q.createProofkeyPair();return this._dataLayer.setItem(this.key(),JSON.stringify(e)),e}getPKPair(){let e=this._dataLayer.getItem(this.key());if(null!==e)try{return JSON.parse(e)}catch{l("Found malformed Proof Key pair in localstorage.");return}}clearPKPair(){return this._dataLayer.removeItem(this.key())}static async createProofkeyPair(){var e;let t=new Uint32Array(16);window.crypto.getRandomValues(t);let i=Array.from(t).map(z).join("");return{code_challenge:(e=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(i)),btoa(String.fromCharCode.call(null,...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:i}}}function H(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var Q=function e(t,i){function r(e,r,s){if("u">typeof document){"number"==typeof(s=H({},i,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var n="";for(var a in s)s[a]&&(n+="; "+a,!0!==s[a]&&(n+="="+s[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+n}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},s=0;s<i.length;s++){var n=i[s].split("="),a=n.slice(1).join("=");try{var o=decodeURIComponent(n[0]);if(r[o]=t.read(a,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",H({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,H({},this.attributes,t))},withConverter:function(t){return e(H({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});let G=e=>(document.cookie?document.cookie.split("; "):[]).filter(t=>{let[i]=t.split("=");return e===i}).length>1,W=(e,t)=>`stytch_sdk_state_${e}${t?`::${t}`:""}`;function V(e){return null==e?{getItem:()=>null,removeItem(){},setItem(){}}:{getItem(t,i){let r=W(t,i);try{return e.getItem(r)}catch{return null}},setItem(t,i,r){let s=W(t,i);try{r&&e.setItem(s,r)}catch{}},removeItem(t,i){let r=W(t,i);try{e.removeItem(r)}catch{}}}}let J=V(globalThis.localStorage),X=V(globalThis.sessionStorage);function Z(e,t){return{getItem:i=>e.getItem(t,i),setItem(i,r){e.setItem(t,i,r)},removeItem(i){e.removeItem(t,i)}}}var Y=e.i(889796);let ee="seen_domains";class et{publicToken;state;_opaqueTokenCookieName=null;_jwtCookieName=null;_cookiePath=null;_domain=null;_cookieAvailableToSubdomains=!1;_istCookieName=null;subscriptions;_localStorage;browserSessionStorage;constructor(e,t){let i;this.publicToken=e,this.state=null,this.subscriptions={},this._localStorage=Z(J,e),this.browserSessionStorage=Z(X,e),t?.cookieOptions&&(this._opaqueTokenCookieName=t.cookieOptions.opaqueTokenCookieName||null,this._jwtCookieName=t.cookieOptions.jwtCookieName||null,this._cookiePath=t.cookieOptions.path||null,this._domain=t.cookieOptions.domain||null,this._cookieAvailableToSubdomains=t.cookieOptions.availableToSubdomains||!1,this._istCookieName=t.cookieOptions.istCookieName||null);const r=this._localStorage.getItem("");if(!r)return;try{i=JSON.parse(r)}catch{this.syncToLocalStorage();return}this.state=i}get opaqueTokenCookieName(){return this._opaqueTokenCookieName??"stytch_session"}get jwtCookieName(){return this._jwtCookieName??"stytch_session_jwt"}get istCookieName(){return this._istCookieName??"stytch_intermediate_session_token"}readSessionCookie(){return{session_token:Q.get(this.opaqueTokenCookieName),session_jwt:Q.get(this.jwtCookieName)}}readIntermediateSessionTokenCookie(){return Q.get(this.istCookieName)}writeSessionCookie(e){let{state:t,session_token:i,session_jwt:r}=e,s=et.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});s.domain&&this.addSeenDomain(s.domain),Q.set(this.opaqueTokenCookieName,i,s),Q.set(this.jwtCookieName,r,s);let n=et.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:!this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});n.domain&&this.addSeenDomain(n.domain),G(this.jwtCookieName)&&Q.remove(this.jwtCookieName,n),G(this.opaqueTokenCookieName)&&Q.remove(this.opaqueTokenCookieName,n),G(this.jwtCookieName)&&l("Could not remove extraneous JWT cookie. This might happen if the cookie has been set using multiple `path` settings, and may produce unwanted behavior."),G(this.opaqueTokenCookieName)&&l("Could not remove extraneous opaque token cookie.")}writeIntermediateSessionTokenCookie(e){let t=new Date(Date.now()+6e5),i=et.generateCookieOpts({expiresAt:t.toString(),availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});Q.set(this.istCookieName,e,i)}removeSessionCookie(){this.removeCookies([this.opaqueTokenCookieName,this.jwtCookieName])}removeISTCookie(){this.removeCookies([this.istCookieName])}
17removeCookies(e){let t=this.getSeenDomains(),i=[...new Set([this._domain,null,...t])];[!0,!1].forEach(t=>{[this._cookiePath,null].forEach(r=>{i.forEach(i=>{let s=et.generateCookieOpts({expiresAt:new Date(0).toString(),availableToSubdomains:t,path:r,domain:i});e.forEach(e=>{Q.remove(e,s)})})})})}syncToLocalStorage(){this._localStorage.setItem("",JSON.stringify(this.state))}getItem(e){return this._localStorage.getItem(e)}setItem(e,t){this._localStorage.setItem(e,t)}removeItem(e){this._localStorage.removeItem(e)}getSeenDomains(){let e=this.getItem(ee);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}addSeenDomain(e){if(!e)return;let t=this.getSeenDomains();t.includes(e)||(t.push(e),this.setItem(ee,JSON.stringify(t)))}static generateCookieOpts({path:e,domain:t,availableToSubdomains:i,expiresAt:r}){let s={expires:new Date(r),sameSite:"lax"};return e&&(s.path=e),"localhost"===window.location.hostname||"[::1]"===window.location.hostname||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)?s.secure=!1:(i&&(s.domain=t||window.location.host),s.secure=!0),s}}class ei extends et{}Symbol.for("__stytch_DataLayer");let er=Symbol.for("__stytch_b2b_DataLayer"),es=(e,t)=>{Object.values(e).forEach(e=>e(t))},en=(0,Y.createDeepEqual)({KEYS_TO_EXCLUDE:["last_accessed_at"]});class ea{_publicToken;_datalayer;fromCache=!0;constructor(e,t,{usingCustomApiEndpoint:i}){if(this._publicToken=e,this._datalayer=t,window.addEventListener("storage",this._listen),!i){const{session_token:e}=this._datalayer.readSessionCookie();if(!e)return void this.destroySession()}}_listen=e=>{if(e.key!==W(this._publicToken,""))return;let t=null===e.newValue||"null"===e.newValue?null:JSON.parse(e.newValue);this.updateState(t,!0)};getTokens(){let{session_token:e,session_jwt:t}=this._datalayer.readSessionCookie();return"string"!=typeof e||"string"!=typeof t?null:{session_token:e,session_jwt:t}}getIntermediateSessionToken(){return this._datalayer.readIntermediateSessionTokenCookie()||null}destroyState(){this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:null})}destroySession(){this._datalayer.removeSessionCookie(),this.updateState(null)}_updateStateAndTokensInternal(e,t){let i=this._datalayer.state,r=null===e.state?null:{...this._datalayer.state,...e.state};this._datalayer.state=r;let s=this.getFromCache();if(this.setCacheRefreshed(),s||!en(i,r)){let e;e=null==r||t.fromCache?r:{...r,sessionDurationMinutes:t.sessionDurationMinutes},es(this._datalayer.subscriptions,e)}}updateStateAndTokens(e,t={fromCache:!1}){e.state?("string"==typeof e.session_token?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()):e.intermediate_session_token?("string"==typeof e.intermediate_session_token?this._datalayer.writeIntermediateSessionTokenCookie(e.intermediate_session_token):this._datalayer.removeISTCookie(),this._datalayer.removeSessionCookie()):(this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()),this._updateStateAndTokensInternal(e,t),this._datalayer.syncToLocalStorage()}updateState(e,t=!1){let i=this._datalayer.state,r=null===e?null:{...this._datalayer.state,...e};this._datalayer.state=r;let s=this.getFromCache();this.setCacheRefreshed();let n=!en(i,r);(s||n)&&(es(this._datalayer.subscriptions,r),n&&!t&&this._datalayer.syncToLocalStorage())}updateTokens(e){let{session_token:t,session_jwt:i}=e,r={...this._datalayer.readSessionCookie(),session_token:t,session_jwt:i};"string"==typeof t||"string"==typeof i?(this._datalayer.writeSessionCookie(r),this._datalayer.removeISTCookie()):this._datalayer.removeSessionCookie()}subscribeToState(e){var t;let i;return t=this._datalayer.subscriptions,t[i=Math.random().toString(36).slice(-10)]=e,()=>delete t[i]}getState(){return this._datalayer.state}destroy(){window.removeEventListener("storage",this._listen)}syncFromDeviceStorage(){return null}getFromCache(){return this.fromCache}setCacheRefreshed(){this.fromCache=!1}}class eo extends ea{updateMember=e=>this.updateState({member:e});getMember=()=>this.getState()?.member??null;updateOrganization=e=>this.updateState({organization:e});getOrganization=()=>this.getState()?.organization??null;getSession=()=>this.getState()?.session??null;updateSession=(e,t)=>{if("member_session"in e&&e.member_session){let i=e.session_token&&e.session_jwt?{session_token:e.session_token,session_jwt:e.session_jwt}:{session_token:!0,session_jwt:!0};this.updateStateAndTokens({state:{session:e.member_session,member:e.member,organization:e.organization},...i,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})}
17else this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:e.intermediate_session_token||!0},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})};withUpdateSession=e=>async t=>{let i=await e(t);return this.updateSession(i,{sessionDurationMinutes:t?.session_duration_minutes}),i}}let el=e=>{try{let t=new URL(e);return`https://${t.hostname}`}catch{}try{let t=new URL(`https://${e}`);return`https://${t.hostname}`}catch{}},ec=Symbol.for("stytch__internal_b2b");Symbol.for("stytch__internal_b2c");let eu="google",eh="microsoft",ed="hubspot",eg="slack",ep="github",ef=class{_networkClient;_subscriptionService;_pkceManager;_dynamicConfig;_config;dfpProtectedAuth;authenticate;discovery;google;microsoft;hubspot;slack;github;constructor(e,t,i,r,s,n){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._dynamicConfig=r,this._config=s,this.dfpProtectedAuth=n,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{let t=await this._pkceManager.getPKPair();t||l("No code verifier found in local storage for OAuth flow.\nConsider using stytch.oauth.$provider.start() to add PKCE to your OAuth flows for added security.\nSee https://stytch.com/docs/oauth#guides_pkce for more information.");let{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s=await this._networkClient.retriableFetchSDK({url:"/b2b/oauth/authenticate",method:"POST",body:{pkce_code_verifier:t?.code_verifier,dfp_telemetry_id:i,captcha_token:r,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0,...e},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),s}),this.discovery={authenticate:this._subscriptionService.withUpdateSession(async e=>{let t=await this._pkceManager.getPKPair(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s={pkce_code_verifier:t?.code_verifier,dfp_telemetry_id:i,captcha_token:r,...e},n=await this._networkClient.retriableFetchSDK({url:"/b2b/oauth/discovery/authenticate",body:s,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),n})},this.google={start:this.startOAuthFlow(eu),discovery:{start:this.startDiscoveryOAuthFlow(eu)}},this.microsoft={start:this.startOAuthFlow(eh),discovery:{start:this.startDiscoveryOAuthFlow(eh)}},this.hubspot={start:this.startOAuthFlow(ed),discovery:{start:this.startDiscoveryOAuthFlow(ed)}},this.slack={start:this.startOAuthFlow(eg),discovery:{start:this.startDiscoveryOAuthFlow(eg)}},this.github={start:this.startOAuthFlow(ep),discovery:{start:this.startDiscoveryOAuthFlow(ep)}}}async getBaseApiUrl(){let{cnameDomain:e}=await this._dynamicConfig;return e?`https://${e}`:this._config.publicToken.includes("public-token-test")?this._config.testAPIURL:this._config.liveAPIURL}startOAuthFlow(e){return async t=>{let{organization_id:i,organization_slug:r,login_redirect_url:s,signup_redirect_url:n,custom_scopes:a,provider_params:o}=t,{pkceRequiredForOAuth:l}=await this._dynamicConfig,c=await this.getBaseApiUrl(),u=new URL(`${c}/v1/b2b/public/oauth/${e}/start`);if(u.searchParams.set("public_token",this._config.publicToken),i&&""!=i&&u.searchParams.set("organization_id",i),r&&""!=r&&u.searchParams.set("slug",r),a&&u.searchParams.set("custom_scopes",a.join(" ")),o)for(let e in o)u.searchParams.set("provider_"+e,o[e]);if(l){let e=await this._pkceManager.startPKCETransaction();u.searchParams.set("pkce_code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();s&&u.searchParams.set("login_redirect_url",s),n&&u.searchParams.set("signup_redirect_url",n),this.navigate(u)}}startDiscoveryOAuthFlow(e){return async t=>{let{discovery_redirect_url:i,custom_scopes:r,provider_params:s}=t,{pkceRequiredForOAuth:n}=await this._dynamicConfig,a=await this.getBaseApiUrl(),o=new URL(`${a}/v1/b2b/public/oauth/${e}/discovery/start`);if(o.searchParams.set("public_token",this._config.publicToken),r&&o.searchParams.set("custom_scopes",r.join(" ")),s)for(let e in s)o.searchParams.set("provider_"+e,s[e]);if(n){let e=await this._pkceManager.startPKCETransaction();o.searchParams.set("pkce_code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();i&&o.searchParams.set("discovery_redirect_url",i),this.navigate(o)}}navigate(e){window.location.href=e.toString()}};class em{bootstrapPromise;state;constructor(e,t,i,r,s=()=>Promise.resolve(void 0)){this.bootstrapPromise=r,this.state=r.then(async r=>r.runDFPProtectedAuth?(await p(`${i}/telemetry.js`,()=>
17window.GetTelemetryID),{publicToken:e,dfpBackendURL:t,enabled:!0,mode:r.dfpProtectedAuthMode||"OBSERVATION",loaded:!0,executeRecaptcha:s}):{publicToken:e,dfpBackendURL:t,enabled:!1,loaded:!1,executeRecaptcha:s})}isEnabled=async()=>this.state.then(e=>e.enabled);getTelemetryID=async()=>{let{publicToken:e,enabled:t,dfpBackendURL:i}=await this.state;if(t)return await window.GetTelemetryID(e,`${i}/submit`)};getDFPTelemetryIDAndCaptcha=async()=>{let e,t,{enabled:i,executeRecaptcha:r,mode:s}=await this.state;return i||(t=await r()),"DECISIONING"===s?e=await this.getTelemetryID():"OBSERVATION"===s&&(e=await this.getTelemetryID(),t=await r()),{dfp_telemetry_id:e,captcha_token:t}};retryWithCaptchaAndDFP=async(e,t)=>{let{enabled:i,executeRecaptcha:r}=await this.state;if(e.type===U.RequiredCaptcha&&i)return t.body&&(t.body.dfp_telemetry_id=await this.getTelemetryID(),t.body.captcha_token=await r()),t;throw Error("Unable to query captcha and/or dfp telemetry ID")}}let ey=()=>({isEnabled:async()=>!1,getTelemetryID:async()=>void 0,getDFPTelemetryIDAndCaptcha:async()=>({dfp_telemetry_id:void 0,captcha_token:void 0}),retryWithCaptchaAndDFP:async()=>{throw Error("DFP protected auth is disabled")}}),ev="floating";class eb extends ef{_oneTap;constructor(e,t,i,r,s,n=ey(),a){super(e,t,i,r,s,n),this._oneTap=a}startOneTapDiscovery=async e=>{let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnDiscoverySuccessHandler({discoveryRedirectUrl:e.discovery_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:ev},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};startOneTap=async e=>{if(!e.organization_id)throw new _("stytch.oauth.googleOneTap.start","organization_id is a required argument");let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnSuccessHandler({organizationId:e.organization_id,signupRedirectUrl:e.signup_redirect_url,loginRedirectUrl:e.login_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:ev},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};googleOneTap={discovery:{start:this.startOneTapDiscovery},start:this.startOneTap}}let e_="u">typeof window&&"IdentityCredential"in window,eS=e=>"forceLegacyEmbedded"===e?"force":"embeddedOnly"===e||"embedded"===e||"floatingOrEmbedded"===e;class ek{_googleClient;_clientId;constructor(e,t){this._googleClient=e,this._clientId=t}cancel(){this._googleClient.cancel()}async render({callback:e,onOneTapCancelled:t,style:i,cancelOnTapOutside:r=!0}){let s,n=eS(i.position),a="force"===(s=eS(i.position))||s&&!e_,o={client_id:this._clientId,callback:e,auto_select:!1,context:"use",itp_support:!0,use_fedcm_for_prompt:"force"!==n,cancel_on_tap_outside:r};return a&&(o.prompt_parent_id="google-parent-prompt",o.cancel_on_tap_outside=!1),this._googleClient.initialize(o),new Promise(e=>{this._googleClient.prompt(i=>{if(i.isSkippedMoment()){let r=i.getSkippedReason?.()??"unknown_reason";return"user_cancel"===r&&t?.(),e({success:!1,reason:r})}return!i.isNotDisplayed&&a||i.isNotDisplayed?.()?e({success:!1,reason:i.getNotDisplayedReason?.()??"unknown_reason"}):i.isDismissedMoment()?void 0:(this.styleFrame(a),e({success:!0}))})})}styleFrame(e){e&&Array.from(document.getElementsByTagName("iframe")).forEac
17h(e=>{e.src.includes(m)&&(e.style.width="100%")})}}let ew=Promise.resolve({pkceRequiredForOAuth:!1});class eC{_networkClient;_pkceManager;_config;googleClientID;constructor(e,t,i=ew){this._networkClient=e,this._pkceManager=t,this._config=i}async fetchGoogleStart(){if(this.googleClientID)return this.googleClientID;let e=await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/start",method:"GET"});return this.googleClientID=e.google_client_id,this.googleClientID}async submitGoogleOneTapTokenDiscovery({credential:e,discoveryRedirectUrl:t}){let i,{pkceRequiredForOAuth:r}=await this._config;return r?i=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/discovery/submit",method:"POST",body:{id_token:e,discovery_redirect_url:t,pkce_code_challenge:i}})}async submitGoogleOneTapToken({credential:e,organizationId:t,signupRedirectUrl:i,loginRedirectUrl:r}){let s,{pkceRequiredForOAuth:n}=await this._config;return n?s=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/submit",method:"POST",body:{id_token:e,organization_id:t,signup_redirect_url:i,login_redirect_url:r,pkce_code_challenge:s}})}async createOneTapClient(){let e;try{e=await this.fetchGoogleStart()}catch(e){return{success:!1,reason:E.from(e).error_type}}return""===e?{success:!1,reason:"oauth_config_not_found"}:{success:!0,client:new ek(await p(y,()=>window.google.accounts.id),e)}}createOnDiscoverySuccessHandler=({discoveryRedirectUrl:e,onSuccess:t,onError:i})=>async r=>{let{credential:s}=r,n=this.submitGoogleOneTapTokenDiscovery({credential:s,discoveryRedirectUrl:e}).then(e=>t(e.redirect_url));i&&(n=n.catch(e=>i(e))),await n};createOnSuccessHandler=({organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i,onSuccess:r,onError:s})=>async n=>{let{credential:a}=n,o=this.submitGoogleOneTapToken({credential:a,organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i}).then(e=>r(e.redirect_url));s&&(o=o.catch(e=>s(e))),await o};redirectOnSuccess=e=>{window.location.href=e}}let eP=` 18You can find your public token at https://stytch.com/dashboard/api-keys.`;class eT{_networkClient;_apiNetworkClient;_subscriptionService;constructor(e,t,i){this._networkClient=e,this._apiNetworkClient=t,this._subscriptionService=i}get=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/me",method:"GET"});return this._subscriptionService.updateOrganization(e.organization),e.organization};getSync=()=>this._subscriptionService.getOrganization();getInfo=()=>({organization:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>this._subscriptionService.subscribeToState(t=>e(t?.organization??null));update=async e=>{let t=await this._networkClient.fetchSDK({url:"/b2b/organizations/me",method:"PUT",body:e});return this._subscriptionService.updateOrganization(t.organization),t};delete=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/me",method:"DELETE"});return this._subscriptionService.destroyState(),e};getBySlug=async e=>this._networkClient.fetchSDK({url:"/b2b/organizations/search",method:"POST",body:e});getConnectedApps=async()=>this._networkClient.fetchSDK({url:"/b2b/organizations/connected_apps",method:"GET"});getConnectedApp=async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/connected_apps/${e.connected_app_id}`,method:"GET"});members={create:async e=>this._networkClient.fetchSDK({url:"/b2b/organizations/members",method:"POST",body:e}),search:async e=>this._networkClient.fetchSDK({url:"/b2b/organizations/me/members/search",method:"POST",body:e}),update:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e.member_id}`,method:"PUT",body:e});return this.updateMemberIfSelf(t),t},deletePassword:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/passwords/${e}`,method:"DELETE"});return this.updateMemberIfSelf(t),t},deleteMFAPhoneNumber:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/mfa_phone_numbers/${e}`,method:"DELETE"});return this.updateMemberIfSelf(t),t},deleteMFATOTP:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/totp/${e}`,method:"DELETE"});return this.updateMemberIfSelf(t),t},delete:async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e}`,method:"DELETE"});return e===this._subscriptionService.getMember()?.member_id&&this._subscriptionService.destroyState(),t},reactivate:async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e}/reactivate`,method:"PUT"}),unlinkRetiredEmail:async e=>{let{member_id:t,...i}=e,r=await this._apiNetworkClient.fetchSDK({url:`/b2b/organizations/members/${t}/unlink_retired_email`,method:"POST",body:i});return this.updateMemberIfSelf(r),r},startEmailUpdate:async e=>{let{member_id:t,...i}=e,r=await this._apiNetworkClient.fetchSDK({url:`/b2b/organizations/members/${t}/start_email_update`,method:"POST",body:i});return this.updateMemberIfSelf(r),r},getConnectedApps:async e=>this._networkClient.fetchSDK({url:`b2b/organizations/members/${e.member_id}/connected_apps`,method:"GET"}),revokeConnectedApp:async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/members/${e.member_id}/connected_apps/${e.connected_app_id}/revoke`,method:"POST"})};updateMemberIfSelf=e=>{e.member_id===this._subscriptionService.getMember()?.member_id&&this._subscriptionService.updateMember(e.member)}}class eE{_networkClient;_subscriptionService;organizations;intermediateSessions;constructor(e,t){this._networkClient=e,this._subscriptionService=t,this.organizations={list:async()=>this._networkClient.fetchSDK({url:"/b2b/discovery/organizations",body:{intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0},method:"POST"}),create:this._subscriptionService.withUpdateSession(async e=>{let t={...e,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.fetchSDK({url:"/b2b/discovery/organizations/create",body:t,method:"POST"})})},this.intermediateSessions={exchange:this._subscriptionService.withUpdateSession(async e=>{let t={...e,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.fetchSDK({url:"/b2b/discovery/intermediate_sessions/exchange",body:t,method:"POST"})})}}}class eA{_networkClient;constructor(e){this._networkClient=e}oauthAuthorizeStart=async e=>this._networkClient.fetchSDK({url:"/idp/b2b/oauth/authorize/start",method:"POST",body:e});oauthAuthorizeSubmit=async e=>this._networkClient.fetchSDK({url:"/idp/b2b/oauth/authorize/submit",method:"POST",body:e});oauthLogoutStart=async e=>this._networkClient.fetchSDK({url:"/b2b/oauth/logout/start",method:"POST",body:e})}class eI{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/impersonation/authenticate",body:{...e,dfp_telemetry_id:t,captcha_token:i},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}}
18let eD=Promise.resolve({pkceRequiredForEmailMagicLinks:!1});class eO{_networkClient;_subscriptionService;_pkceManager;_passwordResetPKCEManager;_config;dfpProtectedAuth;email;authenticate;discovery;constructor(e,t,i,r,s=eD,n=ey()){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._passwordResetPKCEManager=r,this._config=s,this.dfpProtectedAuth=n,this.email={invite:async e=>this._networkClient.fetchSDK({url:"/b2b/magic_links/email/invite",body:e,method:"POST"}),loginOrSignup:async e=>{let t=await this.getCodeChallenge(),i={...e,pkce_code_challenge:t};return this._networkClient.fetchSDK({url:"/b2b/magic_links/email/login_or_signup",body:i,method:"POST"})},discovery:{send:async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this.getCodeChallenge(),s={...e,pkce_code_challenge:r,dfp_telemetry_id:t,captcha_token:i};return this._networkClient.retriableFetchSDK({url:"/b2b/magic_links/email/discovery/send",body:s,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}}},this.authenticate=this._subscriptionService.withUpdateSession(async e=>{let t=await this._passwordResetPKCEManager.getPKPair(),i=null;if(t?.code_verifier)try{i=await this.handlePKCEForAuthenticate(this._passwordResetPKCEManager,e)}catch(e){if(e.message.includes("pkce"))console.log("Authenticate with passwords pkce namespace failed. Falling back to authenticate with magic_links namespace.");else throw e}return i||(i=await this.handlePKCEForAuthenticate(this._pkceManager,e)),i}),this.discovery={authenticate:this._subscriptionService.withUpdateSession(async e=>{let t=await this._pkceManager.getPKPair(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s={pkce_code_verifier:t?.code_verifier,dfp_telemetry_id:i,captcha_token:r,...e},n=await this._networkClient.retriableFetchSDK({url:"/b2b/magic_links/discovery/authenticate",body:s,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),n})}}async getCodeChallenge(){let{pkceRequiredForEmailMagicLinks:e}=await this._config;if(!e)return;let t=await this._pkceManager.getPKPair();return t?t.code_challenge:(t=await this._pkceManager.startPKCETransaction()).code_challenge}async handlePKCEForAuthenticate(e,t){let i=await e.getPKPair(),{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),n={pkce_code_verifier:i?.code_verifier,dfp_telemetry_id:r,captcha_token:s,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0,...t},a=await this._networkClient.retriableFetchSDK({url:"/b2b/magic_links/authenticate",body:n,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return e.clearPKPair(),a}}class eR{_networkClient;_subscriptionService;dfpProtectedAuth;sms;email;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.sms={send:async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/otps/sms/send",body:{...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},authenticate:this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.retriableFetchSDK({url:"/b2b/otps/sms/authenticate",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})},this.email={loginOrSignup:async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/login_or_signup",body:{...e,dfp_telemetry_id:t,captcha_token:i},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},authenticate:this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/authenticate",body:{...e,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0,dfp_telemetry_id:t,captcha_token:i},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}),discovery:{send:async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i};return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/discovery/send",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},authenticate:this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={dfp_telemetry_id:t,captcha_token:i,...e};return this._networkClient.retriableFetchSDK({url:"/b2b/otps/email/discovery/authenticate",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}}}}let eL=Promise.resolve({pkceRequiredForPasswordResets:!1});class eM{_networkClient;_subscriptionService;_pkceManager;_config;dfpProtectedAuth;authenticate;discovery;resetByEmail;resetByExistingPassword;resetBySession;constructor(e,t,i,r=eL,s){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._config=r,this.dfpProtectedAuth=s,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{let t=await this._pkceManager.getPKPair(),i=t?.code_verifier,{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/authenticate",method:"POST",body:{organization_id:e.organization_id,email_address:e.email_address,password:e.password,session_duration_minutes:e.session_duration_minutes,locale:e.locale,captcha_token:s,dfp_telemetry_id:r,code_verifier:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}),this.discovery={resetByEmailStart:async e=>
18{let t=await this.getCodeChallenge(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/discovery/reset/start",method:"POST",body:{email_address:e.email_address,discovery_redirect_url:e.discovery_redirect_url,reset_password_redirect_url:e.reset_password_redirect_url,reset_password_expiration_minutes:e.reset_password_expiration_minutes,reset_password_template_id:e.reset_password_template_id,verify_email_template_id:e.verify_email_template_id,locale:e.locale,pkce_code_challenge:t,captcha_token:r,dfp_telemetry_id:i},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})},resetByEmail:this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this._pkceManager.getPKPair(),s=r?.code_verifier,n=await this._networkClient.retriableFetchSDK({url:"/b2b/passwords/discovery/reset",method:"POST",body:{password_reset_token:e.password_reset_token,password:e.password,captcha_token:i,dfp_telemetry_id:t,pkce_code_verifier:s,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),n}),authenticate:this._subscriptionService.withUpdateSession(async e=>{let t=await this._pkceManager.getPKPair(),i=t?.code_verifier,{dfp_telemetry_id:r,captcha_token:s}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/discovery/authenticate",method:"POST",body:{email_address:e.email_address,password:e.password,captcha_token:s,dfp_telemetry_id:r,code_verifier:i},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})},this.resetByEmail=this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this._pkceManager.getPKPair(),s=r?.code_verifier,n=await this._networkClient.retriableFetchSDK({url:"/b2b/passwords/email/reset",method:"POST",body:{password_reset_token:e.password_reset_token,password:e.password,session_duration_minutes:e.session_duration_minutes,locale:e.locale,captcha_token:i,dfp_telemetry_id:t,code_verifier:s,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),n}),this.resetByExistingPassword=this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/existing_password/reset",method:"POST",body:{organization_id:e.organization_id,email_address:e.email_address,existing_password:e.existing_password,new_password:e.new_password,locale:e.locale,session_duration_minutes:e.session_duration_minutes,captcha_token:i,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}),this.resetBySession=this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/session/reset",method:"POST",body:{password:e.password,captcha_token:i,dfp_telemetry_id:t},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async getCodeChallenge(){let{pkceRequiredForPasswordResets:e}=await this._config;if(!e)return;let t=await this._pkceManager.getPKPair();return t?t.code_challenge:(t=await this._pkceManager.startPKCETransaction()).code_challenge}async resetByEmailStart(e){let t=await this.getCodeChallenge(),{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/passwords/email/reset/start",method:"POST",body:{organization_id:e.organization_id,email_address:e.email_address,login_redirect_url:e.login_redirect_url,reset_password_redirect_url:e.reset_password_redirect_url,reset_password_expiration_minutes:e.reset_password_expiration_minutes,reset_password_template_id:e.reset_password_template_id,verify_email_template_id:e.verify_email_template_id,locale:e.locale,code_challenge:t,captcha_token:r,dfp_telemetry_id:i},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}async strengthCheck(e){return this._networkClient.fetchSDK({url:"/b2b/passwords/strength_check",method:"POST",body:{email_address:e.email_address,password:e.password}})}}class e${roles;resources;rolesByID;constructor(e,t){this.roles=e,this.resources=t,this.rolesByID={}
18,e.forEach(e=>this.rolesByID[e.role_id]=e)}static fromJSON(e){return new e$(e.roles,e.resources)}mergeWithCustomRoles(e){return new e$([...this.roles,...e],this.resources)}callerIsAuthorized(e,t,i){return!!e.map(e=>this.rolesByID[e]).filter(e=>e).flatMap(e=>e.permissions).filter(e=>e.resource_id===t).find(e=>e.actions.includes(i)||e.actions.includes("*"))}allPermissionsForCaller(e){let t=Object.create(null);return this.resources.forEach(i=>{t[i.resource_id]={},i.actions.forEach(r=>{t[i.resource_id][r]=this.callerIsAuthorized(e,i.resource_id,r)})}),t}}class eN{_subscriptionService;cachedPolicy;policyPromise;constructor(e,t,i){this._subscriptionService=i,this.cachedPolicy=e.rbacPolicy?e$.fromJSON(e.rbacPolicy):null,this.policyPromise=t.then(e=>e.rbacPolicy?(this.cachedPolicy=e$.fromJSON(e.rbacPolicy),this.cachedPolicy):(c("Unable to retrieve RBAC policy from servers. Assuming caller has no permissions."),new e$([],[])))}async getEffectivePolicy(){let e=await this.policyPromise,t=this._subscriptionService.getOrganization();return t?.custom_roles?.length?e.mergeWithCustomRoles(t.custom_roles):e}getEffectivePolicySync(){if(!this.cachedPolicy)return null;let e=this._subscriptionService.getOrganization();return e?.custom_roles?.length?this.cachedPolicy.mergeWithCustomRoles(e.custom_roles):this.cachedPolicy}allPermissions(){return this.getEffectivePolicy().then(e=>e.allPermissionsForCaller(this.roleIds()))}isAuthorizedSync=(e,t)=>{let i=this.getEffectivePolicySync();return!!i?.callerIsAuthorized(this.roleIds(),e,t)};isAuthorized=(e,t)=>this.getEffectivePolicy().then(i=>i.callerIsAuthorized(this.roleIds(),e,t));roleIds(){let e=this._subscriptionService.getSession();return e?e.roles??[]:[]}}class eU{_networkClient;_subscriptionService;dfpProtectedAuth;recover;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.recover=this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.retriableFetchSDK({url:"/b2b/recovery_codes/recover",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async rotate(){let{dfp_telemetry_id:e,captcha_token:t}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha();return this._networkClient.retriableFetchSDK({url:"/b2b/recovery_codes/rotate",body:{dfp_telemetry_id:e,captcha_token:t},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})}async get(){return this._networkClient.fetchSDK({url:"/b2b/recovery_codes",method:"GET"})}}class ex{_networkClient;_subscriptionService;constructor(e,t){this._networkClient=e,this._subscriptionService=t}async createConnection(e){return await this._networkClient.fetchSDK({url:"/b2b/scim",method:"POST",body:e})}async updateConnection(e){return await this._networkClient.fetchSDK({url:`/b2b/scim/${e.connection_id}`,method:"PUT",body:e})}async deleteConnection(e){return await this._networkClient.fetchSDK({url:`/b2b/scim/${e}`,method:"DELETE"})}async getConnection(){return await this._networkClient.fetchSDK({url:"/b2b/scim",method:"GET"})}async getConnectionGroups(e){return await this._networkClient.fetchSDK({url:"/b2b/scim/groups",method:"POST",body:e})}async rotateStart(e){return await this._networkClient.fetchSDK({url:"/b2b/scim/rotate/start",method:"POST",body:{connection_id:e}})}async rotateComplete(e){return await this._networkClient.fetchSDK({url:"/b2b/scim/rotate/complete",method:"POST",body:{connection_id:e}})}async rotateCancel(e){return await this._networkClient.fetchSDK({url:"/b2b/scim/rotate/cancel",method:"POST",body:{connection_id:e}})}}class eB{_networkClient;_apiNetworkClient;_subscriptionService;constructor(e,t,i){this._networkClient=e,this._apiNetworkClient=t,this._subscriptionService=i}get=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/me",method:"GET"});return this._subscriptionService.updateMember(e.member),e.member};getSync=()=>this._subscriptionService.getMember();getInfo=()=>({member:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>this._subscriptionService.subscribeToState(t=>e(t?.member??null));update=async e=>{let t=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/update",body:e,method:"PUT"});return this._subscriptionService.updateMember(t.member),t};deleteMFAPhoneNumber=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/deletePhoneNumber",method:"DELETE"});return this._subscriptionService.updateMember(e.member),e};deleteMFATOTP=async()=>{let e=await this._networkClient.fetchSDK({url:"/b2b/organizations/members/deleteTOTP",method:"DELETE"});return this._subscriptionService.updateMember(e.member),e};deletePassword=async e=>{let t=await this._networkClient.fetchSDK({url:`/b2b/organizations/members/passwords/${e}`,method:"DELETE"});return this._subscriptionService.updateMember(t.member),t};unlinkRetiredEmail=async e=>{let t=await this._apiNetworkClient.fetchSDK({url:"/b2b/organizations/members/unlink_retired_email",method:"POST",body:e});return this._subscriptionService.updateMember(t.member),t};startEmailUpdate=async e=>{let t=await this._apiNetworkClient.fetchSDK({url:"/b2b/organizations/members/start_email_update",method:"POST",body:e});return this._subscriptionService.updateMember(t.member),t};getConnectedApps=async()=>this._networkClient.fetchSDK({url:"/b2b/organizations/members/connected_apps",method:"GET"});revokeConnectedApp=async e=>this._networkClient.fetchSDK({url:`/b2b/organizations/members/connected_apps/${e.connected_app_id}/revoke`,method:"POST"})}class eK{_networkClient;_subscriptionService;getSync=()=>this._subscriptionService.getSession();getInfo=()=>({session:this.getSync(),fromCache:this._subscriptionService.getFromCache()});onChange=e=>this._subscriptionService.subscribeToState(t=>e(t?.session??null));revoke=async e=>{try{let e=await this._networkClient.fetchSDK({url:"/b2b/sessions/revoke",method:"POST"});return this._subscriptionService.destroyState(),e}catch(t){throw e?.forceClear?this._subscriptionService.destroyState():w.includes(t.error_type)&&this._subscriptionService.destroyState(),t}};revokeForMember=async e=>await this._networkClient.fetchSDK({url:`/b2b/sessions/revoke/${e.member_id}`,method:"POST"});_authenticate=async e=>{let t=this._subscriptionService.getSession(),i=()=>t?.member_session_id!==this._subscriptionService.getSession()?.member_session_id;try{let t={session_duration_minutes:e?.session_duration_minutes},r=await this._networkClient.fetchSDK({url:"/b2b/sessions/authenticate",body:t,method:"POST"});if(i())return this._authenticate(e);return r}catch(t){if(i())return this._authenticate(e);throw w.includes(t.error_type)&&this._subscriptionService.destroySession(),t}};authenticate;exchange;exchangeAccessToken;attest;constructor(e,t){this._networkClient=e,this._subscriptionService=t,this.authenticate=this._subscriptionService.withUpdateSession(this._authenticate),this.exchange=this._subscriptionService.withUpdateSession(async e=>this._networkClient.fetchSDK({url:"/b2b/sessions/exchange",body:e,method:"POST"})),this.exchangeAccessToken=this._subscriptionService.withUpdateSession(async e=>this._networkClient.fetchSDK({url:"/b2b/sessions/exchange_access_token",body:e,method:"POST"})),this.attest=this._subscriptionService.withUpdateSession(async e=>this._networkClient.fetchSDK({url:"/b2b/sessions/attest",body:e,method:"POST"}))}getTokens(){return this._subscriptionService.getTokens()}updateSession(e){this._subscriptionService.updateTokens(e)}}class eF{_networkClient;_subscriptionService;_pkceManager;_dynamicConfig;_config;dfpProtectedAuth;authenticate;constructor(e,t,i,r,s,n){this._networkClient=e,this._subscriptionService=t,this._pkceManager=i,this._dynamicConfig=r,this._config=s,this.dfpProtectedAuth=n,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{let t=await this._pkceManager.getPKPair();t||l("No code verifier found in local storage for SSO flow.\nConsider using stytch.sso.start() to add PKCE to your SSO flows for added security.\nSee https://stytch.com/docs/oauth#guides_pkce for more information.");let{dfp_telemetry_id:i,captcha_token:r}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),s=await this._networkClient.retriableFetchSDK({url:"/b2b/sso/authenticate",method:"POST",body:{pkce_code_verifier:t?.code_verifier,...e,dfp_telemetry_id:i,captcha_token:r,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0},retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return this._pkceManager.clearPKPair(),s})}async getBaseApiUrl(){return this._config.publicToken.includes("public-token-test")?this._config.testAPIURL:this._config.liveAPIURL}async start({connection_id:e,login_redirect_url:t,signup_redirect_url:i}){let{pkceRequiredForSso:r}=await this._dynamicConfig,s=await this.getBaseApiUrl(),n=new URL(`${s}/v1/public/sso/start`);if(n.searchParams.set("public_token",this._config.publicToken),n.searchParams.set("connection_id",e),r){let e=await this._pkceManager.startPKCETransaction();n.searchParams.set("pkce_code_challenge",e.code_challenge)}else this._pkceManager.clearPKPair();t&&n.searchParams.set("login_redirect_url",t),i&&n.searchParams.set("signup_redirect_url",i),this.navigate(n)}navigate(e){window.location.href=e.toString()}async getConnections(){return await this._networkClient.fetchSDK({url:"/b2b/sso",method:"GET"})}async discoverConnections(e){return await this._networkClient.fetchSDK({url:`/b2b/sso/discovery/connections?email_address=${encodeURIComponent(e)}`,method:"GET"})}async deleteConnection(e){return this._networkClient.fetchSDK({url:`/b2b/sso/${e}`,method:"DELETE"})}saml={createConnection:async e=>await this._networkClient.fetchSDK({url:"/b2b/sso/saml",method:"POST",body:e}),updateConnection:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}`,method:"PUT",body:e}),updateConnectionByURL:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}/url`,method:"PUT",body:e}),deleteVerificationCertificate:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}/verification_certificates/${e.certificate_id}`,method:"DELETE"}),deleteEncryptionPrivateKey:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/saml/${e.connection_id}/encryption_private_key/${e.private_key_id}`,method:"DELETE"})};oidc={createConnection:async e=>await this._networkClient.fetchSDK({url:"/b2b/sso/oidc",method:"POST",body:e}),updateConnection:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/oidc/${e.connection_id}`,method:"PUT",body:e})};external={createConnection:async e=>await this._networkClient.fetchSDK({url:"/b2b/sso/external",method:"POST",body:e}),updateConnection:async e=>await this._networkClient.fetchSDK({url:`/b2b/sso/external/${e.connection_id}`,method:"PUT",body:e})}}class ej{_networkClient;_subscriptionService;dfpProtectedAuth;authenticate;constructor(e,t,i){this._networkClient=e,this._subscriptionService=t,this.dfpProtectedAuth=i,this.authenticate=this._subscriptionService.withUpdateSession(async e=>{let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r={...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:this._subscriptionService.getIntermediateSessionToken()||void 0};return this._networkClient.retriableFetchSDK({url:"/b2b/totp/authenticate",body:r,method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP})})}async create(e){let{dfp_telemetry_id:t,captcha_token:i}=await this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha(),r=await this._networkClient.retriableFetchSDK({url:"/b2b/totp",body:{...e,dfp_telemetry_id:t,captcha_token:i,intermediate_session_token:await this._subscriptionService.getIntermediateSessionToken()||void 0},method:"POST",retryCallback:this.dfpProtectedAuth.retryWithCaptchaAndDFP});return r.member_id===this._subscriptionService.getMember()?.member_id&&this._subscriptionService.updateMember(r.member),r}}class ez{_subscriptionService;emptyState;constructor(e,t){this._subscriptionService=e,this.emptyState=t}onStateChange=e=>this._subscriptionService.subscribeToState(t=>{e(t??this.emptyState)})}class eq{hasWarned=!1;registry=new Map;register(e,t){let i=this.registry.get(e);i&&i!==t&&(this.hasWarned||(l(v),this.hasWarned=!0),i.cancelBackgroun
18dRefresh()),this.registry.set(e,t)}unregister(e,t){let i=this.registry.get(e);i&&i===t&&this.registry.delete(e)}}class eH{_subscriptionService;_headlessSessionClient;_publicToken;_options;static REFRESH_INTERVAL_MS=18e4;timeout=null;lastAuthenticationSessionDuration;static registry=new eq;register(){eH.registry.register(this._publicToken,this)}unregister(){eH.registry.unregister(this._publicToken,this)}constructor(e,t,i,r){this._subscriptionService=e,this._headlessSessionClient=t,this._publicToken=i,this._options=r,this._subscriptionService.subscribeToState(this._onDataChange)}performBackgroundRefresh(){this._reauthenticateWithBackoff().then(()=>{this.scheduleBackgroundRefresh()}).catch(e=>{l("Session background refresh failed. Signalling to app that user is logged out.",{error:e}),this._subscriptionService.destroySession()})}scheduleBackgroundRefresh(){this.cancelBackgroundRefresh(),this.register(),this.timeout=setTimeout(()=>{this.performBackgroundRefresh()},eH.REFRESH_INTERVAL_MS)}cancelBackgroundRefresh(){null!==this.timeout&&(this.unregister(),clearTimeout(this.timeout),this.timeout=null)}_onDataChange=e=>{null!=e&&e.sessionDurationMinutes&&(this.lastAuthenticationSessionDuration=e.sessionDurationMinutes),e?.session?this.scheduleBackgroun
18dRefresh():this.cancelBackgroundRefresh()};_reauthenticateWithBackoff=async()=>{let e=0;for(;;)try{let e={session_duration_minutes:this._options.keepSessionAlive?this.lastAuthenticationSessionDuration:void 0};return await this._headlessSessionClient.authenticate(e)}catch(t){if(eH.isUnrecoverableError(t))return Promise.reject(t);e++,await new Promise(t=>setTimeout(t,eH.timeoutForAttempt(e)))}};static timeoutForAttempt(e){return e=Math.min(e,7),Math.floor(350*Math.random())-175+2e3*2**e}static isUnrecoverableError(e){return w.includes(e.error_type)}}class eQ{_networkClient;dfpProtectedAuth;constructor(e,t){this._networkClient=e,this.dfpProtectedAuth=t}searchUser(e){return this.dfpProtectedAuth.getDFPTelemetryIDAndCaptcha().then(({dfp_telemetry_id:t,captcha_token:i})=>this._networkClient.fetchSDK({url:"/users/search",method:"POST",body:{email:e,dfp_telemetry_id:t,captcha_token:i}}))}searchMember(e,t){return this._networkClient.fetchSDK({url:"/b2b/organizations/members/search",method:"POST",body:{email_address:e,organization_id:t}})}}let eG=(0,a.ssrSafeClientFactory)(class{_subscriptionService;_sessionManager;_networkClient;_dataLayer;_stateChangeClient;magicLinks;session;member;self;organization;oauth;sso;discovery;passwords;otps;totp;recoveryCodes;rbac;scim;impersonation;idp;onStateChange;parseAuthenticateUrl;authenticateByUrl;constructor(e,t){if("u"<typeof window)throw Error("`new StytchB2BClient()` is not supported in server environments. If using @stytch/react or @stytch/nextjs, use `createStytchB2BClient()` instead.");(e=>{"string"!=typeof e?l(`Public token is malformed. Expected a string, got ${typeof e}.${eP}`):""===e?l(`Public token is malformed. Expected "public-token-...", got an empty string.${eP}`):e.startsWith("public-token-")||l(`Public token is malformed. Expected "public-token-...", got ${e}.${eP}`)})(e);const i=e??"",r=((e,t={})=>{let{cookieOptions:i,keepSessionAlive:r}=t;return{cookieOptions:i,keepSessionAlive:r,endpoints:{testAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.testApiDomain;if(t){let i=el(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"testApiDomain";l(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.testAPIURL??"https://test.stytch.com"})(t),liveAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.apiDomain;if(t){let i=el(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"apiDomain";l(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.liveAPIURL??"https://api.stytch.com"})(t),dfpBackendURL:(e=>{let t=e?.dfppaUrl??e?.endpointOptions?.dfppaDomain;if(t){let i=el(t);if(i)return i;{let i=e?.dfppaUrl?"dfppaUrl":"dfppaDomain";l(`Unable to use custom DFPPA domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.dfpBackendURL??"https://telemetry.stytch.com"})(t),dfpCdnURL:(e=>{let t=e?.dfpCdnUrl??e?.endpointOptions?.dfpCdnDomain;if(t){let i=el(t);if(i)return i;{let i=e?.dfpCdnUrl?"dfpCdnUrl":"dfpCdnDomain";l(`Unable to use custom DFP CDN domain \`${t}\`. ${i} should be a valid domain.`)}}return"https://elements.stytch.com"})(t),clientsideServicesIframeURL:t?.endpoints?.clientsideServicesIframeURL??"https://js.stytch.com/clientside-services/index.html"}}})(this.constructor.name,t),s=((e,t={})=>{let{customBaseUrl:i,endpointOptions:r}=t;return e.includes("public-token-test")?!!(i||r?.testApiDomain):!!(i||r?.apiDomain)})(i,t);this._dataLayer=((e,t)=>{let i,r=((i=window)[er]||(i[er]={}),i[er]);return r[e]||(r[e]=new ei(e,t)),r[e]})(i,r),this._subscriptionService=new eo(i,this._dataLayer,{usingCustomApiEndpoint:s}),this._stateChangeClient=new ez(this._subscriptionService,{}),this.onStateChange=(...e)=>this._stateChangeClient.onStateChange(...e);const n=()=>({stytch_member_id:this._dataLayer.state?.member?.member_id,stytch_member_session_id:this._dataLayer.state?.session?.member_session_id}),a=new q(this._dataLayer,"passwords"),o=new j(i,this._dataLayer,r.endpoints.liveAPIURL,r.endpoints.testAPIURL,n);this._networkClient=o;const u=new d(i,o,this._dataLayer),h=new f(u.getAsync()),g=new em(i,r.endpoints.dfpBacken
18dURL,r.endpoints.dfpCdnURL,u.getAsync(),h.executeRecaptcha),p=new D(r.endpoints.clientsideServicesIframeURL),m=new q(this._dataLayer,"oauth"),y=new eC(o,m,u.getAsync());this.organization=new eT(o,o,this._subscriptionService),this.member=new eB(o,o,this._subscriptionService),this.self=new eB(o,o,this._subscriptionService),this.session=new eK(o,this._subscriptionService),this.magicLinks=new eO(o,this._subscriptionService,new q(this._dataLayer,"magic_links"),a,u.getAsync(),g),this.oauth=new eb(o,this._subscriptionService,m,u.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},g,y),this.sso=new eF(o,this._subscriptionService,new q(this._dataLayer,"sso"),u.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},g),this.discovery=new eE(o,this._subscriptionService),this.passwords=new eM(o,this._subscriptionService,a,u.getAsync(),g),this.otps=new eR(o,this._subscriptionService,g),this.totp=new ej(o,this._subscriptionService,g),this.recoveryCodes=new eU(o,this._subscriptionService,g),this.rbac=new eN(u.getSync(),u.getAsync(),this._subscriptionService),this.scim=new ex(this._networkClient,this._subscriptionService),this.impersonation=new eI(this._networkClient,this._subscriptionService,g),this.idp=new eA(o),this._sessionManager=new eH(this._subscriptionService,this.session,i,{keepSessionAlive:r.keepSessionAlive});const v=new eQ(o,g);(s||this._dataLayer.readSessionCookie().session_token)&&this._sessionManager.performBackgroundRefresh();const{authenticateByUrl:b,parseAuthenticateUrl:_}=(e=>{let t=Object.keys(e),i=(e=window.location.href)=>{let i=new URL(e),r=i.searchParams.get("stytch_token_type"),s=i.searchParams.get("token");return s&&r?t.includes(r)?{handled:!0,token:s,tokenType:r}:{handled:!1,token:s,tokenType:r}:null};return{authenticateByUrl:async({clearParams:t,...r},s=window.location.href)=>{let n,a,o,l=t??s===window.location.href,c=i(s);if(null==c)return null;if(!c.handled)return c;let{token:u,tokenType:h}=c,d=e[h];return l&&((a=(n=new URL(window.location.toString())).searchParams).delete("token"),a.delete("stytch_token_type"),o=n,window.history.replaceState(null,document.title,o)),{handled:!0,tokenType:h,data:await d(u,r)}},parseAuthenticateUrl:i}})({discovery:e=>this.magicLinks.discovery.authenticate({discovery_magic_links_token:e}),discovery_oauth:e=>this.oauth.discovery.authenticate({discovery_oauth_token:e}),oauth:(e,t)=>this.oauth.authenticate({oauth_token:e,...t}),sso:(e,t)=>this.sso.authenticate({sso_token:e,...t}),multi_tenant_magic_links:(e,t)=>this.magicLinks.authenticate({magic_links_token:e,...t}),multi_tenant_impersonation:e=>this.impersonation.authenticate({impersonation_token:e})});this.authenticateByUrl=b,this.parseAuthenticateUrl=_,o.logEvent({name:"b2b_sdk_instance_instantiated",details:{event_callback_registered:!1,error_callback_registered:!1,success_callback_registered:!1}}),u.getAsync().then(e=>{"CONSUMER"===e.vertical&&c("This application is using a Stytch client for B2B projects, but the public token is for a Stytch Consumer project. Use a Consumer Stytch client instead, or verify that the public token is correct.")}),((e,t)=>{Object.assign(e,{[ec]:t})})(this,{bootstrap:u,clientsideServices:p,publicToken:i,searchManager:v,dataLayer:this._dataLayer,networkClient:o,oneTap:y})}});var eW=e.i(544259);let eV=eG("public-token-live-bbc59d30-d3c8-4815-a5be-fede00306680",{cookieOptions:{opaqueTokenCookieName:eW.STYTCH_SESSION_TOKEN_COOKIE_NAME,jwtCookieName:eW.STYTCH_SESSION_JWT_COOKIE_NAME,istCookieName:eW.STYTCH_INTERMEDIATE_SESSION_TOKEN_COOKIE_NAME,path:"",availableToSubdomains:!1,domain:""},endpointOptions:{dfppaDomain:"telemetry.assemblyai.com"}});e.s(["AuthenticationProvider",0,function(e){let t,i=(0,s.c)(2),{children:a}=e;return i[0]!==a?(t=(0,r.jsx)(n.StytchB2BProvider,{stytch:eV,children:a}),i[0]=a,i[1]=t):t=i[1],t}],204186)},922538,e=>{"use strict";var t=e.i(28722),i=e.i(604576),r=e.i(884109),s=e.i(260936),n=e.i(922310);function a(){}e.s(["ComplianceProvider",0,function(e){let o,l,c,u,h=(0,i.c)(10),{children:d,options:g}=e,[p,f]=(0,r.useState)("loading"),[m,y]=(0,r.useState)(null),[v,b]=(0,r.useState)(null);h[0]!==g?(o=()=>{let e=n.ComplianceService.init(g),t=()=>{f(e.state),y(e.getConsent()),b(e)};return e.addListener(e=>{y(e),t()}),t(),a},l=[g],h[0]=g,h[1]=o,h[2]=l):(o=h[1],l=h[2]),(0,r.useEffect)(o,l);let _=m??void 0,S=v??void 0;h[3]!==p||h[4]!==_||h[5]!==S?(c={state:p,consent:_,instance:S,acceptAll:n.ComplianceService.acceptAll,rejectAll:n.ComplianceService.rejectAll,toggleSettings:n.ComplianceService.toggleSettings},h[3]=p,h[4]=_,h[5]=S,h[6]=c):c=h[6];let k=c;return h[7]!==d||h[8]!==k?(u=(0,t.jsx)(s.ComplianceContext.Provider,{value:k,children:d}),h[7]=d,h[8]=k,h[9]=u):u=h[9],u}])},972897,e=>{"use strict";let t;var i=e.i(28722),r=e.i(604576),s=e.i(944443),n=e.i(615046),a=e.i(432868),o=e.i(493284),l=e.i(881693),c=class extends l.Subscribable{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,i){let r=t.queryKey,s=t.queryHash??(0,n.hashQueryKeyByOptions)(r,t),o=this.get(s);return o||(o=new a.Query({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:i,defaultOptions:e.getQueryDefaults(r)}),this.add(o)),o}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){o.notifyManager.batch(()=>
18{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>(0,n.matchQuery)(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>(0,n.matchQuery)(e,t)):t}notify(e){o.notifyManager.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){o.notifyManager.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){o.notifyManager.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},u=e.i(548789),h=l,d=class extends h.Subscribable{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#i=new Map,this.#r=0}#t;#i;#r;build(e,t,i){let r=new u.Mutation({client:e,mutationCache:this,mutationId:++this.#r,options:e.defaultMutationOptions(t),state:i});return this.add(r),r}add(e){this.#t.add(e);let t=g(e);if("string"==typeof t){let i=this.#i.get(t);i?i.push(e):this.#i.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){let t=g(e);if("string"==typeof t){let i=this.#i.get(t);if(i)if(i.length>1){let t=i.indexOf(e);-1!==t&&i.splice(t,1)}else i[0]===e&&this.#i.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){let t=g(e);if("string"!=typeof t)return!0;{let i=this.#i.get(t),r=i?.find(e=>"pending"===e.state.status);return!r||r===e}}runNext(e){let t=g(e);if("string"!=typeof t)return Promise.resolve();{let i=this.#i.get(t)?.find(t=>
18t!==e&&t.state.isPaused);return i?.continue()??Promise.resolve()}}clear(){o.notifyManager.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#i.clear()})}getAll(){return Array.from(this.#t)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>(0,n.matchMutation)(t,e))}findAll(e={}){return this.getAll().filter(t=>(0,n.matchMutation)(e,t))}notify(e){o.notifyManager.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return o.notifyManager.batch(()=>Promise.all(e.map(e=>e.continue().catch(n.noop))))}};function g(e){return e.options.scope?.id}var p=e.i(735795),f=e.i(45536),m=e.i(142669),y=class{#s;#n;#a;#o;#l;#c;#u;#h;constructor(e={}){this.#s=e.queryCache||new c,this.#n=e.mutationCache||new d,this.#a=e.defaultOptions||{},this.#o=new Map,this.#l=new Map,this.#c=0}mount(){this.#c++,1===this.#c&&(this.#u=p.focusManager.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#s.onFocus())}),this.#h=f.onlineManager.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#s.onOnline())}))}unmount(){this.#c--,0===this.#c&&(this.#u?.(),this.#u=void 0,this.#h?.(),this.#h=void 0)}isFetching(e){return this.#s.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#n.findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#s.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),i=this.#s.build(this,t),r=i.state.data;return void 0===r?this.fetchQuery(e):(e.revalidateIfStale&&i.isStaleByTime((0,n.resolveStaleTime)(t.staleTime,i))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#s.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,i){let r=this.defaultQueryOptions({queryKey:e}),s=this.#s.get(r.queryHash),a=s?.state.data,o=(0,n.functionalUpdate)(t,a);if(void 0!==o)return this.#s.build(this,r).setData(o,{...i,manual:!0})}setQueriesData(e,t,i){return o.notifyManager.batch(()=>this.#s.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,i)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#s.get(t.queryHash)?.state}removeQueries(e){let t=this.#s;o.notifyManager.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let i=this.#s;return o.notifyManager.batch(()=>(i.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let i={revert:!0,...t};return Promise.all(o.notifyManager.batch(()=>this.#s.findAll(e).map(e=>e.cancel(i)))).then(n.noop).catch(n.noop)}invalidateQueries(e,t={}){return o.notifyManager.batch(()=>(this.#s.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType==="none")?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t))}refetchQueries(e,t={}){let i={...t,cancelRefetch:t.cancelRefetch??!0};return Promise.all(o.notifyManager.batch(()=>this.#s.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,i);return i.throwOnError||(t=t.catch(n.noop)),"paused"===e.state.fetchStatus?Promise.resolve():t}))).then(n.noop)}fetchQuery(e){let t=this.defaultQueryOptions(e);void 0===t.retry&&(t.retry=!1);let i=this.#s.build(this,t);return i.isStaleByTime((0,n.resolveStaleTime)(t.staleTime,i))?i.fetch(t):Promise.resolve(i.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(n.noop).catch(n.noop)}fetchInfiniteQuery(e){return e.behavior=(0,m.infiniteQueryBehavior)(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(n.noop).catch(n.noop)}ensureInfiniteQueryData(e){return e.behavior=(0,m.infiniteQueryBehavior)(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return f.onlineManager.isOnline()?this.#n.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#s}getMutationCache(){return this.#n}getDefaultOptions(){return this.#a}setDefaultOptions(e){this.#a=e}setQueryDefaults(e,t){this.#o.set((0,n.hashKey)(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#o.values()],i={};return t.forEach(t=>{(0,n.partialMatchKey)(e,t.queryKey)&&Object.assign(i,t.defaultOptions)}),i}setMutationDefaults(e,t){this.#l.set((0,n.hashKey)(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#l.values()],i={};return t.forEach(t=>{(0,n.partialMatchKey)(e,t.mutationKey)&&Object.assign(i,t.defaultOptions)}),i}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#a.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=(0,n.hashQueryKeyByOptions)(t.queryKey,t)),void 0===t.refetchOnReconnect&&(t.refetchOnReconnect="always"!==t.networkMode),void 0===t.throwOnError&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===n.skipToken&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#a.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#s.clear(),this.#n.clear()}},v=e.i(59615);function b(){return new y({defaultOptions:{queries:{staleTime:6e4},dehydrate:{shouldDehydrateQuery:e=>(0,v.defaultShouldDehydrateQuery)(e)||"pending"===e.state.status}}})}e.s(["QueryProvider",0,function(e){let a,o,l=(0,r.c)(3),{children:c}=e;l[0]===Symbol.for("react.memo_cache_sentinel")?(a=n.isServer?b():(t||(t=b()),t),l[0]=a):a=l[0];let u=a;return l[1]!==c?(o=(0,i.jsx)(s.QueryClientProvider,{client:u,children:c}),l[1]=c,l[2]=o):o=l[2],o}],972897)}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.