@descope/web-component 3.49.0 → 3.49.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  !function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}function n(e,t,n,o){return new(n||(n=Promise))((function(i,r){function s(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}))}function o(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function i(e,t,n,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?i.call(e,n):i?i.value=n:t.set(e,n),n}"function"==typeof SuppressedError&&SuppressedError;class r extends Error{}function s(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return atob(t)}}function a(e,t){if("string"!=typeof e)throw new r("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,o=e.split(".")[n];if("string"!=typeof o)throw new r(`Invalid token specified: missing part #${n+1}`);let i;try{i=s(o)}catch(e){throw new r(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new r(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}r.prototype.name="InvalidTokenError";var l={accessKey:{exchange:"/v1/auth/accesskey/exchange"},otp:{verify:"/v1/auth/otp/verify",signIn:"/v1/auth/otp/signin",signUp:"/v1/auth/otp/signup",update:{email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},signUpOrIn:"/v1/auth/otp/signup-in"},magicLink:{verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/magiclink/signin",signUp:"/v1/auth/magiclink/signup",update:{email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},signUpOrIn:"/v1/auth/magiclink/signup-in"},enchantedLink:{verify:"/v1/auth/enchantedlink/verify",signIn:"/v1/auth/enchantedlink/signin",signUp:"/v1/auth/enchantedlink/signup",session:"/v1/auth/enchantedlink/pending-session",update:{email:"/v1/auth/enchantedlink/update/email"},signUpOrIn:"/v1/auth/enchantedlink/signup-in"},oauth:{start:"/v1/auth/oauth/authorize",exchange:"/v1/auth/oauth/exchange",startNative:"v1/auth/oauth/native/start",finishNative:"v1/auth/oauth/native/finish",oneTap:{getOneTapClientId:"/v1/auth/onetap/clientid/{provider}",exchangeOneTapIDToken:"/v1/auth/onetap/idtoken/exchange",verifyOneTapIDToken:"/v1/auth/onetap/idtoken/verify"}},outbound:{connect:"/v1/outbound/oauth/connect"},saml:{start:"/v1/auth/saml/authorize",exchange:"/v1/auth/saml/exchange"},totp:{verify:"/v1/auth/totp/verify",signUp:"/v1/auth/totp/signup",update:"/v1/auth/totp/update"},notp:{signIn:"/v1/auth/notp/whatsapp/signin",signUp:"/v1/auth/notp/whatsapp/signup",signUpOrIn:"/v1/auth/notp/whatsapp/signup-in",session:"/v1/auth/notp/pending-session"},webauthn:{signUp:{start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},signIn:{start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},signUpOrIn:{start:"/v1/auth/webauthn/signup-in/start"},update:{start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"}},password:{signUp:"/v1/auth/password/signup",signIn:"/v1/auth/password/signin",sendReset:"/v1/auth/password/reset",update:"/v1/auth/password/update",replace:"/v1/auth/password/replace",policy:"/v1/auth/password/policy"},refresh:"/v1/auth/refresh",tryRefresh:"/v1/auth/try-refresh",selectTenant:"/v1/auth/tenant/select",logout:"/v1/auth/logout",logoutAll:"/v1/auth/logoutall",me:"/v1/auth/me",myTenants:"/v1/auth/me/tenants",history:"/v1/auth/me/history",flow:{start:"/v1/flow/start",next:"/v1/flow/next"}};const c="<region>",d=`https://api.${c}descope.com`,u=6e5,p="dct",h=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},retries(t){return e.Retries=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},g=[521,524],f=e=>async(...t)=>{let n=await e(...t);g.includes(n.status)&&(n=await e(...t),n.retries=1);const o=await n.text();return n.text=()=>Promise.resolve(o),n.json=()=>Promise.resolve(JSON.parse(o)),n.clone=()=>n,n};let v;const m=()=>{if(v)return v;const e=new Date,t=`${e.getUTCFullYear().toString()}-${(e.getUTCMonth()+1).toString().padStart(2,"0")}-${e.getUTCDate().toString().padStart(2,"0")}-${e.getUTCHours().toString().padStart(2,"0")}:${e.getUTCMinutes().toString().padStart(2,"0")}:${e.getUTCSeconds().toString().padStart(2,"0")}:${e.getUTCMilliseconds().toString()}`,n=Math.floor(1e3+9e3*Math.random());return v=`${t}-${n}`,v};var b;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT",e.patch="PATCH"}(b||(b={}));const w=({path:e,baseUrl:t,queryParams:n,projectId:o})=>{const i=o.slice(1,-27);t=t.replace(c,i?i+".":"");let r=e?`${t.replace(/\/$/,"")}/${null==e?void 0:e.replace(/^\//,"")}`:t;if(n){const e=Object.keys(n);e.forEach(((t,o)=>{r=`${r}${0===o?"?":""}${t}=${encodeURIComponent(n[t])}${o===e.length-1?"":"&"}`}))}return r},y=(...e)=>new Headers(e.reduce(((e,t)=>((e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t).forEach((([t,n])=>{e[t]="function"==typeof n?n():n})),e)),{})),k={"Content-Type":"application/json"},I=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},S=(e,t)=>{const n={"x-descope-sdk-session-id":m(),"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.52.2","x-descope-project-id":e};return t&&(n["x-descope-refresh-cookie-name"]=t),n},O=e=>{try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e};var C=e=>{var t;return(({baseUrl:e,projectId:t,baseConfig:n,refreshCookieName:o,logger:i,hooks:r,cookiePolicy:s,fetch:a})=>{const l=e||d,c=((e,t)=>{const n=t||fetch;return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>h().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const o=await f(n)(...t);return e[o.ok?"log":"error"](await(async e=>{const t=await e.text();return h().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).retries(e.retries).build()})(o)),o}:f(n)})(i,a),u=async e=>{var i;const a=(null==r?void 0:r.beforeRequest)?r.beforeRequest(e):e,{path:d,body:u,headers:p,queryParams:h,method:g,token:f}=a,v=(e=>void 0===e?void 0:JSON.stringify(e))(u),m={headers:y(I(t,f),S(t,o),(null==n?void 0:n.baseHeaders)||{},O(v)?k:{},p),method:g,body:v};null!==s&&(m.credentials=s||"include");const b=await c(w({path:d,baseUrl:l,queryParams:h,projectId:t}),m);if((null==r?void 0:r.afterRequest)&&await r.afterRequest(e,null==b?void 0:b.clone()),null==r?void 0:r.transformResponse){const e=await b.json(),t=((null===(i=b.headers)||void 0===i?void 0:i.get("set-cookie"))||"").split(";").reduce(((e,t)=>{const[n,o]=t.split("=");return Object.assign(Object.assign({},e),{[n.trim()]:o})}),{}),n=Object.assign(Object.assign({},b),{json:()=>Promise.resolve(e),cookies:t});return n.clone=()=>n,r.transformResponse(n)}return b};return{get:(e,{headers:t,queryParams:n,token:o}={})=>u({path:e,headers:t,queryParams:n,body:void 0,method:b.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:i}={})=>u({path:e,headers:n,queryParams:o,body:t,method:b.post,token:i}),patch:(e,t,{headers:n,queryParams:o,token:i}={})=>u({path:e,headers:n,queryParams:o,body:t,method:b.patch,token:i}),put:(e,t,{headers:n,queryParams:o,token:i}={})=>u({path:e,headers:n,queryParams:o,body:t,method:b.put,token:i}),delete:(e,{headers:t,queryParams:n,token:o}={})=>u({path:e,headers:t,queryParams:n,body:void 0,method:b.delete,token:o}),hooks:r,buildUrl:(e,n)=>w({projectId:t,baseUrl:l,path:e,queryParams:n})}})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:t=>{var n;const o=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==o?void 0:o.reduce(((e,t)=>t(e)),t)},afterRequest:async(t,n)=>{var o;const i=[].concat((null===(o=e.hooks)||void 0===o?void 0:o.afterRequest)||[]);0!=i.length&&(await Promise.allSettled(null==i?void 0:i.map((e=>e(t,null==n?void 0:n.clone()))))).forEach((t=>{var n;return"rejected"===t.status&&(null===(n=e.logger)||void 0===n?void 0:n.error(t.reason))}))},transformResponse:null===(t=e.hooks)||void 0===t?void 0:t.transformResponse}}))},x=429;function A(e,t,n){var o;let i=j(e);if(t){if(!(null==i?void 0:i.tenants)&&(null==i?void 0:i[p])===t)return(null==i?void 0:i[n])||[];i=null===(o=null==i?void 0:i.tenants)||void 0===o?void 0:o[t]}const r=null==i?void 0:i[n];return Array.isArray(r)?r:[]}function j(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return a(e)}function E(e){const{exp:t}=j(e);return(new Date).getTime()/1e3>t}function U(e){let t=j(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function R(e,t){return A(e,t,"permissions")}function T(e,t){return A(e,t,"roles")}const $=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function L(e,t){var n;const o=await e,i={code:o.status,ok:o.ok,response:o},r=await o.clone().json();return o.ok?i.data=r:(i.error=r,o.status===x&&Object.assign(i.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),i}function P(e){var t;return(null===(t=j(e))||void 0===t?void 0:t[p])||""}const W=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),N=(e,t)=>(n=t)=>t=>{const o=e.filter((e=>e(t)));return!(o.length<e.length)&&(n?n.replace("{val}",t):o.join(" OR "))},M=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),_=e=>t=>e.test(t),D=_(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),q=_(/^\+[1-9]{1}[0-9]{3,14}$/),F=W(D,'"{val}" is not a valid email'),K=W(q,'"{val}" is not a valid phone number'),J=W((e=>e.length>=1),"Minimum length is 1");const V=W((e=>"string"==typeof e),"Input is not a string"),H=W((e=>Array.isArray(e)),"Input is not an array"),B=W((e=>"boolean"==typeof e),"Input is not a boolean"),z=W((e=>void 0===e),"Input is defined"),G=N([V(),z()],"Input is not a string or undefined"),Z=N([H(),B()],"Input is not an array or boolean"),X=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>M(...e).validate(n[t]))),t(...n)),Y=e=>[V(`"${e}" must be a string`)],Q=e=>[G(`"${e}" must be string or undefined`)],ee=e=>[V(`"${e}" must be a string`),J(`"${e}" must not be empty`)],te=e=>[V(`"${e}" must be a string`),F()],ne=e=>[V(`"${e}" must be a string`),K()],oe=X(ee("accessKey")),ie=e=>({exchange:oe(((t,n)=>L(e.post(l.accessKey.exchange,{loginOptions:n},{token:t}))))}),re=(e,t,n)=>(t.forEach((t=>{const o=t.split(".");let i=o.shift(),r=e;for(;o.length>0;){if(r=r[i],!i||!r)throw Error(`Invalid path "${t}", "${i}" is missing or has no value`);i=o.shift()}if("function"!=typeof r[i])throw Error(`"${t}" is not a function`);const s=r[i];r[i]=n(s)})),e),se=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||u,u)});var ae,le;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(ae||(ae={})),function(e){e.email="email"}(le||(le={}));const ce=Object.assign(Object.assign({},ae),le);var de;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(de||(de={}));const ue=ee("loginId"),pe=X(ee("token")),he=X(ue),ge=X(ee("pendingRef")),fe=X(ue,te("email")),ve=e=>({verify:pe((t=>L(e.post(l.enchantedLink.verify,{token:t})))),signIn:he(((n,o,i={},r)=>{var{providerId:s}=i,a=t(i,["providerId"]);return L(e.post($(l.enchantedLink.signIn,ce.email),{loginId:n,URI:o,loginOptions:a,providerId:s},{token:r}))})),signUpOrIn:he(((n,o,i={})=>{var{providerId:r}=i,s=t(i,["providerId"]);return L(e.post($(l.enchantedLink.signUpOrIn,ce.email),{loginId:n,URI:o,loginOptions:s,providerId:r}))})),signUp:he(((n,o,i,r={})=>{var{providerId:s}=r,a=t(r,["providerId"]);return L(e.post($(l.enchantedLink.signUp,ce.email),{loginId:n,URI:o,user:i,loginOptions:a,providerId:s}))})),waitForSession:ge(((t,n)=>new Promise((o=>{const{pollingIntervalMs:i,timeoutMs:r}=se(n);let s;const a=setInterval((async()=>{const n=await e.post(l.enchantedLink.session,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(L(Promise.resolve(n))))}),i);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)})))),update:{email:fe(((t,n,o,i,r)=>L(e.post(l.enchantedLink.update.email,Object.assign({loginId:t,email:n,URI:o},r),{token:i}))))}}),me=X(ee("flowId")),be=X(ee("executionId"),ee("stepId"),ee("interactionId")),we=e=>({start:me(((t,n,o,i,r,s,a)=>L(e.post(l.flow.start,{flowId:t,options:n,conditionInteractionId:o,interactionId:i,componentsVersion:r,flowVersions:s,input:a})))),next:be(((t,n,o,i,r,s)=>L(e.post(l.flow.next,{executionId:t,stepId:n,interactionId:o,version:i,componentsVersion:r,input:s}))))}),ye=ee("loginId"),ke=X(ee("token")),Ie=X(ye),Se=X(ye,ne("phone")),Oe=X(ye,te("email")),Ce=Object.keys(ce).filter((e=>e!==ae.voice)),xe=e=>({verify:ke((t=>L(e.post(l.magicLink.verify,{token:t})))),signIn:Ce.reduce(((n,o)=>Object.assign(Object.assign({},n),{[o]:Ie(((n,i,r={},s)=>{var{providerId:a}=r,c=t(r,["providerId"]);return L(e.post($(l.magicLink.signIn,o),{loginId:n,URI:i,loginOptions:c,providerId:a},{token:s}))}))})),{}),signUp:Ce.reduce(((n,o)=>Object.assign(Object.assign({},n),{[o]:Ie(((n,i,r,s={})=>{var{providerId:a}=s,c=t(s,["providerId"]);return L(e.post($(l.magicLink.signUp,o),{loginId:n,URI:i,user:r,loginOptions:c,providerId:a}))}))})),{}),signUpOrIn:Ce.reduce(((n,o)=>Object.assign(Object.assign({},n),{[o]:Ie(((n,i,r={})=>{var{providerId:s}=r,a=t(r,["providerId"]);return L(e.post($(l.magicLink.signUpOrIn,o),{loginId:n,URI:i,loginOptions:a,providerId:s}))}))})),{}),update:{email:Oe(((t,n,o,i,r)=>L(e.post(l.magicLink.update.email,Object.assign({loginId:t,email:n,URI:o},r),{token:i})))),phone:Object.keys(ae).filter((e=>e!==ae.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Se(((t,o,i,r,s)=>L(e.post($(l.magicLink.update.phone,n),Object.assign({loginId:t,phone:o,URI:i},s),{token:r}))))})),{})}});var Ae;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin",e.slack="slack"}(Ae||(Ae={}));const je=X(ee("code")),Ee=e=>({start:Object.assign(((t,n,o,i,r)=>L(e.post(l.oauth.start,o||{},{queryParams:Object.assign(Object.assign({provider:t},n&&{redirectURL:n}),r&&{loginHint:r}),token:i}))),Object.keys(Ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,i,r)=>L(e.post(l.oauth.start,o||{},{queryParams:Object.assign(Object.assign({provider:n},t&&{redirectURL:t}),r&&{loginHint:r}),token:i}))})),{})),exchange:je((t=>L(e.post(l.oauth.exchange,{code:t})))),startNative:(t,n,o)=>L(e.post(l.oauth.startNative,{provider:t,loginOptions:n,implicit:o})),finishNative:(t,n,o,i,r)=>L(e.post(l.oauth.finishNative,{provider:t,stateId:n,user:o,code:i,idToken:r})),getOneTapClientId:t=>L(e.get(l.oauth.oneTap.getOneTapClientId.replace("{provider}",t))),verifyOneTapIDToken:(t,n,o,i)=>L(e.post(l.oauth.oneTap.verifyOneTapIDToken,{provider:t,idToken:n,nonce:o,loginOptions:i})),exchangeOneTapIDToken:(t,n,o,i)=>L(e.post(l.oauth.oneTap.exchangeOneTapIDToken,{provider:t,idToken:n,nonce:o,loginOptions:i}))}),Ue=ee("appId"),Re=X(Ue),Te=e=>({connect:Re(((t,n,o)=>{const i=null==n?void 0:n.tenantId,r=null==n?void 0:n.tenantLevel;return null==n||delete n.tenantId,null==n||delete n.tenantLevel,L(e.post(l.outbound.connect,{appId:t,tenantId:i,tenantLevel:r,options:n},{token:o}))}))}),$e=ee("loginId"),Le=X($e,ee("code")),Pe=X($e),We=X($e,ne("phone")),Ne=X($e,te("email")),Me=e=>({verify:Object.keys(ce).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Le(((t,o)=>L(e.post($(l.otp.verify,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(ce).reduce(((n,o)=>Object.assign(Object.assign({},n),{[o]:Pe(((n,i={},r)=>{var{providerId:s}=i,a=t(i,["providerId"]);return L(e.post($(l.otp.signIn,o),{loginId:n,loginOptions:a,providerId:s},{token:r}))}))})),{}),signUp:Object.keys(ce).reduce(((n,o)=>Object.assign(Object.assign({},n),{[o]:Pe(((n,i,r={})=>{var{providerId:s}=r,a=t(r,["providerId"]);return L(e.post($(l.otp.signUp,o),{loginId:n,user:i,loginOptions:a,providerId:s}))}))})),{}),signUpOrIn:Object.keys(ce).reduce(((n,o)=>Object.assign(Object.assign({},n),{[o]:Pe(((n,i={})=>{var{providerId:r}=i,s=t(i,["providerId"]);return L(e.post($(l.otp.signUpOrIn,o),{loginId:n,loginOptions:s,providerId:r}))}))})),{}),update:{email:Ne(((t,n,o,i)=>L(e.post(l.otp.update.email,Object.assign({loginId:t,email:n},i),{token:o})))),phone:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:We(((t,o,i,r)=>L(e.post($(l.otp.update.phone,n),Object.assign({loginId:t,phone:o},r),{token:i}))))})),{})}}),_e=X(ee("tenant")),De=X(ee("code")),qe=e=>({start:_e(((t,n,o,i,r,s,a)=>L(e.post(l.saml.start,o||{},Object.assign({queryParams:Object.assign(Object.assign(Object.assign(Object.assign({tenant:t},n&&{redirectURL:n}),r&&{ssoId:r}),s&&{forceAuthn:"true"}),a&&{loginHint:a})},i&&{token:i}))))),exchange:De((t=>L(e.post(l.saml.exchange,{code:t}))))}),Fe=ee("loginId"),Ke=X(Fe,ee("code")),Je=X(Fe),Ve=X(Fe),He=e=>({signUp:Je(((t,n)=>L(e.post(l.totp.signUp,{loginId:t,user:n})))),verify:Ke(((t,n,o,i)=>L(e.post(l.totp.verify,{loginId:t,code:n,loginOptions:o},{token:i})))),update:Ve(((t,n)=>L(e.post(l.totp.update,{loginId:t},{token:n}))))}),Be=ee("loginId"),ze=ee("newPassword"),Ge=X(Be,ee("password")),Ze=X(Be),Xe=X(Be,ze),Ye=X(Be,ee("oldPassword"),ze),Qe=e=>({signUp:Ge(((n,o,i,r={})=>{var{providerId:s}=r,a=t(r,["providerId"]);return L(e.post(l.password.signUp,{loginId:n,password:o,user:i,loginOptions:a,providerId:s}))})),signIn:Ge(((n,o,i={})=>{var{providerId:r}=i,s=t(i,["providerId"]);return L(e.post(l.password.signIn,{loginId:n,password:o,loginOptions:s,providerId:r}))})),sendReset:Ze(((t,n,o)=>L(e.post(l.password.sendReset,{loginId:t,redirectUrl:n,templateOptions:o})))),update:Xe(((t,n,o)=>L(e.post(l.password.update,{loginId:t,newPassword:n},{token:o})))),replace:Ye(((t,n,o)=>L(e.post(l.password.replace,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>L(e.get(l.password.policy))}),et=Y("loginId"),tt=ee("loginId"),nt=ee("origin"),ot=X(tt,nt,ee("name")),it=X(tt,nt),rt=X(et,nt),st=X(tt,nt,Q("token")),at=X(ee("transactionId"),ee("response")),lt=e=>({signUp:{start:ot(((t,n,o,i)=>L(e.post(l.webauthn.signUp.start,{user:{loginId:t,name:o},origin:n,passkeyOptions:i})))),finish:at(((t,n)=>L(e.post(l.webauthn.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:rt(((t,n,o,i,r)=>L(e.post(l.webauthn.signIn.start,{loginId:t,origin:n,loginOptions:o,passkeyOptions:r},{token:i})))),finish:at(((t,n)=>L(e.post(l.webauthn.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:it(((t,n,o)=>L(e.post(l.webauthn.signUpOrIn.start,{loginId:t,origin:n,passkeyOptions:o}))))},update:{start:st(((t,n,o,i)=>L(e.post(l.webauthn.update.start,{loginId:t,origin:n,passkeyOptions:i},{token:o})))),finish:at(((t,n)=>L(e.post(l.webauthn.update.finish,{transactionId:t,response:n}))))}}),ct=Y("loginId"),dt=X(ct),ut=X(ee("pendingRef")),pt=e=>({signUpOrIn:dt(((n,o={})=>{var{providerId:i}=o,r=t(o,["providerId"]);return L(e.post(l.notp.signUpOrIn,{loginId:n,loginOptions:r,providerId:i}))})),signUp:dt(((n,o,i={})=>{var{providerId:r}=i,s=t(i,["providerId"]);return L(e.post(l.notp.signUp,{loginId:n,user:o,providerId:r,loginOptions:s}))})),signIn:dt(((n,o={},i)=>{var{providerId:r}=o,s=t(o,["providerId"]);return L(e.post(l.notp.signIn,{loginId:n,loginOptions:s,providerId:r},{token:i}))})),waitForSession:ut(((t,n)=>new Promise((o=>{const{pollingIntervalMs:i,timeoutMs:r}=se(n);let s;const a=setInterval((async()=>{const n=await e.post(l.notp.session,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(L(Promise.resolve(n))))}),i);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)}))))}),ht=X(ee("token")),gt=X(Q("token"));var ft,vt=X([(ft=ee("projectId"),W(((e,t)=>n=>M(...t).validate(((e,t)=>{const n=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),o=n.length;let i=0,r=e===Object(e)?e:void 0;for(;null!=r&&i<o;)r=r[n[i++]];return i&&i===o&&void 0!==r?r:void 0})(n,e)))("projectId",ft))())])((e=>{const{projectId:t,logger:n,baseUrl:o,cookiePolicy:i,baseHeaders:r={},refreshCookieName:s,fetch:a}=e;return c=C({baseUrl:o,projectId:t,logger:n,hooks:{get beforeRequest(){var t;return null===(t=e.hooks)||void 0===t?void 0:t.beforeRequest},get afterRequest(){var t;return null===(t=e.hooks)||void 0===t?void 0:t.afterRequest},get transformResponse(){var t;return null===(t=e.hooks)||void 0===t?void 0:t.transformResponse}},cookiePolicy:i,baseConfig:{baseHeaders:r},refreshCookieName:s,fetch:a}),{accessKey:ie(c),otp:Me(c),magicLink:xe(c),enchantedLink:ve(c),oauth:Ee(c),outbound:Te(c),saml:qe(c),totp:He(c),notp:pt(c),webauthn:lt(c),password:Qe(c),flow:we(c),refresh:gt(((e,t,n,o)=>{const i={};n&&(i.externalToken=n);const r=o?l.tryRefresh:l.refresh;return L(c.post(r,i,{token:e,queryParams:t}))})),selectTenant:X([V("tenantId")],[G('"token" must be string or undefined')])(((e,t)=>L(c.post(l.selectTenant,{tenant:e},{token:t})))),logout:gt((e=>L(c.post(l.logout,{},{token:e})))),logoutAll:gt((e=>L(c.post(l.logoutAll,{},{token:e})))),me:gt((e=>L(c.get(l.me,{token:e})))),myTenants:X([Z('"tenants" must a string array or a boolean')],[G('"token" must be string or undefined')])(((e,t)=>{const n={};return"boolean"==typeof e?n.dct=e:n.ids=e,L(c.post(l.myTenants,n,{token:t}))})),history:gt((e=>L(c.get(l.history,{token:e})))),isJwtExpired:ht(E),getTenants:ht(U),getJwtPermissions:ht(R),getJwtRoles:ht(T),getCurrentTenant:ht(P),httpClient:c};var c})),mt=Object.assign(vt,{DeliveryMethods:ce});
2
- /*! js-cookie v3.0.5 | MIT */function bt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}var wt=function e(t,n){function o(e,o,i){if("undefined"!=typeof document){"number"==typeof(i=bt({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var r="";for(var s in i)i[s]&&(r+="; "+s,!0!==i[s]&&(r+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(o,e)+r}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],o={},i=0;i<n.length;i++){var r=n[i].split("="),s=r.slice(1).join("=");try{var a=decodeURIComponent(r[0]);if(o[a]=t.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}},remove:function(e,t){o(e,"",bt({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,bt({},this.attributes,t))},withConverter:function(t){return e(bt({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},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:"/"});var yt={default:"endpoint"},kt="Blocked by CSP",It="The endpoint parameter is not a valid URL",St="Failed to load the JS script of the agent",Ot="9319";function Ct(e,t){var n,o,i,r,s,a=[],l=(n=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var o,i=0,r=t.length;i<r;i++)!o&&i in t||(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),r=0,o=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,r++))},i=new Set,[n.current(),function(e,t){var r,s=t instanceof Error?t.message:"";if(s===kt||s===It)n.exclude(),r=0;else if(s===Ot)n.exclude();else if(s===St){var a=Date.now()-e.getTime()<50,l=n.current();l&&a&&!i.has(l)&&(i.add(l),r=0),n.postpone()}else n.postpone();var c=n.current();return void 0===c?void 0:[c,null!=r?r:e.getTime()+o()-Date.now()]}]),c=l[0],d=l[1];if(void 0===c)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var u=function(e){var n=new Date,o=function(t){return a.push({url:e,startedAt:n,finishedAt:new Date,error:t})},i=t(e);return i.then((function(){return o()}),o),i.catch((function(e){if(null!=s||(s=e),a.length>=5)throw s;var t=d(n,e);if(!t)throw s;var o,i=t[0],r=t[1];return(o=r,new Promise((function(e){return setTimeout(e,o)}))).then((function(){return u(i)}))}))};return u(c).then((function(e){return[e,a]}))}var xt="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",At=xt;function jt(n){var o;n.scriptUrlPattern;var i=n.token,r=n.apiKey,s=void 0===r?i:r,a=t(n,["scriptUrlPattern","token","apiKey"]),l=null!==(o=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(n,"scriptUrlPattern"))&&void 0!==o?o:xt,c=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,o){return e.addEventListener(t,n,o),function(){return e.removeEventListener(t,n,o)}}(document,"visibilitychange",t);return t(),[e,n]}(),d=c[0],u=c[1];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");var e=function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var n=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n("3.11.6"):e}))}(String(e),t)}))}(l,s);return Ct(e,Et)})).catch((function(e){throw u(),function(e){return e instanceof Error&&e.message===Ot?new Error(St):e}(e)})).then((function(t){var n=t[0],o=t[1];return u(),n.load(e(e({},a),{ldi:{attempts:o,visibilityStates:d}}))}))}function Et(e){return function(e,t,n){var o,i=document,r="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),i=t.blockedURI;i!==n.href&&i!==n.protocol.slice(0,-1)&&i!==n.origin||(o=t,a())};i.addEventListener(r,s);var a=function(){return i.removeEventListener(r,s)};return Promise.resolve().then(t).then((function(e){return a(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(a(),o)return n(o);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(It);var o=document.createElement("script"),i=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},r=document.head||document.getElementsByTagName("head")[0];o.onload=function(){i(),t()},o.onerror=function(){i(),n(new Error(St))},o.async=!0,o.src=e,r.appendChild(o)}))}(e)}),(function(){throw new Error(kt)})).then(Ut)}function Ut(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,o=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==o?void 0:o.configurable)?delete e[t]:o&&!o.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(Ot);return n}let Rt;const Tt=e=>{try{return a(e).exp}catch(e){return null}},$t=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:Tt(n)},Lt=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?Tt(o):void 0)},Pt=e=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=e,s=t(e,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:e.sessionJwt||n,idToken:o,refreshJwt:e.refreshJwt||i,sessionExpiration:e.sessionExpiration||Lt(e),cookieExpiration:e.cookieExpiration||$t(e)},s)},Wt=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},Nt=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json()),n=(null==t?void 0:t.authInfo)||t||{};return Pt(n)},Mt=void 0!==Rt||"undefined"!=typeof localStorage,_t=(e,t)=>{var n,o;return null===(o=null===(n=Rt||localStorage)||void 0===n?void 0:n.setItem)||void 0===o?void 0:o.call(n,e,t)},Dt=e=>{var t,n;return null===(n=null===(t=Rt||localStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,e)},qt=e=>{var t,n;return null===(n=null===(t=Rt||localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},Ft=e=>{var t,n,o,i;return null!==(i=null!==(n=null===(t=null==Rt?void 0:Rt.key)||void 0===t?void 0:t.call(Rt,e))&&void 0!==n?n:null===(o=null===localStorage||void 0===localStorage?void 0:localStorage.key)||void 0===o?void 0:o.call(localStorage,e))&&void 0!==i?i:null},Kt=(...e)=>{console.debug(...e)},Jt="3.2.0",Vt="undefined"!=typeof window,Ht=Math.pow(2,31)-1,Bt=`https://descopecdn.com/npm/oidc-client-ts@${Jt}/dist/browser/oidc-client-ts.min.js`,zt=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${Jt}/dist/browser/oidc-client-ts.min.js`,Gt="DS",Zt="DSR",Xt="DSI";const Yt=e=>(null==e?void 0:e.cookieName)||Gt;function Qt(e=""){return Dt(`${e}${Zt}`)||""}function en(e="",t){return wt.get(Yt(t))||Dt(`${e}${Gt}`)||""}function tn(e=""){return Dt(`${e}${Xt}`)||""}function nn(e="",t){qt(`${e}${Zt}`),qt(`${e}${Gt}`),qt(`${e}${Xt}`);const n=Yt(t);wt.remove(n)}const on=Vt&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",rn="vsid",sn="vrid",an="fp",ln=(e=!1)=>{const t=Dt(an);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},cn=async(e,t=on)=>{try{if(ln())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const r=i.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",s=jt({apiKey:e,endpoint:[o.toString(),yt],scriptUrlPattern:[r,At]}),a=await s,{requestId:l}=await a.get({linkedId:n}),c=((e,t)=>({[rn]:e,[sn]:t}))(n,l);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};_t(an,JSON.stringify(t))})(c)}catch(e){console.warn("Could not load fingerprint",e)}},dn=e=>{const t=ln(!0);return t&&e.body&&(e.body.fpData=t),e},un="descopeFlowNonce",pn="X-Descope-Flow-Nonce",hn="/v1/flow/start",gn="/v1/flow/next",fn=(e,t=un)=>`${t}${e}`,vn=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},mn=e=>{var t;return e.path===gn&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?vn(e.body.executionId):null},bn="dls_last_user_login_id",wn="dls_last_user_display_name",yn=e=>_t(bn,e),kn=()=>Dt(bn),In=()=>Dt(wn),Sn=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=kn(),r=In();return i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r),await e(...t)};function On(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}async function Cn(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Rn(n.publicKey.challenge),n.publicKey.user.id=Rn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=Rn(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:Tn(n.rawId),type:n.type,response:{attestationObject:Tn(n.response.attestationObject),clientDataJSON:Tn(n.response.clientDataJSON)}});var n}async function xn(e){const t=En(e);return Un(await navigator.credentials.get(t))}async function An(e,t){const n=En(e);return n.signal=t.signal,n.mediation="conditional",Un(await navigator.credentials.get(n))}async function jn(e=!1){if(!Vt)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function En(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Rn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=Rn(e.id)})),n}function Un(e){return JSON.stringify({id:e.id,rawId:Tn(e.rawId),type:e.type,response:{authenticatorData:Tn(e.response.authenticatorData),clientDataJSON:Tn(e.response.clientDataJSON),signature:Tn(e.response.signature),userHandle:e.response.userHandle?Tn(e.response.userHandle):void 0}})}function Rn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function Tn(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var $n,Ln=($n=e=>({async signUp(t,n,o){const i=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await Cn(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,r)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const i=await xn(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,i)},async signUpOrIn(t,n){var o;const i=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!i.ok)return i;if(null===(o=i.data)||void 0===o?void 0:o.create){const t=await Cn(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await xn(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,t)}},async update(t,n,o){const i=await e.webauthn.update.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await Cn(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:Cn,get:xn,isSupported:jn,conditional:An}}),(...e)=>{const t=$n(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const Pn="/fedcm/config",Wn=()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)};async function Nn(e,t){var n;try{await Mn(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function Mn(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=Wn(),s=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const l=a.data.clientId;return new Promise((e=>{var a,c;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};s.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(c=null==n?void 0:n.use_fedcm_for_prompt)||void 0===c||c,client_id:l,callback:d,nonce:r})),s.prompt((e=>{var t,n;if(i&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==i||i(n),void d()}if(o&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==o||o(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!i.credential)return null;if(null==t?void 0:t.onCodeReceived){const o=await e.oauth.verifyOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!o.ok||!o.data)throw new Error("Failed to verify OneTap client ID for provider "+i.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,o.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+i.provider);null===(o=null==t?void 0:t.onAuthenticated)||void 0===o||o.call(t,n.data)}}var _n=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await jn(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});let Dn;const qn=(e,t)=>new Promise(((n,o)=>{if(!e.length)return o(new Error("No URLs provided to loadScriptWithFallback"));const i=t();if(i)return n(i);const r=e.shift(),s=document.createElement("script");s.src=r,s.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(r),s.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},s.addEventListener("error",(()=>{qn(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)})),Fn=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await(async(e,t,n)=>{Dn||(Dn=(async()=>{try{return require("oidc-client-ts")}catch(e){return qn([Bt,zt],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await Dn;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=t,s=(null==n?void 0:n.redirectUri)||window.location.href,a=(null==n?void 0:n.scope)||"openid email roles descope.custom_claims offline_access",l=`${r}_user`;let c=e.httpClient.buildUrl(t);(null==n?void 0:n.applicationId)&&(c=`${c}/${n.applicationId}`);const d={authority:c,client_id:t,redirect_uri:s,response_type:"code",scope:a,stateStore:new i({store:window.localStorage,prefix:r}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),(null==n?void 0:n.scope)&&(d.scope=n.scope),{client:new o(d),stateUserKey:l}})(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),s=await i.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(s)))),_t(r,JSON.stringify({id_token:(a=s).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),s};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await o(),i=await n.createSigninRequest(e),{url:r}=i;return t||(window.location.href=r),{ok:!0,data:i}},finishLogin:i,finishLoginIfNeed:async(e="")=>{if(window.location.search.includes("code")&&window.location.search.includes("state"))return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),s=(e=>{const t=Dt(e);return t?JSON.parse(t):null})(r);if(!s)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const l=await i.useRefreshToken({state:{refresh_token:a,session_state:s.session_state,profile:s.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(l)))),l},logout:async(e,t=!1)=>{const{client:n,stateUserKey:i}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||tn(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:s}=r;return qt(i),t||window.location.replace(s),r}}},Kn=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var n;return n=t.customStorage,Rt=n,e(t)}),(e=>n=>{var{fpKey:o,fpLoad:i}=n,r=t(n,["fpKey","fpLoad"]);return Vt?(o&&i&&cn(o).catch((()=>null)),e(Wt(r,{beforeRequest:dn}))):e(r)}),(e=>n=>{var{autoRefresh:o}=n,i=t(n,["autoRefresh"]);if(!o||"undefined"!=typeof window&&window.descopeBridge)return e(i);const{clearAllTimers:r,setTimer:s}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let l,c;Vt&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&l&&new Date>l&&(Kt("Expiration time passed, refreshing session"),d.refresh(Qt()||c))}));const d=e(Wt(i,{afterRequest:async(e,t)=>{const{sessionJwt:n,refreshJwt:o,sessionExpiration:i}=await Nt(t);if(401===(null==t?void 0:t.status))Kt("Received 401, canceling all timers"),r();else if(n||i){if(l=((e,t)=>{if(t)return new Date(1e3*t);Kt("Could not extract expiration time from session token, trying to decode the token");try{const t=a(e);if(t.exp)return new Date(1e3*t.exp)}catch(e){return null}})(n,i),!l)return void Kt("Could not extract expiration time from session token");c=o;const e=(e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>Ht&&(Kt(`Timeout is too large (${t}ms), setting it to ${Ht}ms`),t=Ht),t})(l);if(r(),e<=2e4)return void Kt("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});Kt(`Setting refresh timer for ${t}. (${e}ms)`),s((()=>{Kt("Refreshing session due to timer"),d.refresh(Qt()||o)}),e)}}}));return re(d,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return Kt("Clearing all timers"),r(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.38.2"},t.baseHeaders)}))),(e=>t=>{const n=On(),o=On(),i=On(),r=On(),s=e(Wt(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))o.pub(null),i.pub(null),n.pub(null),r.pub(null);else{const e=await(async e=>{const t=await Nt(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)})(t);e&&i.pub(e);const{sessionJwt:s,sessionExpiration:a,claims:l}=await Nt(t);s&&o.pub(s),l&&r.pub(l),(a||s)&&n.pub(a||42)}}})),a=re(s,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const s=await e(...t);return o.pub(null),i.pub(null),n.pub(null),r.pub(null),s}));return Object.assign(a,{onSessionTokenChange:o.sub,onUserChange:i.sub,onClaimsChange:r.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(e=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=un}=n,r=t(n,["enableFlowNonce","nonceStoragePrefix"]);return o?(((e=un)=>{try{if(!Mt)return;for(let o=0;o<(void 0,void 0,null!==(n=null!==(t=null==Rt?void 0:Rt.length)&&void 0!==t?t:null===localStorage||void 0===localStorage?void 0:localStorage.length)&&void 0!==n?n:0);o++){const t=Ft(o);if(t&&t.startsWith(e)){const n=Dt(t);if(n)try{JSON.parse(n).expiry<Date.now()&&qt(t)}catch(e){qt(t)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}var t,n})(i),e(Wt(r,{afterRequest:async(e,t)=>{if(e.path!==hn&&e.path!==gn)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(pn);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=mn(e)),{nonce:n,executionId:vn(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);n&&o&&((e,t,n,o=un)=>{try{const i=fn(e,o),r=n?172800:10800,s={value:t,expiry:Date.now()+1e3*r,isStart:n};_t(i,JSON.stringify(s))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===hn,i)},beforeRequest:e=>{if(e.path===gn){const t=mn(e);if(t){const n=((e,t=un)=>{try{const n=fn(e,t),o=Dt(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(((e,t=un)=>{try{const n=fn(e,t);qt(n)}catch(e){console.error("Error removing flow nonce:",e)}})(e,t),null):i.value}catch(e){return console.error("Error getting flow nonce:",e),null}})(t,i);n&&(e.headers=e.headers||{},e.headers[pn]=n)}}return e}}))):e(r)}),(e=>n=>{var{storeLastAuthenticatedUser:o=!0,keepLastAuthenticatedUserAfterLogout:i=!1}=n,r=t(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!o)return Object.assign(e(r),{getLastUserLoginId:kn,getLastUserDisplayName:In});const s=e(Wt(r,{afterRequest:async(e,t)=>{var n;const{userInfo:o,lastAuth:i}=await(async e=>{if(!(null==e?void 0:e.ok))return{userInfo:void 0,lastAuth:void 0};const t=await(null==e?void 0:e.clone().json()),n=Pt((null==t?void 0:t.authInfo)||t||{});return{userInfo:(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0),lastAuth:t.lastAuth}})(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],s=null==o?void 0:o.name;r?(yn(r),(e=>{_t(wn,e)})(s)):(null==i?void 0:i.loginId)&&yn(i.loginId)}}));let a=re(s,["flow.start"],Sn);return a=re(a,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return e||(qt(bn),qt(wn)),o})(i)),Object.assign(a,{getLastUserLoginId:kn,getLastUserDisplayName:In})}),(e=>n=>{var{persistTokens:o,sessionTokenViaCookie:i,storagePrefix:r}=n,s=t(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!o||!Vt)return e(s);const a=e(Wt(s,{beforeRequest:(l=r,e=>Object.assign(e,{token:e.token||Qt(l)})),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?n||nn(r,i):((e={},t=!1,n="")=>{var o,i;const{sessionJwt:r,refreshJwt:s}=e;if(s&&_t(`${n}${Zt}`,s),r)if(t){const n=t.sameSite||"Strict",s=null===(o=t.secure)||void 0===o||o,a=null!==(i=t.domain)&&void 0!==i?i:e.cookieDomain;!function(e,t,n){if(t){const{cookieDomain:o,cookiePath:i,cookieSameSite:r,cookieExpiration:s,cookieSecure:a}=n,l=new Date(1e3*s),c=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(o);wt.set(e,t,{path:i,domain:c?o:void 0,expires:l,sameSite:r,secure:a})}}(Yt(t),r,Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:s,cookieDomain:a}))}else _t(`${n}${Gt}`,r);e.idToken&&_t(`${n}${Xt}`,e.idToken)})(await Nt(t),i,r)}}));var l;const c=re(a,["logout","logoutAll","oidc.logout"],((e,t)=>n=>async(...o)=>{const i=await n(...o);return nn(e,t),i})(r,i));return Object.assign(c,{getRefreshToken:()=>Qt(r),getSessionToken:()=>en(r),getIdToken:()=>tn(r)})}))((e=>{const t=mt(e),n=Fn(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(o,i)=>{var r;if(e.oidcConfig)try{return await n.refreshToken(o),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=en(),a=Qt();let l="";if(e.getExternalToken)try{l=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){Kt("Error getting external token while refreshing",e)}return t.refresh(o,{dcs:s?"t":"f",dcr:a?"t":"f"},l,i)},logout:async o=>{if(e.oidcConfig)try{return await n.logout({id_token_hint:o}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(o)},flow:_n(t),webauthn:Ln(t),fedcm:(o=t,i=e.projectId,{onetap:{requestExchangeCode(e){Nn(o,e)},requestAuthentication(e){Nn(o,e)}},async oneTap(e,t,n,i,r){await Mn(o,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:i,onDismissed:r})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:o.httpClient.buildUrl(i+Pn),clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return o.refresh(r.token)},isSupported:()=>Vt&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=o.httpClient.buildUrl(i+Pn);try{const o={identity:{context:e||"signin",providers:[{configURL:n,clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return!!r&&!!r.token}catch(e){return!1}}}),oidc:n});var o,i})),Jn="undefined"!=typeof localStorage,Vn="J151000",Hn="E103205",Bn=Jn&&localStorage.getItem("base.content.url")||"",zn="base.ui.components.url";Jn&&localStorage.getItem(zn),Jn&&localStorage.getItem(zn);const Gn="descope-login-flow",Zn="code",Xn="redirect_mode",Yn="data-exclude-field",Qn="data-exclude-next",eo="dls_last_auth",to="state_id",no="saml_idp_state_id",oo="saml_idp_username",io="descope_idp_initiated",ro="sso_app_id",so="third_party_app_id",ao="third_party_app_state_id",lo="oidc_login_hint",co="oidc_prompt",uo="oidc_resource",po="oidc_error_redirect_uri",ho="application_scopes",go="data-type",fo="redirect",vo="poll",mo="webauthnCreate",bo="webauthnGet",wo="nativeBridge",yo="loadForm",ko="submit",Io="polling",So=["descope-multi-select-combo-box","descope-text-area"],Oo=["cssVars","componentsConfig","inputs","errorText","errorType","clientScripts"];var Co;!function(e){e.backward="backward",e.forward="forward"}(Co||(Co={}));const xo=["descope-enriched-text"];function Ao(e){return new URLSearchParams(window.location.search).get(e)}function jo(e){if(window.history.replaceState&&Ao(e)){const t=new URL(window.location.href),n=new URLSearchParams(t.search);n.delete(e),t.search=n.toString(),window.history.replaceState({},"",t.toString())}}function Eo(e,t){if(!t)return;const n=+e,o=+t;return Number.isNaN(n)||Number.isNaN(o)?void 0:n>o?Co.forward:n<o?Co.backward:void 0}const Uo=e=>{let[t="",n=""]=(Ao(Gn)||"").split("_");const o=(e=>{var t;return(null===(t=/(.*)\|#\|.*/.exec(e))||void 0===t?void 0:t[1])||""})(t);return(!e||o&&o!==e)&&(t="",n=""),{executionId:t,stepId:n,executionFlowId:o}};function Ro(){jo(Gn)}const To=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),$o=(e,t)=>{const{executionId:n,stepId:o,executionFlowId:i}=Uo(e);if(i&&e!==i)return t.debug("Flow id does not match the execution flow id, skipping url params handling"),{ssoQueryParams:{}};(n||o)&&Ro();const r=Ao("t")||void 0;r&&jo("t");const s=Ao(Zn)||void 0;s&&jo(Zn);const a="popup"===Ao(Xn);a&&jo(Xn);const l=Ao("err")||void 0;l&&jo("err");const{redirectAuthCodeChallenge:c,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthInitiator:p}={redirectAuthCodeChallenge:Ao("ra-challenge"),redirectAuthCallbackUrl:Ao("ra-callback"),redirectAuthBackupCallbackUri:Ao("ra-backup-callback"),redirectAuthInitiator:Ao("ra-initiator")},h=Ao(to);h&&jo(to);const g=Ao(no);g&&jo(no);const f=Ao(oo);g&&jo(oo);const v=Ao(io);v&&jo(io);const m=Ao(ro);m&&jo(ro);const b=Ao(so);b&&jo(so);const w=Ao(ao);w&&jo(ao);const y=Ao(ho);y&&jo(ho);const k=Ao(lo);k&&jo(lo);const I=Ao(co);I&&jo(co);const S=Ao(po);S&&jo(po);const O=Ao(uo);O&&jo(uo);return{executionId:n,stepId:o,token:r,code:s,isPopup:a,exchangeError:l,redirectAuthCodeChallenge:c,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthInitiator:p,ssoQueryParams:{oidcIdpStateId:h,samlIdpStateId:g,samlIdpUsername:f,descopeIdpInitiated:"true"===v,ssoAppId:m,oidcLoginHint:k,oidcPrompt:I,oidcErrorRedirectUri:S,oidcResource:O,thirdPartyAppId:b,thirdPartyAppStateId:w,applicationScopes:y}}},Lo=e=>{let t,n;return Object.assign(((...o)=>{return t&&(r=o,(i=t).length===r.length&&i.every(((e,t)=>e===r[t])))||(t=o,n=e(...o)),n;var i,r}),{reset:()=>{t=void 0,n=void 0}})},Po=(e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}};function Wo(e,t,n){return new Promise(((o,i)=>{let r=!1;const s=setTimeout((()=>{r=!0,void 0!==n?o(n):i(new Error(`Promise timed out after ${e} ms`))}),e);t.then((e=>{r||(clearTimeout(s),o(e))})).catch((e=>{r||(clearTimeout(s),i(e))}))}))}const No=(e,{oidcIdpStateId:t,samlIdpStateId:n,samlIdpUsername:o,ssoAppId:i,oidcLoginHint:r,oidcPrompt:s,oidcErrorRedirectUri:a,oidcResource:l,thirdPartyAppId:c,thirdPartyAppStateId:d,applicationScopes:u})=>!(!e||t||n||o||i||r||s||a||l||c||d||u),Mo=e=>null==e?void 0:e.submit(),_o=(e,t)=>{const n=t.find((t=>e[t]));return n?e[n]:null},Do=(e,t=100)=>{let n;return function(...o){n||e.apply(this,o),clearTimeout(n),n=setTimeout((()=>{n=null}),t)}};function qo(e){if(e)return{locale:e.toLowerCase(),fallback:e.toLowerCase()};const t=navigator.language;return t?t.includes("-")?{locale:t.toLowerCase(),fallback:t.split("-")[0].toLowerCase()}:{locale:t.toLowerCase(),fallback:t.toLowerCase()}:{locale:"",fallback:""}}const Fo=e=>{var t,n,o;const i=(r=e.screenState,s=(e,t)=>Oo.includes(t)||t.startsWith("_"),Object.fromEntries(Object.entries(r).filter((([e,t])=>!s(t,e)))));var r,s;const{screenState:{errorText:a,errorType:l}}=e;return(a||l)&&(i.error={text:a,type:l}),e.action&&(i.action=e.action),(null===(o=null===(n=null===(t=e.screenState)||void 0===t?void 0:t.componentsConfig)||void 0===n?void 0:n.thirdPartyAppApproveScopes)||void 0===o?void 0:o.data)&&(i.inboundAppApproveScopes=e.screenState.componentsConfig.thirdPartyAppApproveScopes.data),i},Ko=e=>{const t=Object.assign({},e);return e.inboundAppApproveScopes&&(t.thirdPartyAppApproveScopes=e.inboundAppApproveScopes),t};function Jo(e,t){return`sdkScriptsResults.${t?`${e}_${t}`:e}`}const Vo=(e,t,n,o)=>{const i=void 0!==window.screenLeft?window.screenLeft:window.screen.left,r=void 0!==window.screenTop?window.screenTop:window.screen.top,s=((window.innerWidth||document.documentElement.clientWidth||window.screen.width)-n)/2+i,a=((window.innerHeight||document.documentElement.clientHeight||window.screen.height)-o)/2+r,l=function(){const e=navigator.userAgent||"",t=/\b(iPhone)\b/.test(e),n=/Safari/.test(e)&&!/CriOS|FxiOS|OPiOS|EdgiOS|Chrome|Chromium/.test(e);return t&&n}()?"about:blank":"",c=window.open(l,t,`width=${n},height=${o},top=${a},left=${s},scrollbars=yes,resizable=yes`);return c.location.href=e,c.focus(),c};var Ho,Bo,zo,Go;function Zo(e,t){const n=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(n.length!==o.length)return!1;for(let o=0;o<n.length;o+=1){const i=n[o],r=e[i],s=t[i];if(null===r||null===s){if(r!==s)return!1}else if("object"==typeof r&&"object"==typeof s){if(!Zo(r,s))return!1}else if(r!==s)return!1}return!0}class Xo{constructor(e={},{forceUpdate:t=!1}={}){Ho.set(this,void 0),Bo.set(this,{}),zo.set(this,0),Go.set(this,!0),this.update=e=>{const t="function"==typeof e?e(o(this,Ho,"f")):e,n=Object.assign(Object.assign({},o(this,Ho,"f")),t),r=o(this,Ho,"f");i(this,Ho,n,"f"),Object.freeze(o(this,Ho,"f")),setTimeout((()=>{Object.values(o(this,Bo,"f")).forEach((({cb:e,selector:t,forceUpdate:i})=>{const s=t(r),a=t(n);(o(this,Go,"f")||i||(function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(a)?!Zo(s,a):s!==a))&&e(a,s,((e,t)=>n=>e[n]!==t[n])(a,s))}))}),0)},i(this,Ho,e,"f"),i(this,Go,t,"f")}get current(){return Object.assign({},o(this,Ho,"f"))}set forceUpdate(e){i(this,Go,e,"f")}subscribe(e,t=e=>e,{forceUpdate:n=!1}={}){return i(this,zo,o(this,zo,"f")+1,"f"),o(this,Bo,"f")[o(this,zo,"f")]={cb:e,selector:t,forceUpdate:n},o(this,zo,"f").toString()}unsubscribe(e){const t=!!o(this,Bo,"f")[e];return t&&delete o(this,Bo,"f")[e],t}unsubscribeAll(){return i(this,Bo,{},"f"),!0}}Ho=new WeakMap,Bo=new WeakMap,zo=new WeakMap,Go=new WeakMap;const Yo=["*","#","/","(",")","[","]","_","<",">","`"],Qo=e=>{const t=Yo.map((t=>`${e}${t}`)).join("|");return new RegExp(`(${t})`,"g")},ei=["disabled"],ti=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${Yn}])`)).forEach((e=>{e.value=n}))}))},ni=(e,t)=>t.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),e),oi=(e,t,n)=>e.replace(/{{(.+?)}}/g,((e,o)=>n?(e=>"string"!=typeof e?e:e.replace(Qo("\\"),"\\$1"))(ni(t,o)):ni(t,o))),ii=(e,t)=>{e.querySelectorAll("descope-text,descope-link,descope-enriched-text,descope-code-snippet").forEach((e=>{const n=(o=e.localName,xo.includes(o));var o;e.textContent=oi(e.textContent,t,n);const i=e.getAttribute("href");i&&e.setAttribute("href",oi(i,t))}))},ri=(e,t,n)=>{e.querySelectorAll(`[${go}="${t}"]`).forEach((e=>{e.setAttribute("href",n)}))},si=(e,t,n)=>{var o,i;const r=null===(o=customElements.get(t))||void 0===o?void 0:o.cssVarList.url;n&&r&&(null===(i=null==e?void 0:e.style)||void 0===i||i.setProperty(r,`url(data:image/jpg;base64,${n})`))},ai=(e,n,o,i,r)=>{var s,a;ri(e,"totp-link",null===(s=null==n?void 0:n.totp)||void 0===s?void 0:s.provisionUrl),ri(e,"notp-link",null===(a=null==n?void 0:n.notp)||void 0===a?void 0:a.redirectUrl),ii(e,n),((e,n,o)=>{if(!n)return;const{componentsDynamicAttrs:i}=n,r=t(n,["componentsDynamicAttrs"]),s=Object.keys(r).reduce(((e,t)=>(e[`[name=${t}]`]=r[t],e)),{});i&&Object.keys(i).forEach((e=>{const t=i[e];if(t){const{attributes:n}=t;n&&Object.keys(n).length&&(s[e]=n)}})),Object.keys(s).forEach((t=>{e.querySelectorAll(t).forEach((e=>{const n=s[t];Object.keys(n).forEach((t=>{let i=n[t];if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){o.error(`Could not stringify value "${i}" for "${t}"`,e.message),i=""}e.setAttribute(t,i)}))}))}))})(e,o,r),((e,t)=>{e.querySelectorAll("[data-has-dynamic-attr-values]").forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=oi(e.value,t)}))}))})(e,n),((e,t)=>{Object.entries(t).forEach((([t,n])=>{e.querySelectorAll(`[name="${t}"]`).forEach((e=>{Object.entries(n).forEach((([t,n])=>{ei.includes(t)&&e.setAttribute(t,n)}))}))}))})(e,i)},li=Lo((()=>n(void 0,void 0,void 0,(function*(){var e,t;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return!1;try{const n=Promise.all([null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable(),null===(t=window.PublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable()]).then((e=>e.every((e=>!!e)))),o=(()=>{var e;const t=null===(e=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===e?void 0:e.brands,n=null==t?void 0:t.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t)));return n?n.version:0})()>=108;return yield Wo(100,n,o)}catch(e){return console.error("Conditional login check failed",e),!1}})))),ci=(e,t,n,o={})=>{var i,r,s,a;return[Math.min(Math.max(t,("all"===o.left?e.offsetWidth:null!==(i=o.left)&&void 0!==i?i:0)-e.offsetWidth),window.innerWidth-("all"===o.right?e.offsetWidth:null!==(r=o.right)&&void 0!==r?r:0)),Math.min(Math.max(n,("all"===o.top?e.offsetHeight:null!==(s=o.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===o.bottom?e.offsetHeight:null!==(a=o.bottom)&&void 0!==a?a:0))]};let di;const ui=(e,t)=>{di?di.setItem(e,t):void 0!==(null===window||void 0===window?void 0:window.localStorage)&&window.localStorage.setItem(e,t)},pi=e=>di?di.getItem(e):void 0!==(null===window||void 0===window?void 0:window.localStorage)?window.localStorage.getItem(e):null,hi="dls_ab_testing_id",gi={"lastAuth.loginId":{"not-empty":e=>{var t;return!!e.loginId||!!(null===(t=e.lastAuth)||void 0===t?void 0:t.loginId)},empty:e=>{var t;return!e.loginId&&!(null===(t=e.lastAuth)||void 0===t?void 0:t.loginId)}},idpInitiated:{"is-true":e=>!!e.code,"is-false":e=>!e.code},externalToken:{"is-true":e=>!!e.token,"is-false":e=>!e.token},abTestingKey:{"greater-than":(e,t)=>(e.abTestingKey||0)>t,"less-than":(e,t)=>(e.abTestingKey||0)<t,"greater-than-or-equal":(e,t)=>(e.abTestingKey||0)>=t,"less-than-or-equal":(e,t)=>(e.abTestingKey||0)<=t,"in-range":(e,t)=>{const[n,o]=t?t.split(",").map(Number):[void 0,void 0];return(e.abTestingKey||0)>=(null!=n?n:0)&&(e.abTestingKey||0)<=(null!=o?o:0)},"not-in-range":(e,t)=>{const[n,o]=t?t.split(",").map(Number):[void 0,void 0];return!(void 0!==n&&void 0!==o&&!Number.isNaN(n)&&!Number.isNaN(o))||((e.abTestingKey||0)<n||(e.abTestingKey||0)>o)},"devised-by":(e,t)=>{const n=Number(t);return!Number.isNaN(n)&&(e.abTestingKey||0)%n==0}}};function fi(e){const t={};try{Object.assign(t,JSON.parse(pi(eo)))}catch(e){}return(null==t?void 0:t.loginId)||e?t:{}}function vi(e,t){(null==e?void 0:e.authMethod)&&(t&&!(null==e?void 0:e.loginId)||ui(eo,JSON.stringify(e)))}function mi(...e){return t=>e.reduce(((e,t)=>t(e)),t)}const bi=e=>{const t=Symbol((e=>{const t=e.toString();let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n&=n;return n.toString(16)})(e));return n=>{if(n[t])return n;const o=e(n);return o[t]=!0,o}},wi=["error","warn","info","debug"],yi=bi((e=>{var t,n,r,s;return s=class extends e{constructor(){super(...arguments),t.add(this),n.set(this,o(this,t,"m",r).call(this,console))}set logger(e){i(this,n,o(this,t,"m",r).call(this,e||console),"f")}get logger(){return o(this,n,"f")}onLogEvent(e,t){}},n=new WeakMap,t=new WeakSet,r=function(e){return wi.reduce(((t,n)=>(t[n]=(...t)=>{var o;this.onLogEvent(n,t),null===(o=e[n])||void 0===o||o.call(e,...t)},t)),{})},s})),ki="undefined"!=typeof localStorage,Ii=ki&&localStorage.getItem("base.content.url")||"",Si=(e,t)=>!t&&`${e} cannot be empty, please make sure to set this attribute`,Oi=bi((e=>{var t,n;return n=class extends e{constructor(){super(...arguments),t.set(this,!0)}connectedCallback(){var e,n;null===(e=super.connectedCallback)||void 0===e||e.call(this),(null===(n=this.shadowRoot)||void 0===n?void 0:n.isConnected)&&o(this,t,"f")&&(i(this,t,!1,"f"),this.init())}async init(){}},t=new WeakMap,n})),Ci=bi((e=>{var t,n;const i=mi(yi,Oi)(e);return n=class extends i{constructor(){super(...arguments),t.set(this,{})}async init(){var e,n,i;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),n=this,i=e=>{var n;null===(n=o(this,t,"f")[e])||void 0===n||n.forEach((t=>{t(e,this.getAttribute(e))}))},Array.from(n.attributes).forEach((e=>i(e.name))),new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&i(e.attributeName)}))})).observe(n,{attributes:!0})}observeAttribute(e,n){o(this,t,"f")[e]||(o(this,t,"f")[e]=[]);const i=o(this,t,"f")[e].push(n);return()=>o(this,t,"f")[e].splice(i,1)}observeAttributes(e,t){const n=e.reduce(((e,n)=>(e.push(this.observeAttribute(n,t)),e)),[]);return()=>n.forEach((e=>e()))}},t=new WeakMap,n})),xi=e=>t=>{var n,i,r;const s=mi(yi,Oi,Ci)(t),a=Object.keys(e);return r=class extends s{constructor(...e){super(...e),n.add(this),this.observeAttributes(a,o(this,n,"m",i).bind(this))}async init(){var e;a.forEach((e=>o(this,n,"m",i).call(this,e,this.getAttribute(e)))),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},n=new WeakSet,i=function(t,n){const o=e[t],i="function"==typeof o?o(t,n):o;i&&this.logger.error(i)},r};xi.missingAttrValidator=Si;const Ai=bi((e=>{const t=mi(xi({"project-id":Si}))(e);return class extends t{get projectId(){return this.getAttribute("project-id")}}})),ji=bi((e=>class extends e{get baseUrl(){return this.getAttribute("base-url")||""}})),Ei="Trying the next fallback URL...",Ui=async(e,t,{logger:n}={})=>{try{return await fetch(e,t)}catch(o){return null==n||n.debug(`Network error fetching URL ${e} [${o.message}], retrying...`),fetch(e,t)}};function Ri({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:o="https://static.descope.com/pages"}){const i=new URL(o);return i.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(i.pathname,e,n,t),i.baseUrl=o,i}const Ti=bi((e=>{var t,n,r,s,a;const l=mi(yi,Ai,ji)(e);return a=class extends l{constructor(){super(...arguments),t.add(this),n.set(this,void 0),r.set(this,void 0)}async fetchStaticResource(e,n){const a=o(this,t,"m",s).call(this,e),l=Array.isArray(a)?e=>{if(e!==a.length-1){const{baseUrl:t}=a[e];i(this,r,t,"f")}}:null;try{const e=await(async(e,t,{logger:n,onSuccess:o}={})=>{const i=Array.isArray(e)?e:[e];for(let e=0;e<i.length;e++){const r=i[e],s=e===i.length-1;try{const i=await Ui(r.toString(),t,{logger:n});if(i.ok)return null==o||o(e),null==n||n.debug(`Successfully fetched URL ${r}`),i;const a=`Error fetching URL ${r} [${i.status}]`;if(s)throw new Error(a);null==n||n.debug(`${a}. ${Ei}`)}catch(e){const t=`Error fetching URL ${r} [${e.message}]`;if(s)throw new Error(t);null==n||n.debug(`${t}. ${Ei}`)}}})(a,{cache:"default"},{logger:this.logger,onSuccess:l});return{body:await e[n](),headers:Object.fromEntries(e.headers.entries())}}catch(e){this.logger.error(e.message)}}get baseStaticUrl(){return this.getAttribute("base-static-url")||""}},n=new WeakMap,r=new WeakMap,t=new WeakSet,s=function(e){const t=Ii||this.baseStaticUrl;if(t)return Ri({projectId:this.projectId,filename:e,baseUrl:t});const s=o(this,n,"f")!==this.baseUrl,a=s&&!!this.baseUrl;s&&(i(this,n,this.baseUrl,"f"),i(this,r,void 0,"f"));const l=Ri({projectId:this.projectId,filename:e,baseUrl:o(this,r,"f")});if(!a)return l;return[Ri({projectId:this.projectId,filename:e,baseUrl:this.baseUrl+"/pages"}),l]},a})),$i=bi((e=>{var t,n;const i=mi(xi({"project-id":Si}))(e);return n=class extends i{constructor(){super(...arguments),t.set(this,new Map)}onReset(e,n){if(o(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} already exists`);return o(this,t,"f").set(e,n),()=>{o(this,t,"f").delete(e)}}async reset(...e){0===e.length?await Promise.all(Array.from(o(this,t,"f").values()).map((e=>e()))):await Promise.all(e.map((e=>{var n;if(!o(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} does not exist`);return null===(n=o(this,t,"f").get(e))||void 0===n?void 0:n()})))}},t=new WeakMap,n})),Li=bi((e=>{var t,n,r,s,a;const l=mi(Ti,$i,Oi)(e);return a=class extends l{constructor(){super(...arguments),t.add(this),r.set(this,void 0),s.set(this,(async()=>{try{const{body:e,headers:t}=await this.fetchStaticResource("config.json","json");return{projectConfig:e,executionContext:{geo:t["x-geo"]}}}catch(e){this.logger.error("Cannot fetch config file","make sure that your projectId & flowId are correct")}}))}async init(){await super.init(),this.onReset("config",o(this,t,"m",n).bind(this))}get config(){return o(this,r,"f")||i(this,r,o(this,s,"f").call(this),"f"),o(this,r,"f")}},r=new WeakMap,s=new WeakMap,t=new WeakSet,n=function(){i(this,r,void 0,"f")},a})),Pi=["https://descopecdn.com","https://static.descope.com","https://cdn.jsdelivr.net"],Wi=e=>{let t=0;const n=e.toString();for(let e=0;e<n.length;e++){t=(t<<5)-t+n.charCodeAt(e),t|=0}return`${Math.abs(t).toString()}`},Ni=(e,t)=>new Promise(((n,o)=>{const i=(e=>{const t=document.createElement("script");return t.id=e,t})(e);i.onerror=e=>{i.setAttribute("status","error"),o(e)},i.onload=()=>{i.setAttribute("status","loaded"),n(i)},i.src=t.toString(),document.body.appendChild(i)})),Mi=e=>"loaded"===e.getAttribute("status")?Promise.resolve(e):(e=>"error"===e.getAttribute("status"))(e)?Promise.reject():new Promise(((t,n)=>{e.addEventListener("load",(()=>{t(e)})),e.addEventListener("error",(e=>{n(e)}))})),_i=bi((e=>{const t=mi(yi)(e);return class extends t{get baseCdnUrl(){return this.getAttribute("base-cdn-url")||""}injectNpmLib(e,t,n="",o=[]){return this.logger.debug(`Injecting npm lib: "${e}" with version: "${t}"`),(async(e,t)=>{for(const o of e){const{id:e,url:i}=o,r=(n=e,document.querySelector(`script#${n}`));if(r)try{return await Mi(r),o}catch(e){t(o,!0)}else try{return await Ni(e,i),o}catch(e){t(o,!1)}}var n;throw new Error("All scripts failed to load")})(((e,t,n,o="")=>e.reduce(((e,i)=>{const r=i;if(!r)return e;let s;try{s=new URL(r)}catch(e){throw new Error(`Invalid URL: ${r}`)}return"/"!==s.pathname||(s.pathname=`/npm/${t}@${n}/${o}`),[...e,{url:s,id:`npmlib-${t.replaceAll("@","").replaceAll("/","_")}-${Wi(s)}`}]}),[]))([...o,this.baseCdnUrl,...Pi],e,t,n),((e,t)=>{t?this.logger.error(`Existing script cannot be loaded: "${e.url}"`):this.logger.error(`Cannot load script from URL, Make sure this URL is valid and return the correct script: "${e.url}"`)}))}}})),Di="base.ui.components.url",qi=ki&&localStorage.getItem(Di),Fi=bi((e=>{var t,n,r,s,a,l;const c=mi(yi,Li,_i)(e);return l=class extends c{constructor(){super(...arguments),t.add(this),r.set(this,void 0)}get descopeUi(){return o(this,r,"f")||i(this,r,o(this,t,"m",a).call(this),"f"),o(this,r,"f")}async loadDescopeUiComponents(e){const n=Array.isArray(e)?e:(e=>[...Array.from(e.content.querySelectorAll("*")).reduce(((e,t)=>t.localName.startsWith("descope-")?e.add(t.localName):e),new Set)])(e);return Promise.all(n.map((e=>o(this,t,"m",s).call(this,e))))}},r=new WeakMap,t=new WeakSet,n=async function(){var e;const t=await this.config,n=null===(e=null==t?void 0:t.projectConfig)||void 0===e?void 0:e.componentsVersion;return n?this.logger.debug(`Got component version "${n}"`):this.logger.error("Could not get components version"),n},s=async function(e){if(!!customElements.get(e))return void this.logger.debug(`Loading component "${e}" is skipped as it is already defined`);const t=await this.descopeUi;if(t[e])try{return await t[e]()}catch(t){if("NotSupportedError"!==t.name)throw t;console.debug(`Encountered an error while attempting to define the "${e}" component, it is likely that this component is already defined`)}else this.logger.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)},a=async function(){if(globalThis.DescopeUI)return globalThis.DescopeUI;try{return await this.injectNpmLib("@descope/web-components-ui",await o(this,t,"m",n).call(this),"dist/umd/index.js",[qi]),this.logger.debug("DescopeUI was loaded"),globalThis.DescopeUI}catch(e){throw this.logger.error(e),new Error("DescopeUI was not loaded")}},l})),Ki=bi((e=>{var t,n,i;const r=mi(Oi,Ci)(e);return i=class extends r{constructor(){super(...arguments),t.add(this)}get nonce(){return this.getAttribute("nonce")||""}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),this.observeAttribute("nonce",o(this,t,"m",n).bind(this)),o(this,t,"m",n).call(this)}},t=new WeakSet,n=function(){this.nonce&&(window.DESCOPE_NONCE=this.nonce)},i}));class Ji{constructor(e,t,{prepend:n=!1}={}){this.styleEle=document.createElement("style"),this.styleEle.setAttribute("nonce",t),this.ref=e,this.ref&&(n?this.ref.prepend(this.styleEle):this.ref.append(this.styleEle))}replaceSync(e){this.styleEle.textContent=e}get cssRules(){var e;return null===(e=this.styleEle.sheet)||void 0===e?void 0:e.cssRules}}const Vi=bi((e=>{const t=mi(Ki)(e);return class extends t{injectStyle(e,{prepend:t=!1}={}){let n;try{n=new CSSStyleSheet}catch(e){n=new Ji(this.shadowRoot,this.nonce,{prepend:t})}if(e&&n.replaceSync(e),n instanceof CSSStyleSheet){const e=this.shadowRoot;if(e&&"adoptedStyleSheets"in e){const o=[...e.adoptedStyleSheets||[]];o[t?"unshift":"push"](n),e.adoptedStyleSheets=o}}return n}}})),Hi="content-root",Bi="root",zi=bi((e=>{const t=mi(Vi)(e);return class extends t{constructor(...e){var t,n;super(...e),this.attachShadow({mode:"open"}).innerHTML=`\n <div id="${Bi}">\n <div id="${Hi}"></div>\n </div>\n `,this.injectStyle(`\n #${Bi}, #${Hi} {\n height: 100%;\n }\n #${Bi} {\n position: relative;\n height: fit-content;\n }\n `),this.contentRootElement=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById(Hi),this.rootElement=null===(n=this.shadowRoot)||void 0===n?void 0:n.getElementById(Bi)}}})),Gi=(e,t)=>!!t&&"light"!==t&&"dark"!==t&&'Supported theme values are "light", "dark", or leave empty for using the OS theme',Zi=bi((e=>{var t,n,r,s,a,l,c,d,u,p,h,g,f,v;const m=mi(xi({theme:Gi}),Ti,Oi,Fi,Li,zi,Ci,Vi)(e);return v=class extends m{constructor(){super(...arguments),t.add(this),n.set(this,void 0),r.set(this,void 0),h.set(this,(()=>{o(this,t,"m",g).call(this),o(this,f,"f").call(this,"os"===this.getAttribute("theme"))})),f.set(this,(e=>{var n,i,r;const s=e?"addEventListener":"removeEventListener";null===(r=null===(i=null===(n=window.matchMedia)||void 0===n?void 0:n.call(window,"(prefers-color-scheme: dark)"))||void 0===i?void 0:i[s])||void 0===r||r.call(i,"change",(()=>o(this,t,"m",g).call(this)))}))}get theme(){var e,t;const n=this.getAttribute("theme");if("os"===n){return window.matchMedia&&(null===(t=null===(e=window.matchMedia)||void 0===e?void 0:e.call(window,"(prefers-color-scheme: dark)"))||void 0===t?void 0:t.matches)?"dark":"light"}return n||"light"}get styleId(){return this.getAttribute("style-id")||"theme"}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),o(this,h,"f").call(this),await Promise.all([o(this,t,"m",l).call(this),o(this,t,"m",c).call(this)]),this.observeAttributes(["theme"],o(this,h,"f")),this.observeAttributes(["style-id"],(()=>{i(this,r,null,"f"),o(this,t,"m",u).call(this),o(this,t,"m",l).call(this),o(this,t,"m",c).call(this)}))}},n=new WeakMap,r=new WeakMap,h=new WeakMap,f=new WeakMap,t=new WeakSet,s=async function(){try{const{body:e}=await this.fetchStaticResource(`${this.styleId}.json`,"json");return e}catch(e){this.logger.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}},a=function(){return o(this,r,"f")||(i(this,r,o(this,t,"m",s).call(this),"f"),o(this,r,"f").then((e=>this.logger.debug("Fetched theme",e)))),o(this,r,"f")},l=async function(){var e,r;const s=await o(this,t,"a",a);s&&(o(this,n,"f")||i(this,n,this.injectStyle(""),"f"),o(this,n,"f").replaceSync(((null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.globals)||"")+((null===(r=null==s?void 0:s.dark)||void 0===r?void 0:r.globals)||"")))},c=async function(){var e,n;const i=await o(this,t,"a",a);if(!i)return;const r=await this.descopeUi;(null==r?void 0:r.componentsThemeManager)&&(r.componentsThemeManager.themes={light:null===(e=null==i?void 0:i.light)||void 0===e?void 0:e.components,dark:null===(n=null==i?void 0:i.dark)||void 0===n?void 0:n.components})},d=async function(){var e,t;const{projectConfig:n}=await this.config||{},o=null===(e=null==n?void 0:n.styles)||void 0===e?void 0:e[this.styleId],i=null==n?void 0:n.cssTemplate,r=o||i;return null===(t=null==r?void 0:r[this.theme])||void 0===t?void 0:t.fonts},u=async function(){const e=await o(this,t,"m",d).call(this);e?Object.values(e).forEach((e=>{e.url&&(this.logger.debug(`Loading font from URL "${e.url}"`),(e=>{const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url))})):this.logger.debug("No fonts to load")},p=async function(){this.rootElement.setAttribute("data-theme",this.theme);const e=await this.descopeUi;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)},g=function(){o(this,t,"m",u).call(this),o(this,t,"m",p).call(this)},v})),Xi=(e,t="")=>Object.keys(e).reduce(((n,o)=>{var i;if(Array.isArray(e[o]))return Object.assign(Object.assign({},n),{[o]:{value:e[o].map((e=>"object"==typeof e&&null!==e?Xi(e):e))}});if("object"==typeof e[o]&&null!==e[o]&&!(null===(i=e[o])||void 0===i?void 0:i.value))return Object.assign(Object.assign({},n),Xi(e[o],`${t+o}.`));const r="object"==typeof e[o]?e[o]:{value:e[o]},s=Object.assign(Object.assign({},n),{[t+o]:r,[`form.${t}${o}`]:r});return"displayName"===o?Object.assign(Object.assign({},s),{[`${t}fullName`]:r,[`form.${t}fullName`]:r}):s}),[]),Yi=bi((e=>{var t,n,i,r;return r=class extends e{constructor(){super(...arguments),t.add(this)}connectedCallback(){var e;o(this,t,"m",n).call(this)&&o(this,t,"m",i).call(this),null===(e=super.connectedCallback)||void 0===e||e.call(this)}},t=new WeakSet,n=function(){return!this.shadowRoot.host.closest("form")&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},i=function(){const e=this.shadowRoot.host,t=document.createElement("form");t.style.width="100%",t.style.height="100%",e.parentElement.appendChild(t),t.appendChild(e)},r}));var Qi,er,tr,nr,or,ir,rr,sr,ar,lr,cr,dr,ur,pr,hr,gr,fr,vr,mr,br,wr,yr,kr;const Ir=mi(Zi,Ti,Yi,Vi)(HTMLElement);class Sr extends Ir{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(e){super(),Qi.add(this),tr.set(this,!1),nr.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),o(this,Qi,"m",yr).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)},debug:(e,t="")=>{this.logger.debug(e,t)}},or.set(this,new Xo),ir.set(this,new Xo),rr.set(this,{}),this.getComponentsContext=()=>o(this,rr,"f"),this.nextRequestStatus=new Xo({isLoading:!1}),sr.set(this,void 0),ar.set(this,{popstate:o(this,Qi,"m",pr).bind(this),componentsContext:o(this,Qi,"m",mr).bind(this)}),lr.set(this,void 0),this.getConfig=()=>n(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,lr,e,"f"),o(this,Qi,"m",dr).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(e){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var e;const t=null!==(e=this.getAttribute("auto-focus"))&&void 0!==e?e:"true";return"skipFirstScreen"===t?t:"true"===t}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var e;return"true"===(null!==(e=this.getAttribute("store-last-authenticated-user"))&&void 0!==e?e:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return(e=>{try{return Xi(JSON.parse(e))}catch(e){return{}}})(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return e=this.formConfig,t="value",Object.fromEntries(Object.entries(e).map((([e,n])=>[e,n[t]])));var e,t}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const e=JSON.parse(this.getAttribute("outbound-app-scopes"));return e||null}catch(e){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return o(this,nr,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,nr,e,"f"),(e=>{di=e})(e)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"executionContext"in e?e.executionContext:void 0}))}getProjectConfig(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"projectConfig"in e?e.projectConfig:void 0}))}getFlowConfig(){return n(this,void 0,void 0,(function*(){var e,t;const n=yield this.getProjectConfig(),o=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=o.version)&&void 0!==t||(o.version=0),o}))}getTargetLocales(){return n(this,void 0,void 0,(function*(){const e=yield this.getFlowConfig();return((null==e?void 0:e.targetLocales)||[]).map((e=>e.toLowerCase()))}))}getComponentsVersion(){return n(this,void 0,void 0,(function*(){var e;const t=yield this.getConfig(),n="projectConfig"in t?null===(e=t.projectConfig)||void 0===e?void 0:e.componentsVersion:{};return n||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t;if(this.flowStatus="loading",["ready","error","success"].forEach((e=>this.addEventListener(e,(()=>{this.flowStatus=e})))),yield null===(t=e.init)||void 0===t?void 0:t.call(this),o(this,ir,"f").subscribe(o(this,Qi,"m",wr).bind(this)),o(this,ir,"f").update({isDebug:this.debug}),o(this,Qi,"m",ur).call(this),yield o(this,Qi,"m",fr).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const n=yield this.getConfig();if("isMissingConfig"in n&&n.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");o(this,Qi,"m",kr).call(this);const{executionId:r,stepId:s,token:a,code:l,isPopup:c,exchangeError:d,redirectAuthCallbackUrl:u,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:h,redirectAuthInitiator:g,ssoQueryParams:f}=$o(this.flowId,this.loggerWrapper);window.addEventListener("popstate",o(this,ar,"f").popstate),window.addEventListener("components-context",o(this,ar,"f").componentsContext),o(this,or,"f").subscribe(o(this,Qi,"m",gr).bind(this)),o(this,or,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:s,executionId:r,token:a,code:l,isPopup:c,exchangeError:d,redirectAuthCallbackUrl:u,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:h,redirectAuthInitiator:g},f)),i(this,tr,!0,"f")}))}disconnectedCallback(){o(this,or,"f").unsubscribeAll(),o(this,ir,"f").unsubscribeAll(),o(this,Qi,"m",br).call(this),window.removeEventListener("popstate",o(this,ar,"f").popstate),window.removeEventListener("components-context",o(this,ar,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&o(this,tr,"f")&&t!==n&&er.observedAttributes.includes(e)){o(this,Qi,"m",ur).call(this);const i=null===t;o(this,or,"f").update((({stepId:t,executionId:o})=>{let r=t,s=o;return i||(s=null,r=null,Ro()),{[To(e)]:n,stepId:r,executionId:s}})),o(this,ir,"f").update({isDebug:this.debug})}}}var Or,Cr,xr,Ar,jr,Er,Ur,Rr,Tr,$r,Lr,Pr,Wr,Nr,Mr,_r,Dr,qr,Fr,Kr,Jr,Vr,Hr,Br,zr,Gr,Zr,Xr,Yr,Qr,es,ts,ns,os,is,rs,ss,as,ls,cs,ds,us,ps,hs,gs,fs,vs,ms;er=Sr,tr=new WeakMap,nr=new WeakMap,or=new WeakMap,ir=new WeakMap,rr=new WeakMap,sr=new WeakMap,ar=new WeakMap,lr=new WeakMap,Qi=new WeakSet,cr=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},dr=function(){o(this,Qi,"m",cr).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},ur=function(){const e=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];er.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[To(t)])throw Error(`${t} cannot be empty`)}))},pr=function(){const{stepId:e,executionId:t}=Uo(this.flowId);o(this,or,"f").update({stepId:e,executionId:t})},hr=function(e,t){Kn&&"function"==typeof Kn||this.logger.error("SDK was not loaded properly",Kn,JSON.stringify(Kn));const i=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},er.sdkConfigOverrides),{projectId:e,baseUrl:t});o(this,nr,"f")&&(i.customStorage=o(this,nr,"f")),this.sdk=Kn(i),["start","next"].forEach((e=>{const t=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>n(this,void 0,void 0,(function*(){try{return yield t(...e)}catch(e){return{error:{errorCode:Vn,errorDescription:e.toString()}}}}))}))},gr=function(e,t,i){return n(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:n}=e;if(i("projectId")||i("baseUrl")){if(!t)return;o(this,Qi,"m",hr).call(this,t,n)}o(this,lr,"f").call(this,e)}))},fr=function(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield o(this,Qi,"m",vr).call(this))}))},vr=function(){return n(this,void 0,void 0,(function*(){const e=function({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:o}){const i=new URL(Bn||o||"https://static.descope.com/pages");return i.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(i.pathname,e,n,t),i.toString()}({projectId:this.projectId,filename:"config.json",assetsFolder:"v2-alpha",baseUrl:this.baseStaticUrl});try{return yield function(e,t){return n(this,void 0,void 0,(function*(){const n=yield fetch(e,{cache:"default"});if(!n.ok)throw Error(`Error fetching URL ${e} [${n.status}]`);return{body:yield n[t](),headers:Object.fromEntries(n.headers.entries())}}))}(e,"json"),!0}catch(e){return!1}}))},mr=function(e){i(this,rr,Object.assign(Object.assign({},o(this,rr,"f")),e.detail),"f")},br=function(){var e;null===(e=o(this,sr,"f"))||void 0===e||e.remove(),i(this,sr,null,"f")},wr=function(e){return n(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,sr,document.createElement("descope-debugger"),"f"),Object.assign(o(this,sr,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Is})),document.body.appendChild(o(this,sr,"f"))):o(this,Qi,"m",br).call(this)}))},yr=function(e,t){var n;e&&this.debug&&(null===(n=o(this,sr,"f"))||void 0===n||n.updateData({title:e,description:t}))},kr=function(){this.rootElement.onkeydown=e=>{var t,n,o;const i=!!(null===(t=this.shadowRoot.activeElement)||void 0===t?void 0:t.getAttribute("href")),r=So.includes(null!==(o=null===(n=this.shadowRoot.activeElement)||void 0===n?void 0:n.localName)&&void 0!==o?o:"");if("Enter"!==e.key||i||r)return;e.preventDefault();const s=this.rootElement.querySelectorAll("descope-button");if(1===s.length&&"false"!==s[0].getAttribute("auto-submit"))return void s[0].click();const a=Array.from(s).filter((e=>"true"===e.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const l=Array.from(s).filter((e=>"button"===e.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const e=Array.from(s).filter((e=>"sso"===e.getAttribute("data-type")));1===e.length&&"false"!==e[0].getAttribute("auto-submit")&&e[0].click()}}},Sr.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.49.0"}};class bs extends Sr{static set sdkConfigOverrides(e){Sr.sdkConfigOverrides=e}static get sdkConfigOverrides(){return Sr.sdkConfigOverrides}constructor(){const e=new Xo({deferredRedirect:!1});super(e.update.bind(e)),Or.add(this),this.stepState=new Xo({}),Cr.set(this,void 0),xr.set(this,null),Ar.set(this,null),jr.set(this,{visibilitychange:o(this,Or,"m",Er).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},Nr.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},_r.set(this,(e=>{const t=()=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e),e&&(this.contentRootElement.innerHTML="")};e&&this.contentRootElement.hasChildNodes()?o(this,Or,"m",Dr).call(this,t):t()})),qr.set(this,((e,t,r,s,a=!1)=>{const l=[Hn,"E103202"];if(this.flowState.current.action===vo){this.logger.debug("polling - Scheduling polling request");const c=Date.now(),d=a?500:2e3;i(this,Cr,setTimeout((()=>n(this,void 0,void 0,(function*(){var n,i;this.logger.debug("polling - Calling next");const u=this.sdk.flow.next(e,t,Io,r,s,{}),p=document.hidden&&!a&&Date.now()-c>d+500;let h;p&&this.logger.debug("polling - The polling seems to be throttled");try{const e=p?1e3:6e3;h=yield Wo(e,u)}catch(n){return this.logger.warn(`polling - The ${p?"throttled fetch":"fetch"} call timed out or was aborted`),void o(this,qr,"f").call(this,e,t,r,s,p)}if((null===(n=null==h?void 0:h.error)||void 0===n?void 0:n.errorCode)===Vn)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void o(this,qr,"f").call(this,e,t,r,s);this.logger.debug("polling - Got a response"),(null==h?void 0:h.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(h.error,null,4)),(null===(i=null==h?void 0:h.error)||void 0===i?void 0:i.errorCode)&&l.includes(h.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):o(this,qr,"f").call(this,e,t,r,s),o(this,Kr,"f").call(this,h)}))),d),"f")}})),Fr.set(this,(()=>{clearTimeout(o(this,Cr,"f")),i(this,Cr,null,"f")})),Kr.set(this,(e=>{var t,n,r,s,a,l,c,d,u,p,h,g,f;if(!(null==e?void 0:e.ok)){const i=null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url,c=`${null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status} - ${null===(r=null==e?void 0:e.response)||void 0===r?void 0:r.statusText}`;o(this,Or,"m",rs).call(this,"error",(null==e?void 0:e.error)||{errorCode:"J151001",errorDescription:c,errorMessage:i}),this.loggerWrapper.error((null===(s=null==e?void 0:e.error)||void 0===s?void 0:s.errorDescription)||i,(null===(a=null==e?void 0:e.error)||void 0===a?void 0:a.errorMessage)||c);const d=null===(l=null==e?void 0:e.error)||void 0===l?void 0:l.errorCode;return void("E102004"!==d&&d!==Hn||!this.isRestartOnError||o(this,Or,"m",Wr).call(this))}null===(d=null===(c=e.data)||void 0===c?void 0:c.runnerLogs)||void 0===d||d.forEach((e=>{const{level:t,title:n,log:o}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](n,o):this.loggerWrapper.info(n,o)}));const v=null===(h=null===(p=null===(u=e.data)||void 0===u?void 0:u.screen)||void 0===p?void 0:p.state)||void 0===h?void 0:h.errorText;(null===(g=e.data)||void 0===g?void 0:g.error)?this.loggerWrapper.error(`[${e.data.error.code}]: ${e.data.error.description}`,`${v?`${v} - `:""}${e.data.error.message}`):v&&this.loggerWrapper.error(v);const{status:m,authInfo:b,lastAuth:w,action:y,openInNewTabUrl:k}=e.data;if(y!==vo&&o(this,Fr,"f").call(this),"completed"===m){this.storeLastAuthenticatedUser&&vi(w);const t=Object.assign({},b);return e.data.output&&Object.keys(e.data.output).length>0&&(t.flowOutput=e.data.output),void o(this,Or,"m",rs).call(this,"success",t)}this.storeLastAuthenticatedUser&&vi(w,!0),k&&window.open(k,"_blank");const{executionId:I,stepId:S,stepName:O,screen:C,redirect:x,webauthn:A,error:j,samlIdpResponse:E,nativeResponse:U}=e.data,R=Date.now();y!==vo?(this.loggerWrapper.info(`Step "${O||`#${S}`}" is ${m}`,"",{screen:C,status:m,stepId:S,stepName:O,action:y,error:j}),(null===(f=C.state)||void 0===f?void 0:f.clientScripts)&&i(this,Ar,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:S,stepName:O,executionId:I,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==A?void 0:A.transactionId,webauthnOptions:null==A?void 0:A.options,samlIdpResponseUrl:null==E?void 0:E.url,samlIdpResponseSamlResponse:null==E?void 0:E.samlResponse,samlIdpResponseRelayState:null==E?void 0:E.relayState,nativeResponseType:null==U?void 0:U.type,nativePayload:null==U?void 0:U.payload,reqTimestamp:R})):this.flowState.update({action:y,reqTimestamp:R})})),Jr.set(this,Lo((()=>n(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Zr.set(this,null),ts.set(this,Do(((e,t)=>n(this,void 0,void 0,(function*(){var n,i;if("true"===e.getAttribute("formnovalidate")||o(this,Or,"m",zr).call(this)){const r=null==e?void 0:e.getAttribute("id");o(this,Or,"m",Xr).call(this,e);const s=yield o(this,Or,"m",Gr).call(this),a=(i=e,Array.from((null==i?void 0:i.attributes)||[]).reduce(((e,t)=>{var n;const o=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return o?Object.assign(e,{[o]:t.value}):e}),{}));this.nextRequestStatus.update({isLoading:!0});const l=Object.assign(Object.assign(Object.assign({},a),s),{origin:(null===(n=this.nativeOptions)||void 0===n?void 0:n.origin)||window.location.origin});yield t(r,l),this.nextRequestStatus.update({isLoading:!1}),o(this,Or,"m",Yr).call(this,s)}}))))),this.flowState=e}nativeResume(e,t){var n,i,r,s,a;const l=JSON.parse(t);if("oauthWeb"===e||"sso"===e){let{exchangeCode:e}=l;if(!e){e=null===(n=new URL(l.url).searchParams)||void 0===n?void 0:n.get(Zn)}null===(r=(i=this.nativeCallbacks).complete)||void 0===r||r.call(i,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(l.url),t=e.searchParams.get("t"),n=e.searchParams.get(Gn).split("_").pop();o(this,Fr,"f").call(this),this.flowState.update({token:t,stepId:n,action:void 0})}else if("beforeScreen"===e){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=l;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===e){const{interactionId:e,form:t}=l,{screenNext:n}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==n||n(e,t)}else null===(a=(s=this.nativeCallbacks).complete)||void 0===a||a.call(s,l)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>n=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[Jo(e.id,e.resultKey)]:n},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const o=Promise.all(null==e?void 0:e.map((e=>n(this,void 0,void 0,(function*(){var n,o;const i=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(i){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=i;return null===(n=null==t?void 0:t.start)||void 0===n||n.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((n,o)=>{try{const o=r(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,n),this.loggerWrapper);if(o){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=o,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=o.stop)||void 0===t||t.call(o)}))}}catch(e){o(e)}}))}))))),i=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),5e3)}));return Promise.race([o,i])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t,n;this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),o(this,Or,"m",Lr).call(this),window.addEventListener("visibilitychange",o(this,jr,"f").visibilitychange)),yield null===(n=e.init)||void 0===n?void 0:n.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),o(this,Fr,"f").call(this),null===(e=o(this,xr,"f"))||void 0===e||e.abort(),i(this,xr,null,"f"),window.removeEventListener("visibilitychange",o(this,jr,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return n(this,void 0,void 0,(function*(){let n;const o=qo(e),i=yield this.getTargetLocales();return i.includes(o.locale)?n=`${t}-${o.locale}.html`:i.includes(o.fallback)&&(n=`${t}-${o.fallback}.html`),n}))}getPageContent(e,t){return n(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(n){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,n)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(e,r,s){return n(this,void 0,void 0,(function*(){var a,l;const{projectId:c,flowId:d,tenant:u,stepId:p,executionId:h,action:g,screenId:f,screenState:v,redirectTo:m,redirectIsPopup:b,redirectUrl:w,token:y,code:k,isPopup:I,exchangeError:S,webauthnTransactionId:O,webauthnOptions:C,redirectAuthCodeChallenge:x,redirectAuthCallbackUrl:A,redirectAuthBackupCallbackUri:j,redirectAuthInitiator:E,locale:U,samlIdpResponseUrl:R,samlIdpResponseSamlResponse:T,samlIdpResponseRelayState:$,nativeResponseType:L,nativePayload:P,reqTimestamp:W}=e,N=t(e,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let M,_,D;const q=(()=>{const e=pi(hi);if(!e){const e=Math.floor(100*Math.random()+1);return ui(hi,e.toString()),e}return Number(e)})(),{outboundAppId:F}=this,{outboundAppScopes:K}=this,J=this.sdk.getLastUserLoginId(),V=yield this.getFlowConfig(),H=yield this.getProjectConfig(),B=Object.entries(H.flows||{}).reduce(((e,[t,n])=>(e[t]=n.version,e)),{}),z=A&&x?{callbackUrl:A,codeChallenge:x,backupCallbackUri:j}:void 0,G=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let Z={};if(!h){const e=[...V.clientScripts||[],...V.sdkScripts||[]];if(V.conditions){let t=[];({startScreenId:M,conditionInteractionId:D,startScreenName:_,clientScripts:t,componentsConfig:Z}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n,predicate:o})=>{var i;if("ELSE"===t)return!0;const r=null===(i=gi[t])||void 0===i?void 0:i[n];return!!(null==r?void 0:r(e,o))}));return n?{startScreenId:n.met.screenId,startScreenName:n.met.screenName,conditionInteractionId:n.met.interactionId,clientScripts:n.met.clientScripts,componentsConfig:n.met.componentsConfig}:{}})({loginId:J,code:k,token:y,abTestingKey:q,lastAuth:fi(J)},V.conditions)),e.push(...t||[])}else V.condition?({startScreenId:M,conditionInteractionId:D}=((e,t)=>{var n;const o=null===(n=gi[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const i=o(t,e.predicate)?e.met:e.unmet;return{startScreenId:null==i?void 0:i.screenId,startScreenName:null==i?void 0:i.screenName,conditionInteractionId:null==i?void 0:i.interactionId}})(V.condition,{loginId:J,code:k,token:y,abTestingKey:q,lastAuth:fi(J)})):(_=V.startScreenName,M=V.startScreenId);if(i(this,Ar,this.loadSdkScripts(e),"f"),V.fingerprintEnabled&&V.fingerprintKey?yield cn(V.fingerprintKey,this.baseUrl):qt(an),!No(M,N)){const e=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:z},N),{client:this.client}),w&&{redirectUrl:w}),{lastAuth:fi(J),abTestingKey:q,locale:qo(U).locale,nativeOptions:G,outboundAppId:F,outboundAppScopes:K}),D,"",H.componentsVersion,B,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),k?{exchangeCode:k,idpInitiated:!0}:{}),N.descopeIdpInitiated&&{idpInitiated:!0}),y?{token:y}:{}),N.oidcLoginHint?{externalId:N.oidcLoginHint}:{}));return o(this,Kr,"f").call(this,e),void("completed"!==(null===(a=null==e?void 0:e.data)||void 0===a?void 0:a.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:I,code:k,exchangeError:S,isCodeChanged:s("code"),isExchangeErrorChanged:s("exchangeError")})),I&&(s("code")&&k||s("exchangeError")&&S))return void o(this,Or,"m",ss).call(this,h,k,S);if(h&&(s("token")&&y||s("code")&&k||s("exchangeError")&&S)){const e=yield this.sdk.flow.next(h,p,ko,V.version,H.componentsVersion,{token:y,exchangeCode:k,exchangeError:S});return o(this,Kr,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===yo&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>s(e)))){if(!R||!T)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,o)=>{const i=document.createElement("form");i.method="POST",i.action=e,i.innerHTML=`\n <input type="hidden" role="saml-response" name="SAMLResponse" value="${t}" />\n <input type="hidden" role="saml-relay-state" name="RelayState" value="${n}" />\n <input style="display: none;" id="SAMLSubmitButton" type="submit" value="Continue" />\n `,document.body.appendChild(i),o(i)})(R,T,$||"",Mo)}if(g===fo&&(s("redirectTo")||s("deferredRedirect"))){if(!m)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===m)return;if("android"===E&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${b}`),b){this.loggerWrapper.debug("Opening redirect in popup");const e=Vo(m,"?",598,700),t=this.shouldUsePopupPostMessage();t&&(e.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(t?"postMessage":"BroadcastChannel"));const n=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const n=t?this.popupOrigin:window.location.origin;if(e.origin!==n)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${n}"`);const{action:o,data:i}=e.data||{};"code"===o&&this.flowState.update({code:i.code,exchangeError:i.exchangeError})};let i;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{e.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),o(this,Or,"m",rs).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==i||i())}),1e3);if(t)window.addEventListener("message",n),i=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",n)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(h);e.onmessage=n,i=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(m),this.flowState.update({redirectTo:"no-op"}),o(this,Or,"m",rs).call(this,"popupclosed",{});return}if(g===mo||g===bo){if(!O||!C)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(l=o(this,xr,"f"))||void 0===l||l.abort(),i(this,xr,null,"f");try{e=g===mo?yield this.sdk.webauthn.helpers.create(C):yield this.sdk.webauthn.helpers.get(C)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const n=yield this.sdk.flow.next(h,p,ko,V.version,H.componentsVersion,{transactionId:O,response:e,failure:t});o(this,Kr,"f").call(this,n)}if(g===wo)return this.nativeCallbacks.complete=e=>n(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(h,p,ko,V.version,H.componentsVersion,e);o(this,Kr,"f").call(this,t)})),void o(this,Or,"m",Tr).call(this,L,P);if(s("action")&&o(this,qr,"f").call(this,h,p,V.version,H.componentsVersion),!f&&!M)return void this.loggerWrapper.warn("No screen was found to show");const X=M||f,Y=yield this.getHtmlFilenameWithLocale(U,X),{oidcLoginHint:Q,oidcPrompt:ee,oidcErrorRedirectUri:te,oidcResource:ne,samlIdpUsername:oe}=N,ie={direction:Eo(p,r.stepId),screenState:Object.assign(Object.assign({},v),{form:Object.assign(Object.assign({},this.formConfigValues),null==v?void 0:v.form),lastAuth:{loginId:J,name:this.sdk.getLastUserDisplayName()||J},componentsConfig:Object.assign(Object.assign(Object.assign({},V.componentsConfig),Z),null==v?void 0:v.componentsConfig)}),htmlFilename:`${X}.html`,htmlLocaleFilename:Y,screenId:X,stepName:e.stepName||_,samlIdpUsername:oe,oidcLoginHint:Q,oidcPrompt:ee,oidcErrorRedirectUri:te,oidcResource:ne,action:g},re=fi(J);No(M,N)?ie.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=(null==V?void 0:V.clientScripts)||[];yield o(this,Or,"m",ns).call(this,n);const i=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:z},N),{lastAuth:re,preview:this.preview,abTestingKey:q,client:this.client}),w&&{redirectUrl:w}),{locale:qo(U).locale,nativeOptions:G,outboundAppId:F,outboundAppScopes:K}),D,e,H.componentsVersion,B,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),Ko(t)),k&&{exchangeCode:k,idpInitiated:!0}),N.descopeIdpInitiated&&{idpInitiated:!0}),y&&{token:y}));return o(this,Kr,"f").call(this,i),i})):(s("projectId")||s("baseUrl")||s("executionId")||s("stepId"))&&(ie.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=(null==v?void 0:v.clientScripts)||[];yield o(this,Or,"m",ns).call(this,n);const i=yield this.sdk.flow.next(h,p,e,V.version,H.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),Ko(t)));return o(this,Kr,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",ie.screenId),yield o(this,Or,"m",Mr).call(this,ie),this.stepState.update(ie)}))}onStepChange(e,t){return n(this,void 0,void 0,(function*(){var i,r;const{htmlFilename:s,htmlLocaleFilename:a,direction:l,next:c,screenState:d}=e;this.loggerWrapper.debug("Rendering a flow screen");const u=document.createElement("template");u.innerHTML=yield this.getPageContent(s,a);const p=u.content.cloneNode(!0),h=this.loadDescopeUiComponents(u);this.sdk.webauthn.helpers.isSupported()?yield o(this,Or,"m",Hr).call(this,p,c):p.querySelectorAll(`descope-button[${go}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(i=d.form)||void 0===i?void 0:i.loginId)||(null===(r=d.form)||void 0===r?void 0:r.email)||(d.form||(d.form={}),d.form.loginId=e.samlIdpUsername,d.form.email=e.samlIdpUsername),ai(p,d,d.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:g}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(p,g);const f=()=>n(this,void 0,void 0,(function*(){var n,i;yield h;const r=this.contentRootElement;var s,a;s=r,a=null===(n=null==d?void 0:d.totp)||void 0===n?void 0:n.image,si(s,"descope-totp-image",a),((e,t)=>{si(e,"descope-notp-image",t)})(r,null===(i=null==d?void 0:d.notp)||void 0===i?void 0:i.image),((e,t,n,o)=>{n&&Object.keys(n).forEach((i=>{if(!t.querySelector(i))return void o.debug(`Skipping css vars for component "${i}"`,`Got css vars for component ${i} but Could not find it on next page`);const r=customElements.get(i);r?Object.keys(n[i]).forEach((t=>{var s;const a=n[i],l=null===(s=null==r?void 0:r.cssVarList)||void 0===s?void 0:s[t];if(!l)return void o.info(`Could not find css variable name for ${t} in ${i}`,"Check if the css variable is defined in the component");const c=a[t];e.style.setProperty(l,c)})):o.debug(`Could not find component class for ${i}`,"Check if the component is registered")}))})(r,p,d.cssVars,this.loggerWrapper),r.replaceChildren(p);const l=!t.htmlFilename;setTimeout((()=>{o(this,Or,"m",Qr).call(this),this.validateOnBlur&&(e=>{e.querySelectorAll("*[name]").forEach((t=>{t.addEventListener("blur",(()=>{var n;const o=()=>{var e;const n=t.focus;t.focus=()=>{},null===(e=t.reportValidity)||void 0===e||e.call(t),setTimeout((()=>{t.focus=n}))};if("true"===t.getAttribute("invalid")||(null===(n=t.value)||void 0===n?void 0:n.length))return void o();const i={timer:void 0},r=e=>{"true"===e.target.getAttribute("formnovalidate")&&(clearTimeout(i.timer),i.timer=void 0)};i.timer=setTimeout((()=>{e.removeEventListener("click",r),o(),i.timer=void 0}),150),e.addEventListener("click",r,{once:!0})}))}))})(r),((e,t)=>{ti(e,null==t?void 0:t.inputs),ti(e,null==t?void 0:t.form)})(r,d),o(this,Or,"m",Br).call(this,{isFirstScreen:l,isCustomScreen:!1,stepName:e.stepName}),Po(r,this.autoFocus,l)})),o(this,Or,"m",is).call(this,c);r.querySelector(`[${go}="polling"]`)&&c(Io,{})}));l?o(this,Or,"m",Dr).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${Yn}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}Cr=new WeakMap,xr=new WeakMap,Ar=new WeakMap,jr=new WeakMap,Nr=new WeakMap,_r=new WeakMap,qr=new WeakMap,Fr=new WeakMap,Kr=new WeakMap,Jr=new WeakMap,Zr=new WeakMap,ts=new WeakMap,Or=new WeakSet,Er=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},Ur=function(e,t,i){return n(this,void 0,void 0,(function*(){var n;return(null===(n=this.nativeOptions)||void 0===n?void 0:n.bridgeVersion)>=2&&new Promise((n=>{this.nativeCallbacks.screenNext=i,this.nativeCallbacks.screenResolve=n,o(this,Or,"m",Tr).call(this,"beforeScreen",{screen:e,context:t})}))}))},Rr=function(e){var t;(null===(t=this.nativeOptions)||void 0===t?void 0:t.bridgeVersion)>=2&&o(this,Or,"m",Tr).call(this,"afterScreen",{screen:e})},Tr=function(e,t){o(this,Or,"m",rs).call(this,"bridge",{type:e,payload:t})},$r=function({errorText:e,errorType:t}){const n=()=>{var n;let o=e;try{o=(null===(n=this.errorTransformer)||void 0===n?void 0:n.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}((e,t,n="")=>{e.querySelectorAll(`[${go}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(this.contentRootElement,"error-message",o)};this.addEventListener("screen-updated",n,{once:!0}),n()},Lr=function(){var e,n,i;null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this),(e=>{var n=e.screenState,o=t(void 0===n?{}:n,["errorText","errorType"]),i=t(e,["screenState"]);return Object.assign(Object.assign({},i),{screenState:o})})),null===(n=this.stepState)||void 0===n||n.subscribe(o(this,Or,"m",$r).bind(this),(e=>{var t,n;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(n=null==e?void 0:e.screenState)||void 0===n?void 0:n.errorType}}),{forceUpdate:!0}),null===(i=this.stepState)||void 0===i||i.subscribe(o(this,Or,"m",Pr).bind(this),(e=>{var t,n;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(n=null==e?void 0:e.screenState)||void 0===n?void 0:n.errorType}}),{forceUpdate:!0})},Pr=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),Po(this.contentRootElement,this.autoFocus,!1))},Wr=function(){return n(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},Mr=function(e){return n(this,void 0,void 0,(function*(){var n;const r=Object.assign(Object.assign({},this.stepState.current),e),{next:s,stepName:a}=r,l=t(r,["next","stepName"]),c=Fo(l);let d=yield o(this,Or,"m",Ur).call(this,a,c,s);d||(d=Boolean(yield null===(n=this.onScreenUpdate)||void 0===n?void 0:n.call(this,a,c,s,this)));const u=!this.stepState.current.htmlFilename;if(o(this,_r,"f").call(this,d),o(this,Nr,"f")!==d){const[e,t]=["flow","custom"].sort((()=>d?-1:1));this.loggerWrapper.debug(`Switching from ${t} screen to ${e} screen`),i(this,Nr,d,"f"),d?this.stepState.unsubscribeAll():o(this,Or,"m",Lr).call(this)}d&&(this.loggerWrapper.debug("Showing a custom screen"),o(this,Or,"m",Br).call(this,{isFirstScreen:u,isCustomScreen:d,stepName:e.stepName})),this.stepState.forceUpdate=d}))},Dr=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Vr=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const n=`user-${t}`;e.setAttribute("name",n),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:n)}))}},Hr=function(e,t){return n(this,void 0,void 0,(function*(){var r;null===(r=o(this,xr,"f"))||void 0===r||r.abort();const s=e.querySelector('*[autocomplete="webauthn"]');if(s&&(yield li())){const{options:e,transactionId:r}=(yield o(this,Jr,"f").call(this))||{};e&&r&&(o(this,Or,"m",Vr).call(this,s),i(this,xr,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(e,o(this,xr,"f")).then((e=>n(this,void 0,void 0,(function*(){t(s.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Br=function({isFirstScreen:e,isCustomScreen:t,stepName:n}){e&&o(this,Or,"m",rs).call(this,"ready",{}),t||o(this,Or,"m",Rr).call(this,n),o(this,Or,"m",rs).call(this,"page-updated",{screenName:n}),o(this,Or,"m",rs).call(this,"screen-updated",{screenName:n})},zr=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var n,o;"slot"!==t.localName&&(null===(n=t.reportValidity)||void 0===n||n.call(t),e&&(e=null===(o=t.checkValidity)||void 0===o?void 0:o.call(t)))})),e},Gr=function(){return n(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>n(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Xr=function(e){const t=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((t=>t!==e)),r=()=>n(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",r),e.removeAttribute("loading"),t.forEach((e=>{e.removeAttribute("disabled")}));const n=yield this.getFlowConfig(),o=[...n.clientScripts||[],...n.sdkScripts||[]];this.loadSdkScripts(o)})),s=()=>{var e;window.removeEventListener("pageshow",o(this,Zr,"f")),i(this,Zr,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),r())}),"f"),window.addEventListener("pageshow",o(this,Zr,"f"),{once:!0});const t=null===(e=this.stepState)||void 0===e?void 0:e.subscribe(((e,n)=>{e===n&&r(),this.removeEventListener("popupclosed",r),this.stepState.unsubscribe(t)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?(this.addEventListener("popupclosed",r,{once:!0}),e.setAttribute("loading","true"),t.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),s())}))},Yr=function(e={}){var t,n;const o=_o(e,["externalId","email","phone"]),i=_o(e,["newPassword","password"]);if(o&&i)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:o,password:i});null===(n=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===n||n.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},Qr=function(){document.querySelectorAll('[data-hidden-input="true"]').forEach((e=>e.remove()));this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((e=>o(this,Or,"m",es).call(this,e)))},es=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const n=t.getAttribute("slot"),o=`input-${e.id}-${n}`,i=document.createElement("slot");i.setAttribute("name",o),i.setAttribute("slot",n),e.appendChild(i),t.setAttribute("slot",o),this.appendChild(t)}))},ns=function(e){return n(this,void 0,void 0,(function*(){if(o(this,Ar,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield o(this,Ar,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const t=this.loadSdkScriptsModules(),n=e.map((e=>e.id));for(const e of t)if(n.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}let i=[];for(const e of t)"function"==typeof e.refresh&&i.push(e.refresh());if(i.length>0)try{yield Wo(5e3,Promise.all(i),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},os=function(e){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((t=>{t.addEventListener("input",(()=>{var n;(null===(n=t.checkValidity)||void 0===n?void 0:n.call(t))&&o(this,ts,"f").call(this,t,e)}))}))},is=function(e){this.contentRootElement.querySelectorAll(`descope-button:not([${Qn}]), [data-type="button"]:not([${Qn}]`).forEach((t=>{t.onclick=()=>{o(this,ts,"f").call(this,t,e)}})),o(this,Or,"m",os).call(this,e),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${Yn}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},rs=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},ss=function(e,t,n){var o;const[i,r]=(null===(o=window.name)||void 0===o?void 0:o.split("|"))||[],s={data:{code:t,exchangeError:n},action:"code"};if("descope-wc"===i&&r){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",r);try{window.opener.postMessage(s,r)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(s),t.close()}try{window.close()}catch(e){}},customElements.get("descope-wc")?console.log("descope-wc is already defined"):customElements.define("descope-wc",bs);const ws=document.createElement("template");ws.innerHTML='\n<div class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n';const ys=mi(Vi)(HTMLElement);class ks extends ys{constructor(){super(),as.add(this),ls.set(this,new Xo({messages:[]})),cs.set(this,void 0),ds.set(this,void 0),us.set(this,void 0),ps.set(this,{resize:o(this,as,"m",ms).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(ws.content.cloneNode(!0)),i(this,cs,this.shadowRoot.querySelector(".debugger"),"f"),i(this,ds,o(this,cs,"f").querySelector(".content"),"f"),i(this,us,o(this,cs,"f").querySelector(".header"),"f"),o(this,as,"m",hs).call(this)}updateData(e){o(this,ls,"f").update((t=>({messages:t.messages.concat(e)})))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t,n;null===(t=e.init)||void 0===t||t.call(this),((e,t,n)=>{let o=0,i=0,r=0,s=0;function a(t){t.preventDefault(),o=r-t.clientX,i=s-t.clientY,r=t.clientX,s=t.clientY;const[a,l]=ci(e,e.offsetLeft-o,e.offsetTop-i,n);e.style.top=`${l}px`,e.style.left=`${a}px`}function l(){document.onmouseup=null,document.onmousemove=null}function c(e){e.preventDefault(),r=e.clientX,s=e.clientY,document.onmouseup=l,document.onmousemove=a}t?t.onmousedown=c:e.onmousedown=c})(o(this,cs,"f"),o(this,us,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",o(this,ps,"f").resize),(n=o(this,cs,"f")).onmousemove=e=>{(e.target.w&&e.target.w!==e.target.offsetWidth||e.target.h&&e.target.h!==e.target.offsetHeight)&&n.onresize(e),e.target.w=e.target.offsetWidth,e.target.h=e.target.offsetHeight},o(this,cs,"f").onresize=o(this,as,"m",vs).bind(this),o(this,ls,"f").subscribe(o(this,as,"m",gs).bind(this))}))}disconnectedCallback(){o(this,ls,"f").unsubscribeAll(),window.removeEventListener("resize",o(this,ps,"f").resize)}}ls=new WeakMap,cs=new WeakMap,ds=new WeakMap,us=new WeakMap,ps=new WeakMap,as=new WeakSet,hs=function(){this.injectStyle('\n .debugger {\n all: initial;\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n'),o(this,cs,"f").style.top="32px",o(this,cs,"f").style.left=window.innerWidth-300-32+"px"},gs=function(e){o(this,as,"m",fs).call(this,e),o(this,as,"m",vs).call(this)},fs=function(e){o(this,ds,"f").innerHTML=e.messages.map((e=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${e.title}\n </div>\n <div class="msg_desc">\n ${e.description}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},vs=function(){o(this,ds,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,o=t.clientHeight>20;n||o?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},ms=function(){const[e,t]=ci(o(this,cs,"f"),Number.parseInt(o(this,cs,"f").style.left,10),Number.parseInt(o(this,cs,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});o(this,cs,"f").style.top=`${t}px`,o(this,cs,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",ks);var Is=Object.freeze({__proto__:null,default:ks})}();
2
+ /*! js-cookie v3.0.5 | MIT */function bt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}var wt=function e(t,n){function o(e,o,i){if("undefined"!=typeof document){"number"==typeof(i=bt({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var r="";for(var s in i)i[s]&&(r+="; "+s,!0!==i[s]&&(r+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(o,e)+r}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],o={},i=0;i<n.length;i++){var r=n[i].split("="),s=r.slice(1).join("=");try{var a=decodeURIComponent(r[0]);if(o[a]=t.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}},remove:function(e,t){o(e,"",bt({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,bt({},this.attributes,t))},withConverter:function(t){return e(bt({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},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:"/"});var yt={default:"endpoint"},kt="Blocked by CSP",It="The endpoint parameter is not a valid URL",St="Failed to load the JS script of the agent",Ot="9319";function Ct(e,t){var n,o,i,r,s,a=[],l=(n=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var o,i=0,r=t.length;i<r;i++)!o&&i in t||(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),r=0,o=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,r++))},i=new Set,[n.current(),function(e,t){var r,s=t instanceof Error?t.message:"";if(s===kt||s===It)n.exclude(),r=0;else if(s===Ot)n.exclude();else if(s===St){var a=Date.now()-e.getTime()<50,l=n.current();l&&a&&!i.has(l)&&(i.add(l),r=0),n.postpone()}else n.postpone();var c=n.current();return void 0===c?void 0:[c,null!=r?r:e.getTime()+o()-Date.now()]}]),c=l[0],d=l[1];if(void 0===c)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var u=function(e){var n=new Date,o=function(t){return a.push({url:e,startedAt:n,finishedAt:new Date,error:t})},i=t(e);return i.then((function(){return o()}),o),i.catch((function(e){if(null!=s||(s=e),a.length>=5)throw s;var t=d(n,e);if(!t)throw s;var o,i=t[0],r=t[1];return(o=r,new Promise((function(e){return setTimeout(e,o)}))).then((function(){return u(i)}))}))};return u(c).then((function(e){return[e,a]}))}var xt="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",At=xt;function jt(n){var o;n.scriptUrlPattern;var i=n.token,r=n.apiKey,s=void 0===r?i:r,a=t(n,["scriptUrlPattern","token","apiKey"]),l=null!==(o=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(n,"scriptUrlPattern"))&&void 0!==o?o:xt,c=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,o){return e.addEventListener(t,n,o),function(){return e.removeEventListener(t,n,o)}}(document,"visibilitychange",t);return t(),[e,n]}(),d=c[0],u=c[1];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");var e=function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var n=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n("3.11.6"):e}))}(String(e),t)}))}(l,s);return Ct(e,Et)})).catch((function(e){throw u(),function(e){return e instanceof Error&&e.message===Ot?new Error(St):e}(e)})).then((function(t){var n=t[0],o=t[1];return u(),n.load(e(e({},a),{ldi:{attempts:o,visibilityStates:d}}))}))}function Et(e){return function(e,t,n){var o,i=document,r="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),i=t.blockedURI;i!==n.href&&i!==n.protocol.slice(0,-1)&&i!==n.origin||(o=t,a())};i.addEventListener(r,s);var a=function(){return i.removeEventListener(r,s)};return Promise.resolve().then(t).then((function(e){return a(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(a(),o)return n(o);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(It);var o=document.createElement("script"),i=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},r=document.head||document.getElementsByTagName("head")[0];o.onload=function(){i(),t()},o.onerror=function(){i(),n(new Error(St))},o.async=!0,o.src=e,r.appendChild(o)}))}(e)}),(function(){throw new Error(kt)})).then(Ut)}function Ut(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,o=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==o?void 0:o.configurable)?delete e[t]:o&&!o.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(Ot);return n}let Rt;const Tt=e=>{try{return a(e).exp}catch(e){return null}},$t=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:Tt(n)},Lt=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?Tt(o):void 0)},Pt=e=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=e,s=t(e,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:e.sessionJwt||n,idToken:o,refreshJwt:e.refreshJwt||i,sessionExpiration:e.sessionExpiration||Lt(e),cookieExpiration:e.cookieExpiration||$t(e)},s)},Wt=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},Nt=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json()),n=(null==t?void 0:t.authInfo)||t||{};return Pt(n)},Mt=void 0!==Rt||"undefined"!=typeof localStorage,_t=(e,t)=>{var n,o;return null===(o=null===(n=Rt||localStorage)||void 0===n?void 0:n.setItem)||void 0===o?void 0:o.call(n,e,t)},Dt=e=>{var t,n;return null===(n=null===(t=Rt||localStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,e)},qt=e=>{var t,n;return null===(n=null===(t=Rt||localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},Ft=e=>{var t,n,o,i;return null!==(i=null!==(n=null===(t=null==Rt?void 0:Rt.key)||void 0===t?void 0:t.call(Rt,e))&&void 0!==n?n:null===(o=null===localStorage||void 0===localStorage?void 0:localStorage.key)||void 0===o?void 0:o.call(localStorage,e))&&void 0!==i?i:null},Kt=(...e)=>{console.debug(...e)},Jt="3.2.0",Vt="undefined"!=typeof window,Ht=Math.pow(2,31)-1,Bt=`https://descopecdn.com/npm/oidc-client-ts@${Jt}/dist/browser/oidc-client-ts.min.js`,zt=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${Jt}/dist/browser/oidc-client-ts.min.js`,Gt="DS",Zt="DSR",Xt="DSI";const Yt=e=>(null==e?void 0:e.cookieName)||Gt;function Qt(e=""){return Dt(`${e}${Zt}`)||""}function en(e="",t){return wt.get(Yt(t))||Dt(`${e}${Gt}`)||""}function tn(e=""){return Dt(`${e}${Xt}`)||""}function nn(e="",t){qt(`${e}${Zt}`),qt(`${e}${Gt}`),qt(`${e}${Xt}`);const n=Yt(t);wt.remove(n)}const on=Vt&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",rn="vsid",sn="vrid",an="fp",ln=(e=!1)=>{const t=Dt(an);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},cn=async(e,t=on)=>{try{if(ln())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const r=i.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",s=jt({apiKey:e,endpoint:[o.toString(),yt],scriptUrlPattern:[r,At]}),a=await s,{requestId:l}=await a.get({linkedId:n}),c=((e,t)=>({[rn]:e,[sn]:t}))(n,l);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};_t(an,JSON.stringify(t))})(c)}catch(e){console.warn("Could not load fingerprint",e)}},dn=e=>{const t=ln(!0);return t&&e.body&&(e.body.fpData=t),e},un="descopeFlowNonce",pn="X-Descope-Flow-Nonce",hn="/v1/flow/start",gn="/v1/flow/next",fn=(e,t=un)=>`${t}${e}`,vn=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},mn=e=>{var t;return e.path===gn&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?vn(e.body.executionId):null},bn="dls_last_user_login_id",wn="dls_last_user_display_name",yn=e=>_t(bn,e),kn=()=>Dt(bn),In=()=>Dt(wn),Sn=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=kn(),r=In();return i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r),await e(...t)};function On(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}async function Cn(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Rn(n.publicKey.challenge),n.publicKey.user.id=Rn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=Rn(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:Tn(n.rawId),type:n.type,response:{attestationObject:Tn(n.response.attestationObject),clientDataJSON:Tn(n.response.clientDataJSON)}});var n}async function xn(e){const t=En(e);return Un(await navigator.credentials.get(t))}async function An(e,t){const n=En(e);return n.signal=t.signal,n.mediation="conditional",Un(await navigator.credentials.get(n))}async function jn(e=!1){if(!Vt)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function En(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Rn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=Rn(e.id)})),n}function Un(e){return JSON.stringify({id:e.id,rawId:Tn(e.rawId),type:e.type,response:{authenticatorData:Tn(e.response.authenticatorData),clientDataJSON:Tn(e.response.clientDataJSON),signature:Tn(e.response.signature),userHandle:e.response.userHandle?Tn(e.response.userHandle):void 0}})}function Rn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function Tn(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var $n,Ln=($n=e=>({async signUp(t,n,o){const i=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await Cn(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,r)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const i=await xn(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,i)},async signUpOrIn(t,n){var o;const i=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!i.ok)return i;if(null===(o=i.data)||void 0===o?void 0:o.create){const t=await Cn(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await xn(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,t)}},async update(t,n,o){const i=await e.webauthn.update.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await Cn(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:Cn,get:xn,isSupported:jn,conditional:An}}),(...e)=>{const t=$n(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const Pn="/fedcm/config",Wn=()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)};async function Nn(e,t){var n;try{await Mn(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function Mn(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=Wn(),s=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const l=a.data.clientId;return new Promise((e=>{var a,c;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};s.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(c=null==n?void 0:n.use_fedcm_for_prompt)||void 0===c||c,client_id:l,callback:d,nonce:r})),s.prompt((e=>{var t,n;if(i&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==i||i(n),void d()}if(o&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==o||o(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!i.credential)return null;if(null==t?void 0:t.onCodeReceived){const o=await e.oauth.verifyOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!o.ok||!o.data)throw new Error("Failed to verify OneTap client ID for provider "+i.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,o.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+i.provider);null===(o=null==t?void 0:t.onAuthenticated)||void 0===o||o.call(t,n.data)}}var _n=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await jn(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});let Dn;const qn=(e,t)=>new Promise(((n,o)=>{if(!e.length)return o(new Error("No URLs provided to loadScriptWithFallback"));const i=t();if(i)return n(i);const r=e.shift(),s=document.createElement("script");s.src=r,s.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(r),s.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},s.addEventListener("error",(()=>{qn(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)})),Fn=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await(async(e,t,n)=>{Dn||(Dn=(async()=>{try{return require("oidc-client-ts")}catch(e){return qn([Bt,zt],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await Dn;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=(null==n?void 0:n.redirectUri)||window.location.href;let s,a,l,c;if(null==n?void 0:n.issuer){if(!n.clientId)throw new Error("clientId is required when providing a custom issuer/authority");s=n.issuer,a=n.clientId,l=`${a}_user`,c="openid"}else(null==n?void 0:n.applicationId)?(s=e.httpClient.buildUrl(t),s=`${s}/${n.applicationId}`,a=t,l=`${a}_user`,c="openid email roles descope.custom_claims offline_access"):(s=e.httpClient.buildUrl(t),a=t,l=`${a}_user`,c="openid email roles descope.custom_claims offline_access");const d={authority:s,client_id:a,redirect_uri:r,response_type:"code",scope:(null==n?void 0:n.scope)||c,stateStore:new i({store:window.localStorage,prefix:a}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),{client:new o(d),stateUserKey:l}})(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),s=await i.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(s)))),_t(r,JSON.stringify({id_token:(a=s).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),s};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await o(),i=await n.createSigninRequest(e),{url:r}=i;return t||(window.location.href=r),{ok:!0,data:i}},finishLogin:i,finishLoginIfNeed:async(e="")=>{if(window.location.search.includes("code")&&window.location.search.includes("state"))return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),s=(e=>{const t=Dt(e);return t?JSON.parse(t):null})(r);if(!s)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const l=await i.useRefreshToken({state:{refresh_token:a,session_state:s.session_state,profile:s.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(l)))),l},logout:async(e,t=!1)=>{const{client:n,stateUserKey:i}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||tn(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:s}=r;return qt(i),t||window.location.replace(s),r}}},Kn=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var n;return n=t.customStorage,Rt=n,e(t)}),(e=>n=>{var{fpKey:o,fpLoad:i}=n,r=t(n,["fpKey","fpLoad"]);return Vt?(o&&i&&cn(o).catch((()=>null)),e(Wt(r,{beforeRequest:dn}))):e(r)}),(e=>n=>{var{autoRefresh:o}=n,i=t(n,["autoRefresh"]);if(!o||"undefined"!=typeof window&&window.descopeBridge)return e(i);const{clearAllTimers:r,setTimer:s}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let l,c;Vt&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&l&&new Date>l&&(Kt("Expiration time passed, refreshing session"),d.refresh(Qt()||c))}));const d=e(Wt(i,{afterRequest:async(e,t)=>{const{sessionJwt:n,refreshJwt:o,sessionExpiration:i}=await Nt(t);if(401===(null==t?void 0:t.status))Kt("Received 401, canceling all timers"),r();else if(n||i){if(l=((e,t)=>{if(t)return new Date(1e3*t);Kt("Could not extract expiration time from session token, trying to decode the token");try{const t=a(e);if(t.exp)return new Date(1e3*t.exp)}catch(e){return null}})(n,i),!l)return void Kt("Could not extract expiration time from session token");c=o;const e=(e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>Ht&&(Kt(`Timeout is too large (${t}ms), setting it to ${Ht}ms`),t=Ht),t})(l);if(r(),e<=2e4)return void Kt("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});Kt(`Setting refresh timer for ${t}. (${e}ms)`),s((()=>{Kt("Refreshing session due to timer"),d.refresh(Qt()||o)}),e)}}}));return re(d,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return Kt("Clearing all timers"),r(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.38.3"},t.baseHeaders)}))),(e=>t=>{const n=On(),o=On(),i=On(),r=On(),s=e(Wt(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))o.pub(null),i.pub(null),n.pub(null),r.pub(null);else{const e=await(async e=>{const t=await Nt(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)})(t);e&&i.pub(e);const{sessionJwt:s,sessionExpiration:a,claims:l}=await Nt(t);s&&o.pub(s),l&&r.pub(l),(a||s)&&n.pub(a||42)}}})),a=re(s,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const s=await e(...t);return o.pub(null),i.pub(null),n.pub(null),r.pub(null),s}));return Object.assign(a,{onSessionTokenChange:o.sub,onUserChange:i.sub,onClaimsChange:r.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(e=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=un}=n,r=t(n,["enableFlowNonce","nonceStoragePrefix"]);return o?(((e=un)=>{try{if(!Mt)return;for(let o=0;o<(void 0,void 0,null!==(n=null!==(t=null==Rt?void 0:Rt.length)&&void 0!==t?t:null===localStorage||void 0===localStorage?void 0:localStorage.length)&&void 0!==n?n:0);o++){const t=Ft(o);if(t&&t.startsWith(e)){const n=Dt(t);if(n)try{JSON.parse(n).expiry<Date.now()&&qt(t)}catch(e){qt(t)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}var t,n})(i),e(Wt(r,{afterRequest:async(e,t)=>{if(e.path!==hn&&e.path!==gn)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(pn);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=mn(e)),{nonce:n,executionId:vn(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);n&&o&&((e,t,n,o=un)=>{try{const i=fn(e,o),r=n?172800:10800,s={value:t,expiry:Date.now()+1e3*r,isStart:n};_t(i,JSON.stringify(s))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===hn,i)},beforeRequest:e=>{if(e.path===gn){const t=mn(e);if(t){const n=((e,t=un)=>{try{const n=fn(e,t),o=Dt(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(((e,t=un)=>{try{const n=fn(e,t);qt(n)}catch(e){console.error("Error removing flow nonce:",e)}})(e,t),null):i.value}catch(e){return console.error("Error getting flow nonce:",e),null}})(t,i);n&&(e.headers=e.headers||{},e.headers[pn]=n)}}return e}}))):e(r)}),(e=>n=>{var{storeLastAuthenticatedUser:o=!0,keepLastAuthenticatedUserAfterLogout:i=!1}=n,r=t(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!o)return Object.assign(e(r),{getLastUserLoginId:kn,getLastUserDisplayName:In});const s=e(Wt(r,{afterRequest:async(e,t)=>{var n;const{userInfo:o,lastAuth:i}=await(async e=>{if(!(null==e?void 0:e.ok))return{userInfo:void 0,lastAuth:void 0};const t=await(null==e?void 0:e.clone().json()),n=Pt((null==t?void 0:t.authInfo)||t||{});return{userInfo:(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0),lastAuth:t.lastAuth}})(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],s=null==o?void 0:o.name;r?(yn(r),(e=>{_t(wn,e)})(s)):(null==i?void 0:i.loginId)&&yn(i.loginId)}}));let a=re(s,["flow.start"],Sn);return a=re(a,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return e||(qt(bn),qt(wn)),o})(i)),Object.assign(a,{getLastUserLoginId:kn,getLastUserDisplayName:In})}),(e=>n=>{var{persistTokens:o,sessionTokenViaCookie:i,storagePrefix:r}=n,s=t(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!o||!Vt)return e(s);const a=e(Wt(s,{beforeRequest:(l=r,e=>Object.assign(e,{token:e.token||Qt(l)})),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?n||nn(r,i):((e={},t=!1,n="")=>{var o,i;const{sessionJwt:r,refreshJwt:s}=e;if(s&&_t(`${n}${Zt}`,s),r)if(t){const n=t.sameSite||"Strict",s=null===(o=t.secure)||void 0===o||o,a=null!==(i=t.domain)&&void 0!==i?i:e.cookieDomain;!function(e,t,n){if(t){const{cookieDomain:o,cookiePath:i,cookieSameSite:r,cookieExpiration:s,cookieSecure:a}=n,l=new Date(1e3*s),c=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(o);wt.set(e,t,{path:i,domain:c?o:void 0,expires:l,sameSite:r,secure:a})}}(Yt(t),r,Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:s,cookieDomain:a}))}else _t(`${n}${Gt}`,r);e.idToken&&_t(`${n}${Xt}`,e.idToken)})(await Nt(t),i,r)}}));var l;const c=re(a,["logout","logoutAll","oidc.logout"],((e,t)=>n=>async(...o)=>{const i=await n(...o);return nn(e,t),i})(r,i));return Object.assign(c,{getRefreshToken:()=>Qt(r),getSessionToken:()=>en(r),getIdToken:()=>tn(r)})}))((e=>{const t=mt(e),n=Fn(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(o,i)=>{var r;if(e.oidcConfig)try{return await n.refreshToken(o),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=en(),a=Qt();let l="";if(e.getExternalToken)try{l=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){Kt("Error getting external token while refreshing",e)}return t.refresh(o,{dcs:s?"t":"f",dcr:a?"t":"f"},l,i)},logout:async o=>{if(e.oidcConfig)try{return await n.logout({id_token_hint:o}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(o)},flow:_n(t),webauthn:Ln(t),fedcm:(o=t,i=e.projectId,{onetap:{requestExchangeCode(e){Nn(o,e)},requestAuthentication(e){Nn(o,e)}},async oneTap(e,t,n,i,r){await Mn(o,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:i,onDismissed:r})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:o.httpClient.buildUrl(i+Pn),clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return o.refresh(r.token)},isSupported:()=>Vt&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=o.httpClient.buildUrl(i+Pn);try{const o={identity:{context:e||"signin",providers:[{configURL:n,clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return!!r&&!!r.token}catch(e){return!1}}}),oidc:n});var o,i})),Jn="undefined"!=typeof localStorage,Vn="J151000",Hn="E103205",Bn=Jn&&localStorage.getItem("base.content.url")||"",zn="base.ui.components.url";Jn&&localStorage.getItem(zn),Jn&&localStorage.getItem(zn);const Gn="descope-login-flow",Zn="code",Xn="redirect_mode",Yn="data-exclude-field",Qn="data-exclude-next",eo="dls_last_auth",to="state_id",no="saml_idp_state_id",oo="saml_idp_username",io="descope_idp_initiated",ro="sso_app_id",so="third_party_app_id",ao="third_party_app_state_id",lo="oidc_login_hint",co="oidc_prompt",uo="oidc_resource",po="oidc_error_redirect_uri",ho="application_scopes",go="data-type",fo="redirect",vo="poll",mo="webauthnCreate",bo="webauthnGet",wo="nativeBridge",yo="loadForm",ko="submit",Io="polling",So=["descope-multi-select-combo-box","descope-text-area"],Oo=["cssVars","componentsConfig","inputs","errorText","errorType","clientScripts"];var Co;!function(e){e.backward="backward",e.forward="forward"}(Co||(Co={}));const xo=["descope-enriched-text"];function Ao(e){return new URLSearchParams(window.location.search).get(e)}function jo(e){if(window.history.replaceState&&Ao(e)){const t=new URL(window.location.href),n=new URLSearchParams(t.search);n.delete(e),t.search=n.toString(),window.history.replaceState({},"",t.toString())}}function Eo(e,t){if(!t)return;const n=+e,o=+t;return Number.isNaN(n)||Number.isNaN(o)?void 0:n>o?Co.forward:n<o?Co.backward:void 0}const Uo=e=>{let[t="",n=""]=(Ao(Gn)||"").split("_");const o=(e=>{var t;return(null===(t=/(.*)\|#\|.*/.exec(e))||void 0===t?void 0:t[1])||""})(t);return(!e||o&&o!==e)&&(t="",n=""),{executionId:t,stepId:n,executionFlowId:o}};function Ro(){jo(Gn)}const To=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),$o=(e,t)=>{const{executionId:n,stepId:o,executionFlowId:i}=Uo(e);if(i&&e!==i)return t.debug("Flow id does not match the execution flow id, skipping url params handling"),{ssoQueryParams:{}};(n||o)&&Ro();const r=Ao("t")||void 0;r&&jo("t");const s=Ao(Zn)||void 0;s&&jo(Zn);const a="popup"===Ao(Xn);a&&jo(Xn);const l=Ao("err")||void 0;l&&jo("err");const{redirectAuthCodeChallenge:c,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthInitiator:p}={redirectAuthCodeChallenge:Ao("ra-challenge"),redirectAuthCallbackUrl:Ao("ra-callback"),redirectAuthBackupCallbackUri:Ao("ra-backup-callback"),redirectAuthInitiator:Ao("ra-initiator")},h=Ao(to);h&&jo(to);const g=Ao(no);g&&jo(no);const f=Ao(oo);g&&jo(oo);const v=Ao(io);v&&jo(io);const m=Ao(ro);m&&jo(ro);const b=Ao(so);b&&jo(so);const w=Ao(ao);w&&jo(ao);const y=Ao(ho);y&&jo(ho);const k=Ao(lo);k&&jo(lo);const I=Ao(co);I&&jo(co);const S=Ao(po);S&&jo(po);const O=Ao(uo);O&&jo(uo);return{executionId:n,stepId:o,token:r,code:s,isPopup:a,exchangeError:l,redirectAuthCodeChallenge:c,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthInitiator:p,ssoQueryParams:{oidcIdpStateId:h,samlIdpStateId:g,samlIdpUsername:f,descopeIdpInitiated:"true"===v,ssoAppId:m,oidcLoginHint:k,oidcPrompt:I,oidcErrorRedirectUri:S,oidcResource:O,thirdPartyAppId:b,thirdPartyAppStateId:w,applicationScopes:y}}},Lo=e=>{let t,n;return Object.assign(((...o)=>{return t&&(r=o,(i=t).length===r.length&&i.every(((e,t)=>e===r[t])))||(t=o,n=e(...o)),n;var i,r}),{reset:()=>{t=void 0,n=void 0}})},Po=(e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}};function Wo(e,t,n){return new Promise(((o,i)=>{let r=!1;const s=setTimeout((()=>{r=!0,void 0!==n?o(n):i(new Error(`Promise timed out after ${e} ms`))}),e);t.then((e=>{r||(clearTimeout(s),o(e))})).catch((e=>{r||(clearTimeout(s),i(e))}))}))}const No=(e,{oidcIdpStateId:t,samlIdpStateId:n,samlIdpUsername:o,ssoAppId:i,oidcLoginHint:r,oidcPrompt:s,oidcErrorRedirectUri:a,oidcResource:l,thirdPartyAppId:c,thirdPartyAppStateId:d,applicationScopes:u})=>!(!e||t||n||o||i||r||s||a||l||c||d||u),Mo=e=>null==e?void 0:e.submit(),_o=(e,t)=>{const n=t.find((t=>e[t]));return n?e[n]:null},Do=(e,t=100)=>{let n;return function(...o){n||e.apply(this,o),clearTimeout(n),n=setTimeout((()=>{n=null}),t)}};function qo(e){if(e)return{locale:e.toLowerCase(),fallback:e.toLowerCase()};const t=navigator.language;return t?t.includes("-")?{locale:t.toLowerCase(),fallback:t.split("-")[0].toLowerCase()}:{locale:t.toLowerCase(),fallback:t.toLowerCase()}:{locale:"",fallback:""}}const Fo=e=>{var t,n,o;const i=(r=e.screenState,s=(e,t)=>Oo.includes(t)||t.startsWith("_"),Object.fromEntries(Object.entries(r).filter((([e,t])=>!s(t,e)))));var r,s;const{screenState:{errorText:a,errorType:l}}=e;return(a||l)&&(i.error={text:a,type:l}),e.action&&(i.action=e.action),(null===(o=null===(n=null===(t=e.screenState)||void 0===t?void 0:t.componentsConfig)||void 0===n?void 0:n.thirdPartyAppApproveScopes)||void 0===o?void 0:o.data)&&(i.inboundAppApproveScopes=e.screenState.componentsConfig.thirdPartyAppApproveScopes.data),i},Ko=e=>{const t=Object.assign({},e);return e.inboundAppApproveScopes&&(t.thirdPartyAppApproveScopes=e.inboundAppApproveScopes),t};function Jo(e,t){return`sdkScriptsResults.${t?`${e}_${t}`:e}`}const Vo=(e,t,n,o)=>{const i=void 0!==window.screenLeft?window.screenLeft:window.screen.left,r=void 0!==window.screenTop?window.screenTop:window.screen.top,s=((window.innerWidth||document.documentElement.clientWidth||window.screen.width)-n)/2+i,a=((window.innerHeight||document.documentElement.clientHeight||window.screen.height)-o)/2+r,l=function(){const e=navigator.userAgent||"",t=/\b(iPhone)\b/.test(e),n=/Safari/.test(e)&&!/CriOS|FxiOS|OPiOS|EdgiOS|Chrome|Chromium/.test(e);return t&&n}()?"about:blank":"",c=window.open(l,t,`width=${n},height=${o},top=${a},left=${s},scrollbars=yes,resizable=yes`);return c.location.href=e,c.focus(),c};var Ho,Bo,zo,Go;function Zo(e,t){const n=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(n.length!==o.length)return!1;for(let o=0;o<n.length;o+=1){const i=n[o],r=e[i],s=t[i];if(null===r||null===s){if(r!==s)return!1}else if("object"==typeof r&&"object"==typeof s){if(!Zo(r,s))return!1}else if(r!==s)return!1}return!0}class Xo{constructor(e={},{forceUpdate:t=!1}={}){Ho.set(this,void 0),Bo.set(this,{}),zo.set(this,0),Go.set(this,!0),this.update=e=>{const t="function"==typeof e?e(o(this,Ho,"f")):e,n=Object.assign(Object.assign({},o(this,Ho,"f")),t),r=o(this,Ho,"f");i(this,Ho,n,"f"),Object.freeze(o(this,Ho,"f")),setTimeout((()=>{Object.values(o(this,Bo,"f")).forEach((({cb:e,selector:t,forceUpdate:i})=>{const s=t(r),a=t(n);(o(this,Go,"f")||i||(function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(a)?!Zo(s,a):s!==a))&&e(a,s,((e,t)=>n=>e[n]!==t[n])(a,s))}))}),0)},i(this,Ho,e,"f"),i(this,Go,t,"f")}get current(){return Object.assign({},o(this,Ho,"f"))}set forceUpdate(e){i(this,Go,e,"f")}subscribe(e,t=e=>e,{forceUpdate:n=!1}={}){return i(this,zo,o(this,zo,"f")+1,"f"),o(this,Bo,"f")[o(this,zo,"f")]={cb:e,selector:t,forceUpdate:n},o(this,zo,"f").toString()}unsubscribe(e){const t=!!o(this,Bo,"f")[e];return t&&delete o(this,Bo,"f")[e],t}unsubscribeAll(){return i(this,Bo,{},"f"),!0}}Ho=new WeakMap,Bo=new WeakMap,zo=new WeakMap,Go=new WeakMap;const Yo=["*","#","/","(",")","[","]","_","<",">","`"],Qo=e=>{const t=Yo.map((t=>`${e}${t}`)).join("|");return new RegExp(`(${t})`,"g")},ei=["disabled"],ti=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${Yn}])`)).forEach((e=>{e.value=n}))}))},ni=(e,t)=>t.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),e),oi=(e,t,n)=>e.replace(/{{(.+?)}}/g,((e,o)=>n?(e=>"string"!=typeof e?e:e.replace(Qo("\\"),"\\$1"))(ni(t,o)):ni(t,o))),ii=(e,t)=>{e.querySelectorAll("descope-text,descope-link,descope-enriched-text,descope-code-snippet").forEach((e=>{const n=(o=e.localName,xo.includes(o));var o;e.textContent=oi(e.textContent,t,n);const i=e.getAttribute("href");i&&e.setAttribute("href",oi(i,t))}))},ri=(e,t,n)=>{e.querySelectorAll(`[${go}="${t}"]`).forEach((e=>{e.setAttribute("href",n)}))},si=(e,t,n)=>{var o,i;const r=null===(o=customElements.get(t))||void 0===o?void 0:o.cssVarList.url;n&&r&&(null===(i=null==e?void 0:e.style)||void 0===i||i.setProperty(r,`url(data:image/jpg;base64,${n})`))},ai=(e,n,o,i,r)=>{var s,a;ri(e,"totp-link",null===(s=null==n?void 0:n.totp)||void 0===s?void 0:s.provisionUrl),ri(e,"notp-link",null===(a=null==n?void 0:n.notp)||void 0===a?void 0:a.redirectUrl),ii(e,n),((e,n,o)=>{if(!n)return;const{componentsDynamicAttrs:i}=n,r=t(n,["componentsDynamicAttrs"]),s=Object.keys(r).reduce(((e,t)=>(e[`[name=${t}]`]=r[t],e)),{});i&&Object.keys(i).forEach((e=>{const t=i[e];if(t){const{attributes:n}=t;n&&Object.keys(n).length&&(s[e]=n)}})),Object.keys(s).forEach((t=>{e.querySelectorAll(t).forEach((e=>{const n=s[t];Object.keys(n).forEach((t=>{let i=n[t];if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){o.error(`Could not stringify value "${i}" for "${t}"`,e.message),i=""}e.setAttribute(t,i)}))}))}))})(e,o,r),((e,t)=>{e.querySelectorAll("[data-has-dynamic-attr-values]").forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=oi(e.value,t)}))}))})(e,n),((e,t)=>{Object.entries(t).forEach((([t,n])=>{e.querySelectorAll(`[name="${t}"]`).forEach((e=>{Object.entries(n).forEach((([t,n])=>{ei.includes(t)&&e.setAttribute(t,n)}))}))}))})(e,i)},li=Lo((()=>n(void 0,void 0,void 0,(function*(){var e,t;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return!1;try{const n=Promise.all([null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable(),null===(t=window.PublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable()]).then((e=>e.every((e=>!!e)))),o=(()=>{var e;const t=null===(e=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===e?void 0:e.brands,n=null==t?void 0:t.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t)));return n?n.version:0})()>=108;return yield Wo(100,n,o)}catch(e){return console.error("Conditional login check failed",e),!1}})))),ci=(e,t,n,o={})=>{var i,r,s,a;return[Math.min(Math.max(t,("all"===o.left?e.offsetWidth:null!==(i=o.left)&&void 0!==i?i:0)-e.offsetWidth),window.innerWidth-("all"===o.right?e.offsetWidth:null!==(r=o.right)&&void 0!==r?r:0)),Math.min(Math.max(n,("all"===o.top?e.offsetHeight:null!==(s=o.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===o.bottom?e.offsetHeight:null!==(a=o.bottom)&&void 0!==a?a:0))]};let di;const ui=(e,t)=>{di?di.setItem(e,t):void 0!==(null===window||void 0===window?void 0:window.localStorage)&&window.localStorage.setItem(e,t)},pi=e=>di?di.getItem(e):void 0!==(null===window||void 0===window?void 0:window.localStorage)?window.localStorage.getItem(e):null,hi="dls_ab_testing_id",gi={"lastAuth.loginId":{"not-empty":e=>{var t;return!!e.loginId||!!(null===(t=e.lastAuth)||void 0===t?void 0:t.loginId)},empty:e=>{var t;return!e.loginId&&!(null===(t=e.lastAuth)||void 0===t?void 0:t.loginId)}},idpInitiated:{"is-true":e=>!!e.code,"is-false":e=>!e.code},externalToken:{"is-true":e=>!!e.token,"is-false":e=>!e.token},abTestingKey:{"greater-than":(e,t)=>(e.abTestingKey||0)>t,"less-than":(e,t)=>(e.abTestingKey||0)<t,"greater-than-or-equal":(e,t)=>(e.abTestingKey||0)>=t,"less-than-or-equal":(e,t)=>(e.abTestingKey||0)<=t,"in-range":(e,t)=>{const[n,o]=t?t.split(",").map(Number):[void 0,void 0];return(e.abTestingKey||0)>=(null!=n?n:0)&&(e.abTestingKey||0)<=(null!=o?o:0)},"not-in-range":(e,t)=>{const[n,o]=t?t.split(",").map(Number):[void 0,void 0];return!(void 0!==n&&void 0!==o&&!Number.isNaN(n)&&!Number.isNaN(o))||((e.abTestingKey||0)<n||(e.abTestingKey||0)>o)},"devised-by":(e,t)=>{const n=Number(t);return!Number.isNaN(n)&&(e.abTestingKey||0)%n==0}}};function fi(e){const t={};try{Object.assign(t,JSON.parse(pi(eo)))}catch(e){}return(null==t?void 0:t.loginId)||e?t:{}}function vi(e,t){(null==e?void 0:e.authMethod)&&(t&&!(null==e?void 0:e.loginId)||ui(eo,JSON.stringify(e)))}function mi(...e){return t=>e.reduce(((e,t)=>t(e)),t)}const bi=e=>{const t=Symbol((e=>{const t=e.toString();let n=0;for(let e=0;e<t.length;e++)n=(n<<5)-n+t.charCodeAt(e),n&=n;return n.toString(16)})(e));return n=>{if(n[t])return n;const o=e(n);return o[t]=!0,o}},wi=["error","warn","info","debug"],yi=bi((e=>{var t,n,r,s;return s=class extends e{constructor(){super(...arguments),t.add(this),n.set(this,o(this,t,"m",r).call(this,console))}set logger(e){i(this,n,o(this,t,"m",r).call(this,e||console),"f")}get logger(){return o(this,n,"f")}onLogEvent(e,t){}},n=new WeakMap,t=new WeakSet,r=function(e){return wi.reduce(((t,n)=>(t[n]=(...t)=>{var o;this.onLogEvent(n,t),null===(o=e[n])||void 0===o||o.call(e,...t)},t)),{})},s})),ki="undefined"!=typeof localStorage,Ii=ki&&localStorage.getItem("base.content.url")||"",Si=(e,t)=>!t&&`${e} cannot be empty, please make sure to set this attribute`,Oi=bi((e=>{var t,n;return n=class extends e{constructor(){super(...arguments),t.set(this,!0)}connectedCallback(){var e,n;null===(e=super.connectedCallback)||void 0===e||e.call(this),(null===(n=this.shadowRoot)||void 0===n?void 0:n.isConnected)&&o(this,t,"f")&&(i(this,t,!1,"f"),this.init())}async init(){}},t=new WeakMap,n})),Ci=bi((e=>{var t,n;const i=mi(yi,Oi)(e);return n=class extends i{constructor(){super(...arguments),t.set(this,{})}async init(){var e,n,i;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),n=this,i=e=>{var n;null===(n=o(this,t,"f")[e])||void 0===n||n.forEach((t=>{t(e,this.getAttribute(e))}))},Array.from(n.attributes).forEach((e=>i(e.name))),new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&i(e.attributeName)}))})).observe(n,{attributes:!0})}observeAttribute(e,n){o(this,t,"f")[e]||(o(this,t,"f")[e]=[]);const i=o(this,t,"f")[e].push(n);return()=>o(this,t,"f")[e].splice(i,1)}observeAttributes(e,t){const n=e.reduce(((e,n)=>(e.push(this.observeAttribute(n,t)),e)),[]);return()=>n.forEach((e=>e()))}},t=new WeakMap,n})),xi=e=>t=>{var n,i,r;const s=mi(yi,Oi,Ci)(t),a=Object.keys(e);return r=class extends s{constructor(...e){super(...e),n.add(this),this.observeAttributes(a,o(this,n,"m",i).bind(this))}async init(){var e;a.forEach((e=>o(this,n,"m",i).call(this,e,this.getAttribute(e)))),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},n=new WeakSet,i=function(t,n){const o=e[t],i="function"==typeof o?o(t,n):o;i&&this.logger.error(i)},r};xi.missingAttrValidator=Si;const Ai=bi((e=>{const t=mi(xi({"project-id":Si}))(e);return class extends t{get projectId(){return this.getAttribute("project-id")}}})),ji=bi((e=>class extends e{get baseUrl(){return this.getAttribute("base-url")||""}})),Ei="Trying the next fallback URL...",Ui=async(e,t,{logger:n}={})=>{try{return await fetch(e,t)}catch(o){return null==n||n.debug(`Network error fetching URL ${e} [${o.message}], retrying...`),fetch(e,t)}};function Ri({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:o="https://static.descope.com/pages"}){const i=new URL(o);return i.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(i.pathname,e,n,t),i.baseUrl=o,i}const Ti=bi((e=>{var t,n,r,s,a;const l=mi(yi,Ai,ji)(e);return a=class extends l{constructor(){super(...arguments),t.add(this),n.set(this,void 0),r.set(this,void 0)}async fetchStaticResource(e,n){const a=o(this,t,"m",s).call(this,e),l=Array.isArray(a)?e=>{if(e!==a.length-1){const{baseUrl:t}=a[e];i(this,r,t,"f")}}:null;try{const e=await(async(e,t,{logger:n,onSuccess:o}={})=>{const i=Array.isArray(e)?e:[e];for(let e=0;e<i.length;e++){const r=i[e],s=e===i.length-1;try{const i=await Ui(r.toString(),t,{logger:n});if(i.ok)return null==o||o(e),null==n||n.debug(`Successfully fetched URL ${r}`),i;const a=`Error fetching URL ${r} [${i.status}]`;if(s)throw new Error(a);null==n||n.debug(`${a}. ${Ei}`)}catch(e){const t=`Error fetching URL ${r} [${e.message}]`;if(s)throw new Error(t);null==n||n.debug(`${t}. ${Ei}`)}}})(a,{cache:"default"},{logger:this.logger,onSuccess:l});return{body:await e[n](),headers:Object.fromEntries(e.headers.entries())}}catch(e){this.logger.error(e.message)}}get baseStaticUrl(){return this.getAttribute("base-static-url")||""}},n=new WeakMap,r=new WeakMap,t=new WeakSet,s=function(e){const t=Ii||this.baseStaticUrl;if(t)return Ri({projectId:this.projectId,filename:e,baseUrl:t});const s=o(this,n,"f")!==this.baseUrl,a=s&&!!this.baseUrl;s&&(i(this,n,this.baseUrl,"f"),i(this,r,void 0,"f"));const l=Ri({projectId:this.projectId,filename:e,baseUrl:o(this,r,"f")});if(!a)return l;return[Ri({projectId:this.projectId,filename:e,baseUrl:this.baseUrl+"/pages"}),l]},a})),$i=bi((e=>{var t,n;const i=mi(xi({"project-id":Si}))(e);return n=class extends i{constructor(){super(...arguments),t.set(this,new Map)}onReset(e,n){if(o(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} already exists`);return o(this,t,"f").set(e,n),()=>{o(this,t,"f").delete(e)}}async reset(...e){0===e.length?await Promise.all(Array.from(o(this,t,"f").values()).map((e=>e()))):await Promise.all(e.map((e=>{var n;if(!o(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} does not exist`);return null===(n=o(this,t,"f").get(e))||void 0===n?void 0:n()})))}},t=new WeakMap,n})),Li=bi((e=>{var t,n,r,s,a;const l=mi(Ti,$i,Oi)(e);return a=class extends l{constructor(){super(...arguments),t.add(this),r.set(this,void 0),s.set(this,(async()=>{try{const{body:e,headers:t}=await this.fetchStaticResource("config.json","json");return{projectConfig:e,executionContext:{geo:t["x-geo"]}}}catch(e){this.logger.error("Cannot fetch config file","make sure that your projectId & flowId are correct")}}))}async init(){await super.init(),this.onReset("config",o(this,t,"m",n).bind(this))}get config(){return o(this,r,"f")||i(this,r,o(this,s,"f").call(this),"f"),o(this,r,"f")}},r=new WeakMap,s=new WeakMap,t=new WeakSet,n=function(){i(this,r,void 0,"f")},a})),Pi=["https://descopecdn.com","https://static.descope.com","https://cdn.jsdelivr.net"],Wi=e=>{let t=0;const n=e.toString();for(let e=0;e<n.length;e++){t=(t<<5)-t+n.charCodeAt(e),t|=0}return`${Math.abs(t).toString()}`},Ni=(e,t)=>new Promise(((n,o)=>{const i=(e=>{const t=document.createElement("script");return t.id=e,t})(e);i.onerror=e=>{i.setAttribute("status","error"),o(e)},i.onload=()=>{i.setAttribute("status","loaded"),n(i)},i.src=t.toString(),document.body.appendChild(i)})),Mi=e=>"loaded"===e.getAttribute("status")?Promise.resolve(e):(e=>"error"===e.getAttribute("status"))(e)?Promise.reject():new Promise(((t,n)=>{e.addEventListener("load",(()=>{t(e)})),e.addEventListener("error",(e=>{n(e)}))})),_i=bi((e=>{const t=mi(yi)(e);return class extends t{get baseCdnUrl(){return this.getAttribute("base-cdn-url")||""}injectNpmLib(e,t,n="",o=[]){return this.logger.debug(`Injecting npm lib: "${e}" with version: "${t}"`),(async(e,t)=>{for(const o of e){const{id:e,url:i}=o,r=(n=e,document.querySelector(`script#${n}`));if(r)try{return await Mi(r),o}catch(e){t(o,!0)}else try{return await Ni(e,i),o}catch(e){t(o,!1)}}var n;throw new Error("All scripts failed to load")})(((e,t,n,o="")=>e.reduce(((e,i)=>{const r=i;if(!r)return e;let s;try{s=new URL(r)}catch(e){throw new Error(`Invalid URL: ${r}`)}return"/"!==s.pathname||(s.pathname=`/npm/${t}@${n}/${o}`),[...e,{url:s,id:`npmlib-${t.replaceAll("@","").replaceAll("/","_")}-${Wi(s)}`}]}),[]))([...o,this.baseCdnUrl,...Pi],e,t,n),((e,t)=>{t?this.logger.error(`Existing script cannot be loaded: "${e.url}"`):this.logger.error(`Cannot load script from URL, Make sure this URL is valid and return the correct script: "${e.url}"`)}))}}})),Di="base.ui.components.url",qi=ki&&localStorage.getItem(Di),Fi=bi((e=>{var t,n,r,s,a,l;const c=mi(yi,Li,_i)(e);return l=class extends c{constructor(){super(...arguments),t.add(this),r.set(this,void 0)}get descopeUi(){return o(this,r,"f")||i(this,r,o(this,t,"m",a).call(this),"f"),o(this,r,"f")}async loadDescopeUiComponents(e){const n=Array.isArray(e)?e:(e=>[...Array.from(e.content.querySelectorAll("*")).reduce(((e,t)=>t.localName.startsWith("descope-")?e.add(t.localName):e),new Set)])(e);return Promise.all(n.map((e=>o(this,t,"m",s).call(this,e))))}},r=new WeakMap,t=new WeakSet,n=async function(){var e;const t=await this.config,n=null===(e=null==t?void 0:t.projectConfig)||void 0===e?void 0:e.componentsVersion;return n?this.logger.debug(`Got component version "${n}"`):this.logger.error("Could not get components version"),n},s=async function(e){if(!!customElements.get(e))return void this.logger.debug(`Loading component "${e}" is skipped as it is already defined`);const t=await this.descopeUi;if(t[e])try{return await t[e]()}catch(t){if("NotSupportedError"!==t.name)throw t;console.debug(`Encountered an error while attempting to define the "${e}" component, it is likely that this component is already defined`)}else this.logger.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)},a=async function(){if(globalThis.DescopeUI)return globalThis.DescopeUI;try{return await this.injectNpmLib("@descope/web-components-ui",await o(this,t,"m",n).call(this),"dist/umd/index.js",[qi]),this.logger.debug("DescopeUI was loaded"),globalThis.DescopeUI}catch(e){throw this.logger.error(e),new Error("DescopeUI was not loaded")}},l})),Ki=bi((e=>{var t,n,i;const r=mi(Oi,Ci)(e);return i=class extends r{constructor(){super(...arguments),t.add(this)}get nonce(){return this.getAttribute("nonce")||""}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),this.observeAttribute("nonce",o(this,t,"m",n).bind(this)),o(this,t,"m",n).call(this)}},t=new WeakSet,n=function(){this.nonce&&(window.DESCOPE_NONCE=this.nonce)},i}));class Ji{constructor(e,t,{prepend:n=!1}={}){this.styleEle=document.createElement("style"),this.styleEle.setAttribute("nonce",t),this.ref=e,this.ref&&(n?this.ref.prepend(this.styleEle):this.ref.append(this.styleEle))}replaceSync(e){this.styleEle.textContent=e}get cssRules(){var e;return null===(e=this.styleEle.sheet)||void 0===e?void 0:e.cssRules}}const Vi=bi((e=>{const t=mi(Ki)(e);return class extends t{injectStyle(e,{prepend:t=!1}={}){let n;try{n=new CSSStyleSheet}catch(e){n=new Ji(this.shadowRoot,this.nonce,{prepend:t})}if(e&&n.replaceSync(e),n instanceof CSSStyleSheet){const e=this.shadowRoot;if(e&&"adoptedStyleSheets"in e){const o=[...e.adoptedStyleSheets||[]];o[t?"unshift":"push"](n),e.adoptedStyleSheets=o}}return n}}})),Hi="content-root",Bi="root",zi=bi((e=>{const t=mi(Vi)(e);return class extends t{constructor(...e){var t,n;super(...e),this.attachShadow({mode:"open"}).innerHTML=`\n <div id="${Bi}">\n <div id="${Hi}"></div>\n </div>\n `,this.injectStyle(`\n #${Bi}, #${Hi} {\n height: 100%;\n }\n #${Bi} {\n position: relative;\n height: fit-content;\n }\n `),this.contentRootElement=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById(Hi),this.rootElement=null===(n=this.shadowRoot)||void 0===n?void 0:n.getElementById(Bi)}}})),Gi=(e,t)=>!!t&&"light"!==t&&"dark"!==t&&'Supported theme values are "light", "dark", or leave empty for using the OS theme',Zi=bi((e=>{var t,n,r,s,a,l,c,d,u,p,h,g,f,v;const m=mi(xi({theme:Gi}),Ti,Oi,Fi,Li,zi,Ci,Vi)(e);return v=class extends m{constructor(){super(...arguments),t.add(this),n.set(this,void 0),r.set(this,void 0),h.set(this,(()=>{o(this,t,"m",g).call(this),o(this,f,"f").call(this,"os"===this.getAttribute("theme"))})),f.set(this,(e=>{var n,i,r;const s=e?"addEventListener":"removeEventListener";null===(r=null===(i=null===(n=window.matchMedia)||void 0===n?void 0:n.call(window,"(prefers-color-scheme: dark)"))||void 0===i?void 0:i[s])||void 0===r||r.call(i,"change",(()=>o(this,t,"m",g).call(this)))}))}get theme(){var e,t;const n=this.getAttribute("theme");if("os"===n){return window.matchMedia&&(null===(t=null===(e=window.matchMedia)||void 0===e?void 0:e.call(window,"(prefers-color-scheme: dark)"))||void 0===t?void 0:t.matches)?"dark":"light"}return n||"light"}get styleId(){return this.getAttribute("style-id")||"theme"}async init(){var e;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),o(this,h,"f").call(this),await Promise.all([o(this,t,"m",l).call(this),o(this,t,"m",c).call(this)]),this.observeAttributes(["theme"],o(this,h,"f")),this.observeAttributes(["style-id"],(()=>{i(this,r,null,"f"),o(this,t,"m",u).call(this),o(this,t,"m",l).call(this),o(this,t,"m",c).call(this)}))}},n=new WeakMap,r=new WeakMap,h=new WeakMap,f=new WeakMap,t=new WeakSet,s=async function(){try{const{body:e}=await this.fetchStaticResource(`${this.styleId}.json`,"json");return e}catch(e){this.logger.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}},a=function(){return o(this,r,"f")||(i(this,r,o(this,t,"m",s).call(this),"f"),o(this,r,"f").then((e=>this.logger.debug("Fetched theme",e)))),o(this,r,"f")},l=async function(){var e,r;const s=await o(this,t,"a",a);s&&(o(this,n,"f")||i(this,n,this.injectStyle(""),"f"),o(this,n,"f").replaceSync(((null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.globals)||"")+((null===(r=null==s?void 0:s.dark)||void 0===r?void 0:r.globals)||"")))},c=async function(){var e,n;const i=await o(this,t,"a",a);if(!i)return;const r=await this.descopeUi;(null==r?void 0:r.componentsThemeManager)&&(r.componentsThemeManager.themes={light:null===(e=null==i?void 0:i.light)||void 0===e?void 0:e.components,dark:null===(n=null==i?void 0:i.dark)||void 0===n?void 0:n.components})},d=async function(){var e,t;const{projectConfig:n}=await this.config||{},o=null===(e=null==n?void 0:n.styles)||void 0===e?void 0:e[this.styleId],i=null==n?void 0:n.cssTemplate,r=o||i;return null===(t=null==r?void 0:r[this.theme])||void 0===t?void 0:t.fonts},u=async function(){const e=await o(this,t,"m",d).call(this);e?Object.values(e).forEach((e=>{e.url&&(this.logger.debug(`Loading font from URL "${e.url}"`),(e=>{const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url))})):this.logger.debug("No fonts to load")},p=async function(){this.rootElement.setAttribute("data-theme",this.theme);const e=await this.descopeUi;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)},g=function(){o(this,t,"m",u).call(this),o(this,t,"m",p).call(this)},v})),Xi=(e,t="")=>Object.keys(e).reduce(((n,o)=>{var i;if(Array.isArray(e[o]))return Object.assign(Object.assign({},n),{[o]:{value:e[o].map((e=>"object"==typeof e&&null!==e?Xi(e):e))}});if("object"==typeof e[o]&&null!==e[o]&&!(null===(i=e[o])||void 0===i?void 0:i.value))return Object.assign(Object.assign({},n),Xi(e[o],`${t+o}.`));const r="object"==typeof e[o]?e[o]:{value:e[o]},s=Object.assign(Object.assign({},n),{[t+o]:r,[`form.${t}${o}`]:r});return"displayName"===o?Object.assign(Object.assign({},s),{[`${t}fullName`]:r,[`form.${t}fullName`]:r}):s}),[]),Yi=bi((e=>{var t,n,i,r;return r=class extends e{constructor(){super(...arguments),t.add(this)}connectedCallback(){var e;o(this,t,"m",n).call(this)&&o(this,t,"m",i).call(this),null===(e=super.connectedCallback)||void 0===e||e.call(this)}},t=new WeakSet,n=function(){return!this.shadowRoot.host.closest("form")&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},i=function(){const e=this.shadowRoot.host,t=document.createElement("form");t.style.width="100%",t.style.height="100%",e.parentElement.appendChild(t),t.appendChild(e)},r}));var Qi,er,tr,nr,or,ir,rr,sr,ar,lr,cr,dr,ur,pr,hr,gr,fr,vr,mr,br,wr,yr;const kr=mi(Zi,Ti,Yi,Vi)(HTMLElement);class Ir extends kr{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(e){super(),Qi.add(this),tr.set(this,!1),nr.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),o(this,Qi,"m",yr).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)},debug:(e,t="")=>{this.logger.debug(e,t)}},or.set(this,new Xo),ir.set(this,new Xo),rr.set(this,{}),this.getComponentsContext=()=>o(this,rr,"f"),this.nextRequestStatus=new Xo({isLoading:!1}),sr.set(this,void 0),ar.set(this,{popstate:o(this,Qi,"m",pr).bind(this),componentsContext:o(this,Qi,"m",mr).bind(this)}),lr.set(this,void 0),this.getConfig=()=>n(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,lr,e,"f"),o(this,Qi,"m",dr).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(e){return{}}}get tenantId(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var e;const t=null!==(e=this.getAttribute("auto-focus"))&&void 0!==e?e:"true";return"skipFirstScreen"===t?t:"true"===t}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var e;return"true"===(null!==(e=this.getAttribute("store-last-authenticated-user"))&&void 0!==e?e:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return(e=>{try{return Xi(JSON.parse(e))}catch(e){return{}}})(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return e=this.formConfig,t="value",Object.fromEntries(Object.entries(e).map((([e,n])=>[e,n[t]])));var e,t}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const e=JSON.parse(this.getAttribute("outbound-app-scopes"));return e||null}catch(e){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return o(this,nr,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,nr,e,"f"),(e=>{di=e})(e)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"executionContext"in e?e.executionContext:void 0}))}getProjectConfig(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"projectConfig"in e?e.projectConfig:void 0}))}getFlowConfig(){return n(this,void 0,void 0,(function*(){var e,t;const n=yield this.getProjectConfig(),o=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=o.version)&&void 0!==t||(o.version=0),o}))}getTargetLocales(){return n(this,void 0,void 0,(function*(){const e=yield this.getFlowConfig();return((null==e?void 0:e.targetLocales)||[]).map((e=>e.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=e=>{var t,n,o;const i=!!(null===(t=this.shadowRoot.activeElement)||void 0===t?void 0:t.getAttribute("href")),r=So.includes(null!==(o=null===(n=this.shadowRoot.activeElement)||void 0===n?void 0:n.localName)&&void 0!==o?o:"");if("Enter"!==e.key||i||r)return;e.preventDefault();const s=this.rootElement.querySelectorAll("descope-button");if(1===s.length&&"false"!==s[0].getAttribute("auto-submit"))return void s[0].click();const a=Array.from(s).filter((e=>"true"===e.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const l=Array.from(s).filter((e=>"button"===e.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const e=Array.from(s).filter((e=>"sso"===e.getAttribute("data-type")));1===e.length&&"false"!==e[0].getAttribute("auto-submit")&&e[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return n(this,void 0,void 0,(function*(){var e;const t=yield this.getConfig(),n="projectConfig"in t?null===(e=t.projectConfig)||void 0===e?void 0:e.componentsVersion:{};return n||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t;if(this.flowStatus="loading",["ready","error","success"].forEach((e=>this.addEventListener(e,(()=>{this.flowStatus=e})))),yield null===(t=e.init)||void 0===t?void 0:t.call(this),o(this,ir,"f").subscribe(o(this,Qi,"m",wr).bind(this)),o(this,ir,"f").update({isDebug:this.debug}),o(this,Qi,"m",ur).call(this),yield o(this,Qi,"m",fr).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const n=yield this.getConfig();if("isMissingConfig"in n&&n.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:r,stepId:s,token:a,code:l,isPopup:c,exchangeError:d,redirectAuthCallbackUrl:u,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:h,redirectAuthInitiator:g,ssoQueryParams:f}=$o(this.flowId,this.loggerWrapper);window.addEventListener("popstate",o(this,ar,"f").popstate),window.addEventListener("components-context",o(this,ar,"f").componentsContext),o(this,or,"f").subscribe(o(this,Qi,"m",gr).bind(this)),o(this,or,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:s,executionId:r,token:a,code:l,isPopup:c,exchangeError:d,redirectAuthCallbackUrl:u,redirectAuthBackupCallbackUri:p,redirectAuthCodeChallenge:h,redirectAuthInitiator:g},f)),i(this,tr,!0,"f")}))}disconnectedCallback(){o(this,or,"f").unsubscribeAll(),o(this,ir,"f").unsubscribeAll(),o(this,Qi,"m",br).call(this),window.removeEventListener("popstate",o(this,ar,"f").popstate),window.removeEventListener("components-context",o(this,ar,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&o(this,tr,"f")&&t!==n&&er.observedAttributes.includes(e)){o(this,Qi,"m",ur).call(this);const i=null===t;o(this,or,"f").update((({stepId:t,executionId:o})=>{let r=t,s=o;return i||(s=null,r=null,Ro()),{[To(e)]:n,stepId:r,executionId:s}})),o(this,ir,"f").update({isDebug:this.debug})}}}var Sr,Or,Cr,xr,Ar,jr,Er,Ur,Rr,Tr,$r,Lr,Pr,Wr,Nr,Mr,_r,Dr,qr,Fr,Kr,Jr,Vr,Hr,Br,zr,Gr,Zr,Xr,Yr,Qr,es,ts,ns,os,is,rs,ss,as,ls,cs,ds,us,ps,hs,gs,fs,vs;er=Ir,tr=new WeakMap,nr=new WeakMap,or=new WeakMap,ir=new WeakMap,rr=new WeakMap,sr=new WeakMap,ar=new WeakMap,lr=new WeakMap,Qi=new WeakSet,cr=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},dr=function(){o(this,Qi,"m",cr).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},ur=function(){const e=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes"];er.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[To(t)])throw Error(`${t} cannot be empty`)}))},pr=function(){const{stepId:e,executionId:t}=Uo(this.flowId);o(this,or,"f").update({stepId:e,executionId:t})},hr=function(e,t){Kn&&"function"==typeof Kn||this.logger.error("SDK was not loaded properly",Kn,JSON.stringify(Kn));const i=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},er.sdkConfigOverrides),{projectId:e,baseUrl:t});o(this,nr,"f")&&(i.customStorage=o(this,nr,"f")),this.sdk=Kn(i),["start","next"].forEach((e=>{const t=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>n(this,void 0,void 0,(function*(){try{return yield t(...e)}catch(e){return{error:{errorCode:Vn,errorDescription:e.toString()}}}}))}))},gr=function(e,t,i){return n(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:n}=e;if(i("projectId")||i("baseUrl")){if(!t)return;o(this,Qi,"m",hr).call(this,t,n)}o(this,lr,"f").call(this,e)}))},fr=function(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield o(this,Qi,"m",vr).call(this))}))},vr=function(){return n(this,void 0,void 0,(function*(){const e=function({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:o}){const i=new URL(Bn||o||"https://static.descope.com/pages");return i.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(i.pathname,e,n,t),i.toString()}({projectId:this.projectId,filename:"config.json",assetsFolder:"v2-alpha",baseUrl:this.baseStaticUrl});try{return yield function(e,t){return n(this,void 0,void 0,(function*(){const n=yield fetch(e,{cache:"default"});if(!n.ok)throw Error(`Error fetching URL ${e} [${n.status}]`);return{body:yield n[t](),headers:Object.fromEntries(n.headers.entries())}}))}(e,"json"),!0}catch(e){return!1}}))},mr=function(e){i(this,rr,Object.assign(Object.assign({},o(this,rr,"f")),e.detail),"f")},br=function(){var e;null===(e=o(this,sr,"f"))||void 0===e||e.remove(),i(this,sr,null,"f")},wr=function(e){return n(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,sr,document.createElement("descope-debugger"),"f"),Object.assign(o(this,sr,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return ks})),document.body.appendChild(o(this,sr,"f"))):o(this,Qi,"m",br).call(this)}))},yr=function(e,t){var n;e&&this.debug&&(null===(n=o(this,sr,"f"))||void 0===n||n.updateData({title:e,description:t}))},Ir.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.49.2"}};class ms extends Ir{static set sdkConfigOverrides(e){Ir.sdkConfigOverrides=e}static get sdkConfigOverrides(){return Ir.sdkConfigOverrides}constructor(){const e=new Xo({deferredRedirect:!1});super(e.update.bind(e)),Sr.add(this),this.stepState=new Xo({}),Or.set(this,void 0),Cr.set(this,null),xr.set(this,null),Ar.set(this,{visibilitychange:o(this,Sr,"m",jr).bind(this)}),this.bridgeVersion=2,this.nativeCallbacks={},Wr.set(this,!1),this.handleRedirect=e=>{window.location.assign(e)},Mr.set(this,(e=>{const t=()=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e),e&&(this.contentRootElement.innerHTML="")};e&&this.contentRootElement.hasChildNodes()?o(this,Sr,"m",_r).call(this,t):t()})),Dr.set(this,((e,t,r,s,a=!1)=>{const l=[Hn,"E103202"];if(this.flowState.current.action===vo){this.logger.debug("polling - Scheduling polling request");const c=Date.now(),d=a?500:2e3;i(this,Or,setTimeout((()=>n(this,void 0,void 0,(function*(){var n,i;this.logger.debug("polling - Calling next");const u=this.sdk.flow.next(e,t,Io,r,s,{}),p=document.hidden&&!a&&Date.now()-c>d+500;let h;p&&this.logger.debug("polling - The polling seems to be throttled");try{const e=p?1e3:6e3;h=yield Wo(e,u)}catch(n){return this.logger.warn(`polling - The ${p?"throttled fetch":"fetch"} call timed out or was aborted`),void o(this,Dr,"f").call(this,e,t,r,s,p)}if((null===(n=null==h?void 0:h.error)||void 0===n?void 0:n.errorCode)===Vn)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void o(this,Dr,"f").call(this,e,t,r,s);this.logger.debug("polling - Got a response"),(null==h?void 0:h.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(h.error,null,4)),(null===(i=null==h?void 0:h.error)||void 0===i?void 0:i.errorCode)&&l.includes(h.error.errorCode)?this.logger.debug("polling - Stopping polling due to error"):o(this,Dr,"f").call(this,e,t,r,s),o(this,Fr,"f").call(this,h)}))),d),"f")}})),qr.set(this,(()=>{clearTimeout(o(this,Or,"f")),i(this,Or,null,"f")})),Fr.set(this,(e=>{var t,n,r,s,a,l,c,d,u,p,h,g,f;if(!(null==e?void 0:e.ok)){const i=null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url,c=`${null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status} - ${null===(r=null==e?void 0:e.response)||void 0===r?void 0:r.statusText}`;o(this,Sr,"m",is).call(this,"error",(null==e?void 0:e.error)||{errorCode:"J151001",errorDescription:c,errorMessage:i}),this.loggerWrapper.error((null===(s=null==e?void 0:e.error)||void 0===s?void 0:s.errorDescription)||i,(null===(a=null==e?void 0:e.error)||void 0===a?void 0:a.errorMessage)||c);const d=null===(l=null==e?void 0:e.error)||void 0===l?void 0:l.errorCode;return void("E102004"!==d&&d!==Hn||!this.isRestartOnError||o(this,Sr,"m",Pr).call(this))}null===(d=null===(c=e.data)||void 0===c?void 0:c.runnerLogs)||void 0===d||d.forEach((e=>{const{level:t,title:n,log:o}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](n,o):this.loggerWrapper.info(n,o)}));const v=null===(h=null===(p=null===(u=e.data)||void 0===u?void 0:u.screen)||void 0===p?void 0:p.state)||void 0===h?void 0:h.errorText;(null===(g=e.data)||void 0===g?void 0:g.error)?this.loggerWrapper.error(`[${e.data.error.code}]: ${e.data.error.description}`,`${v?`${v} - `:""}${e.data.error.message}`):v&&this.loggerWrapper.error(v);const{status:m,authInfo:b,lastAuth:w,action:y,openInNewTabUrl:k}=e.data;if(y!==vo&&o(this,qr,"f").call(this),"completed"===m){this.storeLastAuthenticatedUser&&vi(w);const t=Object.assign({},b);return e.data.output&&Object.keys(e.data.output).length>0&&(t.flowOutput=e.data.output),void o(this,Sr,"m",is).call(this,"success",t)}this.storeLastAuthenticatedUser&&vi(w,!0),k&&window.open(k,"_blank");const{executionId:I,stepId:S,stepName:O,screen:C,redirect:x,webauthn:A,error:j,samlIdpResponse:E,nativeResponse:U}=e.data,R=Date.now();y!==vo?(this.loggerWrapper.info(`Step "${O||`#${S}`}" is ${m}`,"",{screen:C,status:m,stepId:S,stepName:O,action:y,error:j}),(null===(f=C.state)||void 0===f?void 0:f.clientScripts)&&i(this,xr,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:S,stepName:O,executionId:I,action:y,redirectTo:null==x?void 0:x.url,redirectIsPopup:null==x?void 0:x.isPopup,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==A?void 0:A.transactionId,webauthnOptions:null==A?void 0:A.options,samlIdpResponseUrl:null==E?void 0:E.url,samlIdpResponseSamlResponse:null==E?void 0:E.samlResponse,samlIdpResponseRelayState:null==E?void 0:E.relayState,nativeResponseType:null==U?void 0:U.type,nativePayload:null==U?void 0:U.payload,reqTimestamp:R})):this.flowState.update({action:y,reqTimestamp:R})})),Kr.set(this,Lo((()=>n(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.warn("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.warn("Webauthn start failed",e.message)}}))))),Gr.set(this,null),es.set(this,Do(((e,t)=>n(this,void 0,void 0,(function*(){var n,i;if("true"===e.getAttribute("formnovalidate")||o(this,Sr,"m",Br).call(this)){const r=null==e?void 0:e.getAttribute("id");o(this,Sr,"m",Zr).call(this,e);const s=yield o(this,Sr,"m",zr).call(this),a=(i=e,Array.from((null==i?void 0:i.attributes)||[]).reduce(((e,t)=>{var n;const o=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return o?Object.assign(e,{[o]:t.value}):e}),{}));this.nextRequestStatus.update({isLoading:!0});const l=Object.assign(Object.assign(Object.assign({},a),s),{origin:(null===(n=this.nativeOptions)||void 0===n?void 0:n.origin)||window.location.origin});yield t(r,l),this.nextRequestStatus.update({isLoading:!1}),o(this,Sr,"m",Xr).call(this,s)}}))))),this.flowState=e}nativeResume(e,t){var n,i,r,s,a;const l=JSON.parse(t);if("oauthWeb"===e||"sso"===e){let{exchangeCode:e}=l;if(!e){e=null===(n=new URL(l.url).searchParams)||void 0===n?void 0:n.get(Zn)}null===(r=(i=this.nativeCallbacks).complete)||void 0===r||r.call(i,{exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(l.url),t=e.searchParams.get("t"),n=e.searchParams.get(Gn).split("_").pop();o(this,qr,"f").call(this),this.flowState.update({token:t,stepId:n,action:void 0})}else if("beforeScreen"===e){const{screenResolve:e}=this.nativeCallbacks;this.nativeCallbacks.screenResolve=null;const{override:t}=l;t||(this.nativeCallbacks.screenNext=null),null==e||e(t)}else if("resumeScreen"===e){const{interactionId:e,form:t}=l,{screenNext:n}=this.nativeCallbacks;this.nativeCallbacks.screenNext=null,null==n||n(e,t)}else null===(a=(s=this.nativeCallbacks).complete)||void 0===a||a.call(s,l)}loadSdkScriptsModules(){const e=this.shadowRoot.querySelectorAll("div[data-script-id]");return Array.from(e).map((e=>e.moduleRes)).filter((e=>!!e))}loadSdkScripts(e){if(!(null==e?void 0:e.length))return null;const t=(e,t)=>n=>{this.dispatchEvent(new CustomEvent("components-context",{detail:{[Jo(e.id,e.resultKey)]:n},bubbles:!0,composed:!0})),t(e.id)};this.loggerWrapper.debug(`Preparing to load scripts: ${e.map((e=>e.id)).join(", ")}`);const o=Promise.all(null==e?void 0:e.map((e=>n(this,void 0,void 0,(function*(){var n,o;const i=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(i){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=i;return null===(n=null==t?void 0:t.start)||void 0===n||n.call(t),t}yield this.injectNpmLib("@descope/flow-scripts","1.0.13",`dist/${e.id}.js`);const r=null===(o=globalThis.descope)||void 0===o?void 0:o[e.id];return new Promise(((n,o)=>{try{const o=r(e.initArgs,{baseUrl:this.baseUrl,ref:this},t(e,n),this.loggerWrapper);if(o){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=o,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=o.stop)||void 0===t||t.call(o)}))}}catch(e){o(e)}}))}))))),i=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),5e3)}));return Promise.race([o,i])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.descopeBridge)return this._init();this.lazyInit=this._init}_init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t,n;this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),o(this,Sr,"m",$r).call(this),window.addEventListener("visibilitychange",o(this,Ar,"f").visibilitychange)),yield null===(n=e.init)||void 0===n?void 0:n.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),o(this,qr,"f").call(this),null===(e=o(this,Cr,"f"))||void 0===e||e.abort(),i(this,Cr,null,"f"),window.removeEventListener("visibilitychange",o(this,Ar,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return n(this,void 0,void 0,(function*(){let n;const o=qo(e),i=yield this.getTargetLocales();return i.includes(o.locale)?n=`${t}-${o.locale}.html`:i.includes(o.fallback)&&(n=`${t}-${o.fallback}.html`),n}))}getPageContent(e,t){return n(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield this.fetchStaticResource(t,"text");return e}catch(n){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,n)}try{const{body:t}=yield this.fetchStaticResource(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(e,r,s){return n(this,void 0,void 0,(function*(){var a,l;const{projectId:c,flowId:d,tenant:u,stepId:p,executionId:h,action:g,screenId:f,screenState:v,redirectTo:m,redirectIsPopup:b,redirectUrl:w,token:y,code:k,isPopup:I,exchangeError:S,webauthnTransactionId:O,webauthnOptions:C,redirectAuthCodeChallenge:x,redirectAuthCallbackUrl:A,redirectAuthBackupCallbackUri:j,redirectAuthInitiator:E,locale:U,samlIdpResponseUrl:R,samlIdpResponseSamlResponse:T,samlIdpResponseRelayState:$,nativeResponseType:L,nativePayload:P,reqTimestamp:W}=e,N=t(e,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","redirectIsPopup","redirectUrl","token","code","isPopup","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let M,_,D;const q=(()=>{const e=pi(hi);if(!e){const e=Math.floor(100*Math.random()+1);return ui(hi,e.toString()),e}return Number(e)})(),{outboundAppId:F}=this,{outboundAppScopes:K}=this,J=this.sdk.getLastUserLoginId(),V=yield this.getFlowConfig(),H=yield this.getProjectConfig(),B=Object.entries(H.flows||{}).reduce(((e,[t,n])=>(e[t]=n.version,e)),{}),z=A&&x?{callbackUrl:A,codeChallenge:x,backupCallbackUri:j}:void 0,G=this.nativeOptions?{platform:this.nativeOptions.platform,bridgeVersion:this.nativeOptions.bridgeVersion,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let Z={};if(!h){const e=[...V.clientScripts||[],...V.sdkScripts||[]];if(V.conditions){let t=[];({startScreenId:M,conditionInteractionId:D,startScreenName:_,clientScripts:t,componentsConfig:Z}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n,predicate:o})=>{var i;if("ELSE"===t)return!0;const r=null===(i=gi[t])||void 0===i?void 0:i[n];return!!(null==r?void 0:r(e,o))}));return n?{startScreenId:n.met.screenId,startScreenName:n.met.screenName,conditionInteractionId:n.met.interactionId,clientScripts:n.met.clientScripts,componentsConfig:n.met.componentsConfig}:{}})({loginId:J,code:k,token:y,abTestingKey:q,lastAuth:fi(J)},V.conditions)),e.push(...t||[])}else V.condition?({startScreenId:M,conditionInteractionId:D}=((e,t)=>{var n;const o=null===(n=gi[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const i=o(t,e.predicate)?e.met:e.unmet;return{startScreenId:null==i?void 0:i.screenId,startScreenName:null==i?void 0:i.screenName,conditionInteractionId:null==i?void 0:i.interactionId}})(V.condition,{loginId:J,code:k,token:y,abTestingKey:q,lastAuth:fi(J)})):(_=V.startScreenName,M=V.startScreenId);if(i(this,xr,this.loadSdkScripts(e),"f"),V.fingerprintEnabled&&V.fingerprintKey?yield cn(V.fingerprintKey,this.baseUrl):qt(an),!No(M,N)){const e=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:z},N),{client:this.client}),w&&{redirectUrl:w}),{lastAuth:fi(J),abTestingKey:q,locale:qo(U).locale,nativeOptions:G,outboundAppId:F,outboundAppScopes:K}),D,"",H.componentsVersion,B,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),k?{exchangeCode:k,idpInitiated:!0}:{}),N.descopeIdpInitiated&&{idpInitiated:!0}),y?{token:y}:{}),N.oidcLoginHint?{externalId:N.oidcLoginHint}:{}));return o(this,Fr,"f").call(this,e),void("completed"!==(null===(a=null==e?void 0:e.data)||void 0===a?void 0:a.status)&&this.flowState.update({code:void 0,token:void 0}))}}if(this.loggerWrapper.debug("Before popup postmessage send",JSON.stringify({isPopup:I,code:k,exchangeError:S,isCodeChanged:s("code"),isExchangeErrorChanged:s("exchangeError")})),I&&(s("code")&&k||s("exchangeError")&&S))return void o(this,Sr,"m",rs).call(this,h,k,S);if(h&&(s("token")&&y||s("code")&&k||s("exchangeError")&&S)){const e=yield this.sdk.flow.next(h,p,ko,V.version,H.componentsVersion,{token:y,exchangeCode:k,exchangeError:S});return o(this,Fr,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===yo&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>s(e)))){if(!R||!T)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,o)=>{const i=document.createElement("form");i.method="POST",i.action=e,i.innerHTML=`\n <input type="hidden" role="saml-response" name="SAMLResponse" value="${t}" />\n <input type="hidden" role="saml-relay-state" name="RelayState" value="${n}" />\n <input style="display: none;" id="SAMLSubmitButton" type="submit" value="Continue" />\n `,document.body.appendChild(i),o(i)})(R,T,$||"",Mo)}if(g===fo&&(s("redirectTo")||s("deferredRedirect"))){if(!m)return void this.loggerWrapper.error("Did not get redirect url");if("no-op"===m)return;if("android"===E&&document.hidden)return void this.flowState.update({deferredRedirect:!0});if(this.loggerWrapper.debug(`Redirect is popup ${b}`),b){this.loggerWrapper.debug("Opening redirect in popup");const e=Vo(m,"?",598,700),t=this.shouldUsePopupPostMessage();t&&(e.name=`descope-wc|${window.location.origin}`),this.loggerWrapper.debug("Popup communication method: "+(t?"postMessage":"BroadcastChannel"));const n=e=>{this.loggerWrapper.debug("Received popup message",JSON.stringify(e.data));const n=t?this.popupOrigin:window.location.origin;if(e.origin!==n)return void this.loggerWrapper.debug(`Ignoring message from unexpected origin. received: "${e.origin}", expected: "${n}"`);const{action:o,data:i}=e.data||{};"code"===o&&this.flowState.update({code:i.code,exchangeError:i.exchangeError})};let i;this.loggerWrapper.debug("Starting popup closed detection");const r=setInterval((()=>{e.closed&&(this.loggerWrapper.debug("Popup closed, dispatching popupclosed event"),clearInterval(r),o(this,Sr,"m",is).call(this,"popupclosed",{}),this.loggerWrapper.debug("Cleaning up popup listeners"),null==i||i())}),1e3);if(t)window.addEventListener("message",n),i=()=>{this.loggerWrapper.debug("Cleaning up popup postMessage listener"),window.removeEventListener("message",n)};else{this.loggerWrapper.debug("Creating broadcast channel");const e=new BroadcastChannel(h);e.onmessage=n,i=()=>{this.loggerWrapper.debug("Closing channel"),e.close()}}}else this.handleRedirect(m),this.flowState.update({redirectTo:"no-op"}),o(this,Sr,"m",is).call(this,"popupclosed",{});return}if(g===mo||g===bo){if(!O||!C)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(l=o(this,Cr,"f"))||void 0===l||l.abort(),i(this,Cr,null,"f");try{e=g===mo?yield this.sdk.webauthn.helpers.create(C):yield this.sdk.webauthn.helpers.get(C)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const n=yield this.sdk.flow.next(h,p,ko,V.version,H.componentsVersion,{transactionId:O,response:e,failure:t});o(this,Fr,"f").call(this,n)}if(g===wo)return this.nativeCallbacks.complete=e=>n(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(h,p,ko,V.version,H.componentsVersion,e);o(this,Fr,"f").call(this,t)})),void o(this,Sr,"m",Rr).call(this,L,P);if(s("action")&&o(this,Dr,"f").call(this,h,p,V.version,H.componentsVersion),!f&&!M)return void this.loggerWrapper.warn("No screen was found to show");const X=M||f,Y=yield this.getHtmlFilenameWithLocale(U,X),{oidcLoginHint:Q,oidcPrompt:ee,oidcErrorRedirectUri:te,oidcResource:ne,samlIdpUsername:oe}=N,ie={direction:Eo(p,r.stepId),screenState:Object.assign(Object.assign({},v),{form:Object.assign(Object.assign({},this.formConfigValues),null==v?void 0:v.form),lastAuth:{loginId:J,name:this.sdk.getLastUserDisplayName()||J},componentsConfig:Object.assign(Object.assign(Object.assign({},V.componentsConfig),Z),null==v?void 0:v.componentsConfig)}),htmlFilename:`${X}.html`,htmlLocaleFilename:Y,screenId:X,stepName:e.stepName||_,samlIdpUsername:oe,oidcLoginHint:Q,oidcPrompt:ee,oidcErrorRedirectUri:te,oidcResource:ne,action:g},re=fi(J);No(M,N)?ie.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=(null==V?void 0:V.clientScripts)||[];yield o(this,Sr,"m",ts).call(this,n);const i=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:z},N),{lastAuth:re,preview:this.preview,abTestingKey:q,client:this.client}),w&&{redirectUrl:w}),{locale:qo(U).locale,nativeOptions:G,outboundAppId:F,outboundAppScopes:K}),D,e,H.componentsVersion,B,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),this.getComponentsContext()),Ko(t)),k&&{exchangeCode:k,idpInitiated:!0}),N.descopeIdpInitiated&&{idpInitiated:!0}),y&&{token:y}));return o(this,Fr,"f").call(this,i),i})):(s("projectId")||s("baseUrl")||s("executionId")||s("stepId"))&&(ie.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=(null==v?void 0:v.clientScripts)||[];yield o(this,Sr,"m",ts).call(this,n);const i=yield this.sdk.flow.next(h,p,e,V.version,H.componentsVersion,Object.assign(Object.assign({},this.getComponentsContext()),Ko(t)));return o(this,Fr,"f").call(this,i),i}))),this.loggerWrapper.debug("Got a screen with id",ie.screenId),yield o(this,Sr,"m",Nr).call(this,ie),this.stepState.update(ie)}))}onStepChange(e,t){return n(this,void 0,void 0,(function*(){var i,r;const{htmlFilename:s,htmlLocaleFilename:a,direction:l,next:c,screenState:d}=e;this.loggerWrapper.debug("Rendering a flow screen");const u=document.createElement("template");u.innerHTML=yield this.getPageContent(s,a);const p=u.content.cloneNode(!0),h=this.loadDescopeUiComponents(u);this.sdk.webauthn.helpers.isSupported()?yield o(this,Sr,"m",Vr).call(this,p,c):p.querySelectorAll(`descope-button[${go}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(i=d.form)||void 0===i?void 0:i.loginId)||(null===(r=d.form)||void 0===r?void 0:r.email)||(d.form||(d.form={}),d.form.loginId=e.samlIdpUsername,d.form.email=e.samlIdpUsername),ai(p,d,d.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:g}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(p,g);const f=()=>n(this,void 0,void 0,(function*(){var n,i;yield h;const r=this.contentRootElement;var s,a;s=r,a=null===(n=null==d?void 0:d.totp)||void 0===n?void 0:n.image,si(s,"descope-totp-image",a),((e,t)=>{si(e,"descope-notp-image",t)})(r,null===(i=null==d?void 0:d.notp)||void 0===i?void 0:i.image),((e,t,n,o)=>{n&&Object.keys(n).forEach((i=>{if(!t.querySelector(i))return void o.debug(`Skipping css vars for component "${i}"`,`Got css vars for component ${i} but Could not find it on next page`);const r=customElements.get(i);r?Object.keys(n[i]).forEach((t=>{var s;const a=n[i],l=null===(s=null==r?void 0:r.cssVarList)||void 0===s?void 0:s[t];if(!l)return void o.info(`Could not find css variable name for ${t} in ${i}`,"Check if the css variable is defined in the component");const c=a[t];e.style.setProperty(l,c)})):o.debug(`Could not find component class for ${i}`,"Check if the component is registered")}))})(r,p,d.cssVars,this.loggerWrapper),r.replaceChildren(p);const l=!t.htmlFilename;setTimeout((()=>{o(this,Sr,"m",Yr).call(this),this.validateOnBlur&&(e=>{e.querySelectorAll("*[name]").forEach((t=>{t.addEventListener("blur",(()=>{var n;const o=()=>{var e;const n=t.focus;t.focus=()=>{},null===(e=t.reportValidity)||void 0===e||e.call(t),setTimeout((()=>{t.focus=n}))};if("true"===t.getAttribute("invalid")||(null===(n=t.value)||void 0===n?void 0:n.length))return void o();const i={timer:void 0},r=e=>{"true"===e.target.getAttribute("formnovalidate")&&(clearTimeout(i.timer),i.timer=void 0)};i.timer=setTimeout((()=>{e.removeEventListener("click",r),o(),i.timer=void 0}),150),e.addEventListener("click",r,{once:!0})}))}))})(r),((e,t)=>{ti(e,null==t?void 0:t.inputs),ti(e,null==t?void 0:t.form)})(r,d),o(this,Sr,"m",Hr).call(this,{isFirstScreen:l,isCustomScreen:!1,stepName:e.stepName}),Po(r,this.autoFocus,l)})),o(this,Sr,"m",os).call(this,c);r.querySelector(`[${go}="polling"]`)&&c(Io,{})}));l?o(this,Sr,"m",_r).call(this,f):f()}))}getInputs(){return Array.from(this.shadowRoot.querySelectorAll(`*:not(slot)[name]:not([${Yn}])`))}shouldUsePopupPostMessage(){if(!this.popupOrigin)return!1;try{new URL(this.popupOrigin)}catch(e){return!1}return!0}}Or=new WeakMap,Cr=new WeakMap,xr=new WeakMap,Ar=new WeakMap,Wr=new WeakMap,Mr=new WeakMap,Dr=new WeakMap,qr=new WeakMap,Fr=new WeakMap,Kr=new WeakMap,Gr=new WeakMap,es=new WeakMap,Sr=new WeakSet,jr=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},Er=function(e,t,i){return n(this,void 0,void 0,(function*(){var n;return(null===(n=this.nativeOptions)||void 0===n?void 0:n.bridgeVersion)>=2&&new Promise((n=>{this.nativeCallbacks.screenNext=i,this.nativeCallbacks.screenResolve=n,o(this,Sr,"m",Rr).call(this,"beforeScreen",{screen:e,context:t})}))}))},Ur=function(e){var t;(null===(t=this.nativeOptions)||void 0===t?void 0:t.bridgeVersion)>=2&&o(this,Sr,"m",Rr).call(this,"afterScreen",{screen:e})},Rr=function(e,t){o(this,Sr,"m",is).call(this,"bridge",{type:e,payload:t})},Tr=function({errorText:e,errorType:t}){const n=()=>{var n;let o=e;try{o=(null===(n=this.errorTransformer)||void 0===n?void 0:n.call(this,{text:e,type:t}))||e}catch(e){this.loggerWrapper.error("Error transforming error message",e.message)}((e,t,n="")=>{e.querySelectorAll(`[${go}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(this.contentRootElement,"error-message",o)};this.addEventListener("screen-updated",n,{once:!0}),n()},$r=function(){var e,n,i;null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this),(e=>{var n=e.screenState,o=t(void 0===n?{}:n,["errorText","errorType"]),i=t(e,["screenState"]);return Object.assign(Object.assign({},i),{screenState:o})})),null===(n=this.stepState)||void 0===n||n.subscribe(o(this,Sr,"m",Tr).bind(this),(e=>{var t,n;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(n=null==e?void 0:e.screenState)||void 0===n?void 0:n.errorType}}),{forceUpdate:!0}),null===(i=this.stepState)||void 0===i||i.subscribe(o(this,Sr,"m",Lr).bind(this),(e=>{var t,n;return{errorText:null===(t=null==e?void 0:e.screenState)||void 0===t?void 0:t.errorText,errorType:null===(n=null==e?void 0:e.screenState)||void 0===n?void 0:n.errorType}}),{forceUpdate:!0})},Lr=function({errorText:e,errorType:t}){(t||e)&&(this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((e=>{e.shadowRoot.querySelectorAll("descope-text-field[data-id]").forEach((e=>{e.value=""}))})),Po(this.contentRootElement,this.autoFocus,!1))},Pr=function(){return n(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Trying to restart the flow");const e=yield this.getComponentsVersion();this.reset();e===(yield this.getComponentsVersion())?(this.loggerWrapper.debug("Components version was not changed, restarting flow"),this.flowState.update({stepId:null,executionId:null})):this.loggerWrapper.error("Components version mismatch, please reload the page")}))},Nr=function(e){return n(this,void 0,void 0,(function*(){var n;const r=Object.assign(Object.assign({},this.stepState.current),e),{next:s,stepName:a}=r,l=t(r,["next","stepName"]),c=Fo(l);let d=yield o(this,Sr,"m",Er).call(this,a,c,s);d||(d=Boolean(yield null===(n=this.onScreenUpdate)||void 0===n?void 0:n.call(this,a,c,s,this)));const u=!this.stepState.current.htmlFilename;if(o(this,Mr,"f").call(this,d),o(this,Wr,"f")!==d){const[e,t]=["flow","custom"].sort((()=>d?-1:1));this.loggerWrapper.debug(`Switching from ${t} screen to ${e} screen`),i(this,Wr,d,"f"),d?this.stepState.unsubscribeAll():o(this,Sr,"m",$r).call(this)}d?(this.loggerWrapper.debug("Showing a custom screen"),o(this,Sr,"m",Hr).call(this,{isFirstScreen:u,isCustomScreen:d,stepName:e.stepName}),this.disableKeyPressHandler()):this.handleKeyPress(),this.stepState.forceUpdate=d}))},_r=function(e){this.contentRootElement.addEventListener("transitionend",(()=>{this.loggerWrapper.debug("page switch transition end"),this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0}),this.loggerWrapper.debug("page switch transition start"),this.contentRootElement.classList.add("fade-out")},Jr=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const n=`user-${t}`;e.setAttribute("name",n),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:n)}))}},Vr=function(e,t){return n(this,void 0,void 0,(function*(){var r;null===(r=o(this,Cr,"f"))||void 0===r||r.abort();const s=e.querySelector('*[autocomplete="webauthn"]');if(s&&(yield li())){const{options:e,transactionId:r}=(yield o(this,Kr,"f").call(this))||{};e&&r&&(o(this,Sr,"m",Jr).call(this,s),i(this,Cr,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(e,o(this,Cr,"f")).then((e=>n(this,void 0,void 0,(function*(){t(s.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},Hr=function({isFirstScreen:e,isCustomScreen:t,stepName:n}){e&&o(this,Sr,"m",is).call(this,"ready",{}),t||o(this,Sr,"m",Ur).call(this,n),o(this,Sr,"m",is).call(this,"page-updated",{screenName:n}),o(this,Sr,"m",is).call(this,"screen-updated",{screenName:n})},Br=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var n,o;"slot"!==t.localName&&(null===(n=t.reportValidity)||void 0===n||n.call(t),e&&(e=null===(o=t.checkValidity)||void 0===o?void 0:o.call(t)))})),e},zr=function(){return n(this,void 0,void 0,(function*(){const e=this.getInputs();return(yield Promise.all(e.map((e=>n(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Zr=function(e){const t=Array.from(this.contentRootElement.querySelectorAll(':not([disabled]), [disabled="false"]')).filter((t=>t!==e)),r=()=>n(this,void 0,void 0,(function*(){this.loggerWrapper.debug("Restoring components state"),this.removeEventListener("popupclosed",r),e.removeAttribute("loading"),t.forEach((e=>{e.removeAttribute("disabled")}));const n=yield this.getFlowConfig(),o=[...n.clientScripts||[],...n.sdkScripts||[]];this.loadSdkScripts(o)})),s=()=>{var e;window.removeEventListener("pageshow",o(this,Gr,"f")),i(this,Gr,(e=>{e.persisted&&(this.logger.debug("Page was loaded from cache, restoring components state"),r())}),"f"),window.addEventListener("pageshow",o(this,Gr,"f"),{once:!0});const t=null===(e=this.stepState)||void 0===e?void 0:e.subscribe(((e,n)=>{e===n&&r(),this.removeEventListener("popupclosed",r),this.stepState.unsubscribe(t)}),(e=>e.screenId),{forceUpdate:!0})},a=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?(this.addEventListener("popupclosed",r,{once:!0}),e.setAttribute("loading","true"),t.forEach((e=>e.setAttribute("disabled","true")))):(this.nextRequestStatus.unsubscribe(a),s())}))},Xr=function(e={}){var t,n;const o=_o(e,["externalId","email","phone"]),i=_o(e,["newPassword","password"]);if(o&&i)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:o,password:i});null===(n=null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.store)||void 0===n||n.call(t,e)}catch(e){this.loggerWrapper.error("Could not store credentials",e.message)}},Yr=function(){document.querySelectorAll('[data-hidden-input="true"]').forEach((e=>e.remove()));this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((e=>o(this,Sr,"m",Qr).call(this,e)))},Qr=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const n=t.getAttribute("slot"),o=`input-${e.id}-${n}`,i=document.createElement("slot");i.setAttribute("name",o),i.setAttribute("slot",n),e.appendChild(i),t.setAttribute("slot",o),this.appendChild(t)}))},ts=function(e){return n(this,void 0,void 0,(function*(){if(o(this,xr,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield o(this,xr,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const t=this.loadSdkScriptsModules(),n=e.map((e=>e.id));for(const e of t)if(n.includes(e.id))try{if("function"==typeof e.present){(yield e.present())||this.loggerWrapper.debug(`Sdk script ${e.id} was cancelled`)}}catch(t){this.loggerWrapper.error(`Failed to present ${e.id} script module`,t.message)}let i=[];for(const e of t)"function"==typeof e.refresh&&i.push(e.refresh());if(i.length>0)try{yield Wo(5e3,Promise.all(i),null)}catch(e){this.loggerWrapper.error("Failed to refresh script module",e.message)}}))},ns=function(e){this.contentRootElement.querySelectorAll('descope-passcode[data-auto-submit="true"]').forEach((t=>{t.addEventListener("input",(()=>{var n;(null===(n=t.checkValidity)||void 0===n?void 0:n.call(t))&&o(this,es,"f").call(this,t,e)}))}))},os=function(e){this.contentRootElement.querySelectorAll(`descope-button:not([${Qn}]), [data-type="button"]:not([${Qn}]`).forEach((t=>{t.onclick=()=>{o(this,es,"f").call(this,t,e)}})),o(this,Sr,"m",ns).call(this,e),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${Yn}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},is=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},rs=function(e,t,n){var o;const[i,r]=(null===(o=window.name)||void 0===o?void 0:o.split("|"))||[],s={data:{code:t,exchangeError:n},action:"code"};if("descope-wc"===i&&r){this.loggerWrapper.debug("Using postMessage fallback to notify opener in origin",r);try{window.opener.postMessage(s,r)}catch(e){this.loggerWrapper.error("Failed to send postMessage fallback (likely COOP isolation)",null==e?void 0:e.message)}}else{this.loggerWrapper.debug("Creating popup channel",e);const t=new BroadcastChannel(e);t.postMessage(s),t.close()}try{window.close()}catch(e){}},customElements.get("descope-wc")?console.log("descope-wc is already defined"):customElements.define("descope-wc",ms);const bs=document.createElement("template");bs.innerHTML='\n<div class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n';const ws=mi(Vi)(HTMLElement);class ys extends ws{constructor(){super(),ss.add(this),as.set(this,new Xo({messages:[]})),ls.set(this,void 0),cs.set(this,void 0),ds.set(this,void 0),us.set(this,{resize:o(this,ss,"m",vs).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(bs.content.cloneNode(!0)),i(this,ls,this.shadowRoot.querySelector(".debugger"),"f"),i(this,cs,o(this,ls,"f").querySelector(".content"),"f"),i(this,ds,o(this,ls,"f").querySelector(".header"),"f"),o(this,ss,"m",ps).call(this)}updateData(e){o(this,as,"f").update((t=>({messages:t.messages.concat(e)})))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return n(this,void 0,void 0,(function*(){var t,n;null===(t=e.init)||void 0===t||t.call(this),((e,t,n)=>{let o=0,i=0,r=0,s=0;function a(t){t.preventDefault(),o=r-t.clientX,i=s-t.clientY,r=t.clientX,s=t.clientY;const[a,l]=ci(e,e.offsetLeft-o,e.offsetTop-i,n);e.style.top=`${l}px`,e.style.left=`${a}px`}function l(){document.onmouseup=null,document.onmousemove=null}function c(e){e.preventDefault(),r=e.clientX,s=e.clientY,document.onmouseup=l,document.onmousemove=a}t?t.onmousedown=c:e.onmousedown=c})(o(this,ls,"f"),o(this,ds,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",o(this,us,"f").resize),(n=o(this,ls,"f")).onmousemove=e=>{(e.target.w&&e.target.w!==e.target.offsetWidth||e.target.h&&e.target.h!==e.target.offsetHeight)&&n.onresize(e),e.target.w=e.target.offsetWidth,e.target.h=e.target.offsetHeight},o(this,ls,"f").onresize=o(this,ss,"m",fs).bind(this),o(this,as,"f").subscribe(o(this,ss,"m",hs).bind(this))}))}disconnectedCallback(){o(this,as,"f").unsubscribeAll(),window.removeEventListener("resize",o(this,us,"f").resize)}}as=new WeakMap,ls=new WeakMap,cs=new WeakMap,ds=new WeakMap,us=new WeakMap,ss=new WeakSet,ps=function(){this.injectStyle('\n .debugger {\n all: initial;\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n'),o(this,ls,"f").style.top="32px",o(this,ls,"f").style.left=window.innerWidth-300-32+"px"},hs=function(e){o(this,ss,"m",gs).call(this,e),o(this,ss,"m",fs).call(this)},gs=function(e){o(this,cs,"f").innerHTML=e.messages.map((e=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${e.title}\n </div>\n <div class="msg_desc">\n ${e.description}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},fs=function(){o(this,cs,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,o=t.clientHeight>20;n||o?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},vs=function(){const[e,t]=ci(o(this,ls,"f"),Number.parseInt(o(this,ls,"f").style.left,10),Number.parseInt(o(this,ls,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});o(this,ls,"f").style.top=`${t}px`,o(this,ls,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",ys);var ks=Object.freeze({__proto__:null,default:ys})}();