@descope/web-component 3.40.2 → 3.40.4
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/cjs/debugger-wc.js +1 -1
- package/dist/cjs/debugger-wc.js.map +1 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/descope-wc/BaseDescopeWc.js.map +1 -1
- package/dist/esm/debugger-wc.js +1 -1
- package/dist/esm/debugger-wc.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js.map +1 -1
- package/dist/index.js +2 -2
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}function n(e,t,n,i){return new(n||(n=Promise))((function(o,r){function s(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((i=i.apply(e,t||[])).next())}))}function i(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function o(e,t,n,i,o){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?o.call(e,n):o?o.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,i=e.split(".")[n];if("string"!=typeof i)throw new r(`Invalid token specified: missing part #${n+1}`);let o;try{o=s(i)}catch(e){throw new r(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(o)}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"}},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",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,h="dct",p=()=>{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},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}};let g;const f=()=>{if(g)return g;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 g=`${t}-${n}`,g};var v;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT",e.patch="PATCH"}(v||(v={}));const m=({path:e,baseUrl:t,queryParams:n,projectId:i})=>{const o=i.slice(1,-27);t=t.replace(c,o?o+".":"");let r=e?`${t.replace(/\/$/,"")}/${null==e?void 0:e.replace(/^\//,"")}`:t;if(n){const e=Object.keys(n);e.forEach(((t,i)=>{r=`${r}${0===i?"?":""}${t}=${encodeURIComponent(n[t])}${i===e.length-1?"":"&"}`}))}return r},b=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,i])=>(e[n]=i,e)),e),e}),{})),w={"Content-Type":"application/json"},y=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},k=e=>{const t={"x-descope-sdk-session-id":f(),"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.40.0"};return e&&(t["x-descope-refresh-cookie-name"]=e),t},I=e=>{try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e},S=({baseUrl:e,projectId:t,baseConfig:n,refreshCookieName:i,logger:o,hooks:r,cookiePolicy:s,fetch:a})=>{const l=((e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),i=await n.text();return n.text=()=>Promise.resolve(i),n.json=()=>Promise.resolve(JSON.parse(i)),n.clone=()=>n,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=>p().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const i=await n(...t);return e[i.ok?"log":"error"](await(async e=>{const t=await e.text();return p().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(i)),i}:n})(o,a),c=async o=>{var a;const c=(null==r?void 0:r.beforeRequest)?r.beforeRequest(o):o,{path:d,body:u,headers:h,queryParams:p,method:g,token:f}=c,v=(e=>void 0===e?void 0:JSON.stringify(e))(u),S={headers:b(y(t,f),k(i),(null==n?void 0:n.baseHeaders)||{},I(v)?w:{},h),method:g,body:v};null!==s&&(S.credentials=s||"include");const C=await l(m({path:d,baseUrl:e,queryParams:p,projectId:t}),S);if((null==r?void 0:r.afterRequest)&&await r.afterRequest(o,null==C?void 0:C.clone()),null==r?void 0:r.transformResponse){const e=await C.json(),t=((null===(a=C.headers)||void 0===a?void 0:a.get("set-cookie"))||"").split(";").reduce(((e,t)=>{const[n,i]=t.split("=");return Object.assign(Object.assign({},e),{[n.trim()]:i})}),{}),n=Object.assign(Object.assign({},C),{json:()=>Promise.resolve(e),cookies:t});return n.clone=()=>n,r.transformResponse(n)}return C};return{get:(e,{headers:t,queryParams:n,token:i}={})=>c({path:e,headers:t,queryParams:n,body:void 0,method:v.get,token:i}),post:(e,t,{headers:n,queryParams:i,token:o}={})=>c({path:e,headers:n,queryParams:i,body:t,method:v.post,token:o}),patch:(e,t,{headers:n,queryParams:i,token:o}={})=>c({path:e,headers:n,queryParams:i,body:t,method:v.patch,token:o}),put:(e,t,{headers:n,queryParams:i,token:o}={})=>c({path:e,headers:n,queryParams:i,body:t,method:v.put,token:o}),delete:(e,{headers:t,queryParams:n,token:i}={})=>c({path:e,headers:t,queryParams:n,body:void 0,method:v.delete,token:i}),hooks:r,buildUrl:(n,i)=>m({projectId:t,baseUrl:e,path:n,queryParams:i})}};var C=429;function O(e,t,n){var i;let o=x(e);if(t){if(!(null==o?void 0:o.tenants)&&(null==o?void 0:o[h])===t)return(null==o?void 0:o[n])||[];o=null===(i=null==o?void 0:o.tenants)||void 0===i?void 0:i[t]}const r=null==o?void 0:o[n];return Array.isArray(r)?r:[]}function x(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return a(e)}function j(e){const{exp:t}=x(e);return(new Date).getTime()/1e3>t}function A(e){let t=x(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function U(e,t){return O(e,t,"permissions")}function E(e,t){return O(e,t,"roles")}const T=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function R(e,t){var n;const i=await e,o={code:i.status,ok:i.ok,response:i},r=await i.clone().json();return i.ok?o.data=r:(o.error=r,i.status===C&&Object.assign(o.error,{retryAfter:Number.parseInt(null===(n=i.headers)||void 0===n?void 0:n.get("retry-after"))||0})),o}function L(e){var t;return(null===(t=x(e))||void 0===t?void 0:t[h])||""}const _=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),$=(e,t)=>(n=t)=>t=>{const i=e.filter((e=>e(t)));return!(i.length<e.length)&&(n?n.replace("{val}",t):i.join(" OR "))},P=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),D=e=>t=>e.test(t),M=D(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),N=D(/^\+[1-9]{1}[0-9]{3,14}$/),W=_(M,'"{val}" is not a valid email'),q=_(N,'"{val}" is not a valid phone number'),F=_((e=>e.length>=1),"Minimum length is 1");const B=_((e=>"string"==typeof e),"Input is not a string"),V=_((e=>Array.isArray(e)),"Input is not an array"),K=_((e=>"boolean"==typeof e),"Input is not a boolean"),H=_((e=>void 0===e),"Input is defined"),G=$([B(),H()],"Input is not a string or undefined"),J=$([V(),K()],"Input is not an array or boolean"),z=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>P(...e).validate(n[t]))),t(...n)),X=e=>[B(`"${e}" must be a string`)],Q=e=>[G(`"${e}" must be string or undefined`)],Z=e=>[B(`"${e}" must be a string`),F(`"${e}" must not be empty`)],Y=e=>[B(`"${e}" must be a string`),W()],ee=e=>[B(`"${e}" must be a string`),q()],te=z(Z("accessKey")),ne=e=>({exchange:te(((t,n)=>R(e.post(l.accessKey.exchange,{loginOptions:n},{token:t}))))}),ie=(e,t,n)=>(t.forEach((t=>{const i=t.split(".");let o=i.shift(),r=e;for(;i.length>0;){if(r=r[o],!o||!r)throw Error(`Invalid path "${t}", "${o}" is missing or has no value`);o=i.shift()}if("function"!=typeof r[o])throw Error(`"${t}" is not a function`);const s=r[o];r[o]=n(s)})),e),oe=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||u,u)});var re,se;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(re||(re={})),function(e){e.email="email"}(se||(se={}));const ae=Object.assign(Object.assign({},re),se);var le;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(le||(le={}));const ce=Z("loginId"),de=z(Z("token")),ue=z(ce),he=z(Z("pendingRef")),pe=z(ce,Y("email")),ge=e=>({verify:de((t=>R(e.post(l.enchantedLink.verify,{token:t})))),signIn:ue(((t,n,i,o)=>R(e.post(T(l.enchantedLink.signIn,ae.email),{loginId:t,URI:n,loginOptions:i},{token:o})))),signUpOrIn:ue(((t,n,i)=>R(e.post(T(l.enchantedLink.signUpOrIn,ae.email),{loginId:t,URI:n,loginOptions:i})))),signUp:ue(((t,n,i,o)=>R(e.post(T(l.enchantedLink.signUp,ae.email),{loginId:t,URI:n,user:i,loginOptions:o})))),waitForSession:he(((t,n)=>new Promise((i=>{const{pollingIntervalMs:o,timeoutMs:r}=oe(n);let s;const a=setInterval((async()=>{const n=await e.post(l.enchantedLink.session,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),i(R(Promise.resolve(n))))}),o);s=setTimeout((()=>{i({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)})))),update:{email:pe(((t,n,i,o,r)=>R(e.post(l.enchantedLink.update.email,Object.assign({loginId:t,email:n,URI:i},r),{token:o}))))}}),fe=z(Z("flowId")),ve=z(Z("executionId"),Z("stepId"),Z("interactionId")),me=e=>({start:fe(((t,n,i,o,r,s,a)=>R(e.post(l.flow.start,{flowId:t,options:n,conditionInteractionId:i,interactionId:o,componentsVersion:r,flowVersions:s,input:a})))),next:ve(((t,n,i,o,r,s)=>R(e.post(l.flow.next,{executionId:t,stepId:n,interactionId:i,version:o,componentsVersion:r,input:s}))))}),be=Z("loginId"),we=z(Z("token")),ye=z(be),ke=z(be,ee("phone")),Ie=z(be,Y("email")),Se=Object.keys(ae).filter((e=>e!==re.voice)),Ce=e=>({verify:we((t=>R(e.post(l.magicLink.verify,{token:t})))),signIn:Se.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ye(((t,i,o,r)=>R(e.post(T(l.magicLink.signIn,n),{loginId:t,URI:i,loginOptions:o},{token:r}))))})),{}),signUp:Se.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ye(((t,i,o,r)=>R(e.post(T(l.magicLink.signUp,n),{loginId:t,URI:i,user:o,loginOptions:r}))))})),{}),signUpOrIn:Se.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ye(((t,i,o)=>R(e.post(T(l.magicLink.signUpOrIn,n),{loginId:t,URI:i,loginOptions:o}))))})),{}),update:{email:Ie(((t,n,i,o,r)=>R(e.post(l.magicLink.update.email,Object.assign({loginId:t,email:n,URI:i},r),{token:o})))),phone:Object.keys(re).filter((e=>e!==re.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ke(((t,i,o,r,s)=>R(e.post(T(l.magicLink.update.phone,n),Object.assign({loginId:t,phone:i,URI:o},s),{token:r}))))})),{})}});var Oe;!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"}(Oe||(Oe={}));const xe=z(Z("code")),je=e=>({start:Object.assign(((t,n,i,o)=>R(e.post(l.oauth.start,i||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:o}))),Object.keys(Oe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,i,o)=>R(e.post(l.oauth.start,i||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:o}))})),{})),exchange:xe((t=>R(e.post(l.oauth.exchange,{code:t})))),startNative:(t,n,i)=>R(e.post(l.oauth.startNative,{provider:t,loginOptions:n,implicit:i})),finishNative:(t,n,i,o,r)=>R(e.post(l.oauth.finishNative,{provider:t,stateId:n,user:i,code:o,idToken:r})),getOneTapClientId:t=>R(e.get(l.oauth.oneTap.getOneTapClientId.replace("{provider}",t))),verifyOneTapIDToken:(t,n,i,o)=>R(e.post(l.oauth.oneTap.verifyOneTapIDToken,{provider:t,idToken:n,nonce:i,loginOptions:o})),exchangeOneTapIDToken:(t,n,i,o)=>R(e.post(l.oauth.oneTap.exchangeOneTapIDToken,{provider:t,idToken:n,nonce:i,loginOptions:o}))}),Ae=Z("loginId"),Ue=z(Ae,Z("code")),Ee=z(Ae),Te=z(Ae,ee("phone")),Re=z(Ae,Y("email")),Le=e=>({verify:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ue(((t,i)=>R(e.post(T(l.otp.verify,n),{code:i,loginId:t}))))})),{}),signIn:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ee(((t,i,o)=>R(e.post(T(l.otp.signIn,n),{loginId:t,loginOptions:i},{token:o}))))})),{}),signUp:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ee(((t,i,o)=>R(e.post(T(l.otp.signUp,n),{loginId:t,user:i,loginOptions:o}))))})),{}),signUpOrIn:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ee(((t,i)=>R(e.post(T(l.otp.signUpOrIn,n),{loginId:t,loginOptions:i}))))})),{}),update:{email:Re(((t,n,i,o)=>R(e.post(l.otp.update.email,Object.assign({loginId:t,email:n},o),{token:i})))),phone:Object.keys(re).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Te(((t,i,o,r)=>R(e.post(T(l.otp.update.phone,n),Object.assign({loginId:t,phone:i},r),{token:o}))))})),{})}}),_e=z(Z("tenant")),$e=z(Z("code")),Pe=e=>({start:_e(((t,n,i,o,r)=>R(e.post(l.saml.start,i||{},Object.assign({queryParams:Object.assign(Object.assign({tenant:t},n&&{redirectURL:n}),r&&{ssoId:r})},o&&{token:o}))))),exchange:$e((t=>R(e.post(l.saml.exchange,{code:t}))))}),De=Z("loginId"),Me=z(De,Z("code")),Ne=z(De),We=z(De),qe=e=>({signUp:Ne(((t,n)=>R(e.post(l.totp.signUp,{loginId:t,user:n})))),verify:Me(((t,n,i,o)=>R(e.post(l.totp.verify,{loginId:t,code:n,loginOptions:i},{token:o})))),update:We(((t,n)=>R(e.post(l.totp.update,{loginId:t},{token:n}))))}),Fe=Z("loginId"),Be=Z("newPassword"),Ve=z(Fe,Z("password")),Ke=z(Fe),He=z(Fe,Be),Ge=z(Fe,Z("oldPassword"),Be),Je=e=>({signUp:Ve(((t,n,i,o)=>R(e.post(l.password.signUp,{loginId:t,password:n,user:i,loginOptions:o})))),signIn:Ve(((t,n,i)=>R(e.post(l.password.signIn,{loginId:t,password:n,loginOptions:i})))),sendReset:Ke(((t,n,i)=>R(e.post(l.password.sendReset,{loginId:t,redirectUrl:n,templateOptions:i})))),update:He(((t,n,i)=>R(e.post(l.password.update,{loginId:t,newPassword:n},{token:i})))),replace:Ge(((t,n,i)=>R(e.post(l.password.replace,{loginId:t,oldPassword:n,newPassword:i})))),policy:()=>R(e.get(l.password.policy))}),ze=X("loginId"),Xe=Z("loginId"),Qe=Z("origin"),Ze=z(Xe,Qe,Z("name")),Ye=z(Xe,Qe),et=z(ze,Qe),tt=z(Xe,Qe,Q("token")),nt=z(Z("transactionId"),Z("response")),it=e=>({signUp:{start:Ze(((t,n,i,o)=>R(e.post(l.webauthn.signUp.start,{user:{loginId:t,name:i},origin:n,passkeyOptions:o})))),finish:nt(((t,n)=>R(e.post(l.webauthn.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:et(((t,n,i,o,r)=>R(e.post(l.webauthn.signIn.start,{loginId:t,origin:n,loginOptions:i,passkeyOptions:r},{token:o})))),finish:nt(((t,n)=>R(e.post(l.webauthn.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Ye(((t,n,i)=>R(e.post(l.webauthn.signUpOrIn.start,{loginId:t,origin:n,passkeyOptions:i}))))},update:{start:tt(((t,n,i,o)=>R(e.post(l.webauthn.update.start,{loginId:t,origin:n,passkeyOptions:o},{token:i})))),finish:nt(((t,n)=>R(e.post(l.webauthn.update.finish,{transactionId:t,response:n}))))}}),ot=X("loginId"),rt=z(ot),st=z(Z("pendingRef")),at=e=>({signUpOrIn:rt(((t,n)=>R(e.post(l.notp.signUpOrIn,{loginId:t,loginOptions:n})))),signUp:rt(((t,n,i)=>R(e.post(l.notp.signUp,{loginId:t,user:n,loginOptions:i})))),signIn:rt(((t,n,i)=>R(e.post(l.notp.signIn,{loginId:t,loginOptions:n},{token:i})))),waitForSession:st(((t,n)=>new Promise((i=>{const{pollingIntervalMs:o,timeoutMs:r}=oe(n);let s;const a=setInterval((async()=>{const n=await e.post(l.notp.session,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),i(R(Promise.resolve(n))))}),o);s=setTimeout((()=>{i({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)}))))}),lt=z(Z("token")),ct=z(Q("token"));var dt,ut=z([(dt=Z("projectId"),_(((e,t)=>n=>P(...t).validate(((e,t)=>{const n=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),i=n.length;let o=0,r=e===Object(e)?e:void 0;for(;null!=r&&o<i;)r=r[n[o++]];return o&&o===i&&void 0!==r?r:void 0})(n,e)))("projectId",dt))())])((e=>{var t;return(({projectId:e,logger:t,baseUrl:n,hooks:i,cookiePolicy:o,baseHeaders:r={},refreshCookieName:s,fetch:a})=>{return c=S({baseUrl:n||d,projectId:e,logger:t,hooks:i,cookiePolicy:o,baseConfig:{baseHeaders:r},refreshCookieName:s,fetch:a}),{accessKey:ne(c),otp:Le(c),magicLink:Ce(c),enchantedLink:ge(c),oauth:je(c),saml:Pe(c),totp:qe(c),notp:at(c),webauthn:it(c),password:Je(c),flow:me(c),refresh:ct(((e,t)=>R(c.post(l.refresh,{},{token:e,queryParams:t})))),selectTenant:z([B("tenantId")],[G('"token" must be string or undefined')])(((e,t)=>R(c.post(l.selectTenant,{tenant:e},{token:t})))),logout:ct((e=>R(c.post(l.logout,{},{token:e})))),logoutAll:ct((e=>R(c.post(l.logoutAll,{},{token:e})))),me:ct((e=>R(c.get(l.me,{token:e})))),myTenants:z([J('"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,R(c.post(l.myTenants,n,{token:t}))})),history:ct((e=>R(c.get(l.history,{token:e})))),isJwtExpired:lt(j),getTenants:lt(A),getJwtPermissions:lt(U),getJwtRoles:lt(E),getCurrentTenant:lt(L),httpClient:c};var c})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:t=>{var n;const i=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==i?void 0:i.reduce(((e,t)=>t(e)),t)},afterRequest:async(t,n)=>{var i;const o=[].concat((null===(i=e.hooks)||void 0===i?void 0:i.afterRequest)||[]);0!=o.length&&(await Promise.allSettled(null==o?void 0:o.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}}))})),ht=Object.assign(ut,{DeliveryMethods:ae});
|
|
1
|
+
!function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function n(e,t,n,i){return new(n||(n=Promise))((function(s,r){function o(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}function i(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function s(e,t,n,i,s){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?s.call(e,n):s?s.value=n:t.set(e,n),n}"function"==typeof SuppressedError&&SuppressedError;class r extends Error{}function o(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,i=e.split(".")[n];if("string"!=typeof i)throw new r(`Invalid token specified: missing part #${n+1}`);let s;try{s=o(i)}catch(e){throw new r(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new r(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}r.prototype.name="InvalidTokenError";var c={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"}},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",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 l="<region>",d=`https://api.${l}descope.com`,u=6e5,h="dct",p=()=>{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},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}};let g;const f=()=>{if(g)return g;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 g=`${t}-${n}`,g};var m;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT",e.patch="PATCH"}(m||(m={}));const w=({path:e,baseUrl:t,queryParams:n,projectId:i})=>{const s=i.slice(1,-27);t=t.replace(l,s?s+".":"");let r=e?`${t.replace(/\/$/,"")}/${null==e?void 0:e.replace(/^\//,"")}`:t;if(n){const e=Object.keys(n);e.forEach(((t,i)=>{r=`${r}${0===i?"?":""}${t}=${encodeURIComponent(n[t])}${i===e.length-1?"":"&"}`}))}return r},v=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,i])=>(e[n]=i,e)),e),e}),{})),_={"Content-Type":"application/json"},y=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},b=e=>{const t={"x-descope-sdk-session-id":f(),"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.40.0"};return e&&(t["x-descope-refresh-cookie-name"]=e),t},S=e=>{try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e},k=({baseUrl:e,projectId:t,baseConfig:n,refreshCookieName:i,logger:s,hooks:r,cookiePolicy:o,fetch:a})=>{const c=((e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),i=await n.text();return n.text=()=>Promise.resolve(i),n.json=()=>Promise.resolve(JSON.parse(i)),n.clone=()=>n,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=>p().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const i=await n(...t);return e[i.ok?"log":"error"](await(async e=>{const t=await e.text();return p().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(i)),i}:n})(s,a),l=async s=>{var a;const l=(null==r?void 0:r.beforeRequest)?r.beforeRequest(s):s,{path:d,body:u,headers:h,queryParams:p,method:g,token:f}=l,m=(e=>void 0===e?void 0:JSON.stringify(e))(u),k={headers:v(y(t,f),b(i),(null==n?void 0:n.baseHeaders)||{},S(m)?_:{},h),method:g,body:m};null!==o&&(k.credentials=o||"include");const I=await c(w({path:d,baseUrl:e,queryParams:p,projectId:t}),k);if((null==r?void 0:r.afterRequest)&&await r.afterRequest(s,null==I?void 0:I.clone()),null==r?void 0:r.transformResponse){const e=await I.json(),t=((null===(a=I.headers)||void 0===a?void 0:a.get("set-cookie"))||"").split(";").reduce(((e,t)=>{const[n,i]=t.split("=");return Object.assign(Object.assign({},e),{[n.trim()]:i})}),{}),n=Object.assign(Object.assign({},I),{json:()=>Promise.resolve(e),cookies:t});return n.clone=()=>n,r.transformResponse(n)}return I};return{get:(e,{headers:t,queryParams:n,token:i}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:m.get,token:i}),post:(e,t,{headers:n,queryParams:i,token:s}={})=>l({path:e,headers:n,queryParams:i,body:t,method:m.post,token:s}),patch:(e,t,{headers:n,queryParams:i,token:s}={})=>l({path:e,headers:n,queryParams:i,body:t,method:m.patch,token:s}),put:(e,t,{headers:n,queryParams:i,token:s}={})=>l({path:e,headers:n,queryParams:i,body:t,method:m.put,token:s}),delete:(e,{headers:t,queryParams:n,token:i}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:m.delete,token:i}),hooks:r,buildUrl:(n,i)=>w({projectId:t,baseUrl:e,path:n,queryParams:i})}};var I=429;function x(e,t,n){var i;let s=C(e);if(t){if(!(null==s?void 0:s.tenants)&&(null==s?void 0:s[h])===t)return(null==s?void 0:s[n])||[];s=null===(i=null==s?void 0:s.tenants)||void 0===i?void 0:i[t]}const r=null==s?void 0:s[n];return Array.isArray(r)?r:[]}function C(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return a(e)}function E(e){const{exp:t}=C(e);return(new Date).getTime()/1e3>t}function T(e){let t=C(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function O(e,t){return x(e,t,"permissions")}function U(e,t){return x(e,t,"roles")}const R=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function A(e,t){var n;const i=await e,s={code:i.status,ok:i.ok,response:i},r=await i.clone().json();return i.ok?s.data=r:(s.error=r,i.status===I&&Object.assign(s.error,{retryAfter:Number.parseInt(null===(n=i.headers)||void 0===n?void 0:n.get("retry-after"))||0})),s}function j(e){var t;return(null===(t=C(e))||void 0===t?void 0:t[h])||""}const P=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),L=(e,t)=>(n=t)=>t=>{const i=e.filter((e=>e(t)));return!(i.length<e.length)&&(n?n.replace("{val}",t):i.join(" OR "))},q=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),$=e=>t=>e.test(t),N=$(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),M=$(/^\+[1-9]{1}[0-9]{3,14}$/),D=P(N,'"{val}" is not a valid email'),W=P(M,'"{val}" is not a valid phone number'),F=P((e=>e.length>=1),"Minimum length is 1");const H=P((e=>"string"==typeof e),"Input is not a string"),K=P((e=>Array.isArray(e)),"Input is not an array"),J=P((e=>"boolean"==typeof e),"Input is not a boolean"),B=P((e=>void 0===e),"Input is defined"),V=L([H(),B()],"Input is not a string or undefined"),z=L([K(),J()],"Input is not an array or boolean"),G=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>q(...e).validate(n[t]))),t(...n)),Q=e=>[H(`"${e}" must be a string`)],X=e=>[V(`"${e}" must be string or undefined`)],Z=e=>[H(`"${e}" must be a string`),F(`"${e}" must not be empty`)],Y=e=>[H(`"${e}" must be a string`),D()],ee=e=>[H(`"${e}" must be a string`),W()],te=G(Z("accessKey")),ne=e=>({exchange:te(((t,n)=>A(e.post(c.accessKey.exchange,{loginOptions:n},{token:t}))))}),ie=(e,t,n)=>(t.forEach((t=>{const i=t.split(".");let s=i.shift(),r=e;for(;i.length>0;){if(r=r[s],!s||!r)throw Error(`Invalid path "${t}", "${s}" is missing or has no value`);s=i.shift()}if("function"!=typeof r[s])throw Error(`"${t}" is not a function`);const o=r[s];r[s]=n(o)})),e),se=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||u,u)});var re,oe;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(re||(re={})),function(e){e.email="email"}(oe||(oe={}));const ae=Object.assign(Object.assign({},re),oe);var ce;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(ce||(ce={}));const le=Z("loginId"),de=G(Z("token")),ue=G(le),he=G(Z("pendingRef")),pe=G(le,Y("email")),ge=e=>({verify:de((t=>A(e.post(c.enchantedLink.verify,{token:t})))),signIn:ue(((t,n,i,s)=>A(e.post(R(c.enchantedLink.signIn,ae.email),{loginId:t,URI:n,loginOptions:i},{token:s})))),signUpOrIn:ue(((t,n,i)=>A(e.post(R(c.enchantedLink.signUpOrIn,ae.email),{loginId:t,URI:n,loginOptions:i})))),signUp:ue(((t,n,i,s)=>A(e.post(R(c.enchantedLink.signUp,ae.email),{loginId:t,URI:n,user:i,loginOptions:s})))),waitForSession:he(((t,n)=>new Promise((i=>{const{pollingIntervalMs:s,timeoutMs:r}=se(n);let o;const a=setInterval((async()=>{const n=await e.post(c.enchantedLink.session,{pendingRef:t});n.ok&&(clearInterval(a),o&&clearTimeout(o),i(A(Promise.resolve(n))))}),s);o=setTimeout((()=>{i({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)})))),update:{email:pe(((t,n,i,s,r)=>A(e.post(c.enchantedLink.update.email,Object.assign({loginId:t,email:n,URI:i},r),{token:s}))))}}),fe=G(Z("flowId")),me=G(Z("executionId"),Z("stepId"),Z("interactionId")),we=e=>({start:fe(((t,n,i,s,r,o,a)=>A(e.post(c.flow.start,{flowId:t,options:n,conditionInteractionId:i,interactionId:s,componentsVersion:r,flowVersions:o,input:a})))),next:me(((t,n,i,s,r,o)=>A(e.post(c.flow.next,{executionId:t,stepId:n,interactionId:i,version:s,componentsVersion:r,input:o}))))}),ve=Z("loginId"),_e=G(Z("token")),ye=G(ve),be=G(ve,ee("phone")),Se=G(ve,Y("email")),ke=Object.keys(ae).filter((e=>e!==re.voice)),Ie=e=>({verify:_e((t=>A(e.post(c.magicLink.verify,{token:t})))),signIn:ke.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ye(((t,i,s,r)=>A(e.post(R(c.magicLink.signIn,n),{loginId:t,URI:i,loginOptions:s},{token:r}))))})),{}),signUp:ke.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ye(((t,i,s,r)=>A(e.post(R(c.magicLink.signUp,n),{loginId:t,URI:i,user:s,loginOptions:r}))))})),{}),signUpOrIn:ke.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ye(((t,i,s)=>A(e.post(R(c.magicLink.signUpOrIn,n),{loginId:t,URI:i,loginOptions:s}))))})),{}),update:{email:Se(((t,n,i,s,r)=>A(e.post(c.magicLink.update.email,Object.assign({loginId:t,email:n,URI:i},r),{token:s})))),phone:Object.keys(re).filter((e=>e!==re.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:be(((t,i,s,r,o)=>A(e.post(R(c.magicLink.update.phone,n),Object.assign({loginId:t,phone:i,URI:s},o),{token:r}))))})),{})}});var xe;!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"}(xe||(xe={}));const Ce=G(Z("code")),Ee=e=>({start:Object.assign(((t,n,i,s)=>A(e.post(c.oauth.start,i||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:s}))),Object.keys(xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,i,s)=>A(e.post(c.oauth.start,i||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:s}))})),{})),exchange:Ce((t=>A(e.post(c.oauth.exchange,{code:t})))),startNative:(t,n,i)=>A(e.post(c.oauth.startNative,{provider:t,loginOptions:n,implicit:i})),finishNative:(t,n,i,s,r)=>A(e.post(c.oauth.finishNative,{provider:t,stateId:n,user:i,code:s,idToken:r})),getOneTapClientId:t=>A(e.get(c.oauth.oneTap.getOneTapClientId.replace("{provider}",t))),verifyOneTapIDToken:(t,n,i,s)=>A(e.post(c.oauth.oneTap.verifyOneTapIDToken,{provider:t,idToken:n,nonce:i,loginOptions:s})),exchangeOneTapIDToken:(t,n,i,s)=>A(e.post(c.oauth.oneTap.exchangeOneTapIDToken,{provider:t,idToken:n,nonce:i,loginOptions:s}))}),Te=Z("loginId"),Oe=G(Te,Z("code")),Ue=G(Te),Re=G(Te,ee("phone")),Ae=G(Te,Y("email")),je=e=>({verify:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Oe(((t,i)=>A(e.post(R(c.otp.verify,n),{code:i,loginId:t}))))})),{}),signIn:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ue(((t,i,s)=>A(e.post(R(c.otp.signIn,n),{loginId:t,loginOptions:i},{token:s}))))})),{}),signUp:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ue(((t,i,s)=>A(e.post(R(c.otp.signUp,n),{loginId:t,user:i,loginOptions:s}))))})),{}),signUpOrIn:Object.keys(ae).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ue(((t,i)=>A(e.post(R(c.otp.signUpOrIn,n),{loginId:t,loginOptions:i}))))})),{}),update:{email:Ae(((t,n,i,s)=>A(e.post(c.otp.update.email,Object.assign({loginId:t,email:n},s),{token:i})))),phone:Object.keys(re).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Re(((t,i,s,r)=>A(e.post(R(c.otp.update.phone,n),Object.assign({loginId:t,phone:i},r),{token:s}))))})),{})}}),Pe=G(Z("tenant")),Le=G(Z("code")),qe=e=>({start:Pe(((t,n,i,s,r)=>A(e.post(c.saml.start,i||{},Object.assign({queryParams:Object.assign(Object.assign({tenant:t},n&&{redirectURL:n}),r&&{ssoId:r})},s&&{token:s}))))),exchange:Le((t=>A(e.post(c.saml.exchange,{code:t}))))}),$e=Z("loginId"),Ne=G($e,Z("code")),Me=G($e),De=G($e),We=e=>({signUp:Me(((t,n)=>A(e.post(c.totp.signUp,{loginId:t,user:n})))),verify:Ne(((t,n,i,s)=>A(e.post(c.totp.verify,{loginId:t,code:n,loginOptions:i},{token:s})))),update:De(((t,n)=>A(e.post(c.totp.update,{loginId:t},{token:n}))))}),Fe=Z("loginId"),He=Z("newPassword"),Ke=G(Fe,Z("password")),Je=G(Fe),Be=G(Fe,He),Ve=G(Fe,Z("oldPassword"),He),ze=e=>({signUp:Ke(((t,n,i,s)=>A(e.post(c.password.signUp,{loginId:t,password:n,user:i,loginOptions:s})))),signIn:Ke(((t,n,i)=>A(e.post(c.password.signIn,{loginId:t,password:n,loginOptions:i})))),sendReset:Je(((t,n,i)=>A(e.post(c.password.sendReset,{loginId:t,redirectUrl:n,templateOptions:i})))),update:Be(((t,n,i)=>A(e.post(c.password.update,{loginId:t,newPassword:n},{token:i})))),replace:Ve(((t,n,i)=>A(e.post(c.password.replace,{loginId:t,oldPassword:n,newPassword:i})))),policy:()=>A(e.get(c.password.policy))}),Ge=Q("loginId"),Qe=Z("loginId"),Xe=Z("origin"),Ze=G(Qe,Xe,Z("name")),Ye=G(Qe,Xe),et=G(Ge,Xe),tt=G(Qe,Xe,X("token")),nt=G(Z("transactionId"),Z("response")),it=e=>({signUp:{start:Ze(((t,n,i,s)=>A(e.post(c.webauthn.signUp.start,{user:{loginId:t,name:i},origin:n,passkeyOptions:s})))),finish:nt(((t,n)=>A(e.post(c.webauthn.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:et(((t,n,i,s,r)=>A(e.post(c.webauthn.signIn.start,{loginId:t,origin:n,loginOptions:i,passkeyOptions:r},{token:s})))),finish:nt(((t,n)=>A(e.post(c.webauthn.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Ye(((t,n,i)=>A(e.post(c.webauthn.signUpOrIn.start,{loginId:t,origin:n,passkeyOptions:i}))))},update:{start:tt(((t,n,i,s)=>A(e.post(c.webauthn.update.start,{loginId:t,origin:n,passkeyOptions:s},{token:i})))),finish:nt(((t,n)=>A(e.post(c.webauthn.update.finish,{transactionId:t,response:n}))))}}),st=Q("loginId"),rt=G(st),ot=G(Z("pendingRef")),at=e=>({signUpOrIn:rt(((t,n)=>A(e.post(c.notp.signUpOrIn,{loginId:t,loginOptions:n})))),signUp:rt(((t,n,i)=>A(e.post(c.notp.signUp,{loginId:t,user:n,loginOptions:i})))),signIn:rt(((t,n,i)=>A(e.post(c.notp.signIn,{loginId:t,loginOptions:n},{token:i})))),waitForSession:ot(((t,n)=>new Promise((i=>{const{pollingIntervalMs:s,timeoutMs:r}=se(n);let o;const a=setInterval((async()=>{const n=await e.post(c.notp.session,{pendingRef:t});n.ok&&(clearInterval(a),o&&clearTimeout(o),i(A(Promise.resolve(n))))}),s);o=setTimeout((()=>{i({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)}))))}),ct=G(Z("token")),lt=G(X("token"));var dt,ut=G([(dt=Z("projectId"),P(((e,t)=>n=>q(...t).validate(((e,t)=>{const n=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),i=n.length;let s=0,r=e===Object(e)?e:void 0;for(;null!=r&&s<i;)r=r[n[s++]];return s&&s===i&&void 0!==r?r:void 0})(n,e)))("projectId",dt))())])((e=>{var t;return(({projectId:e,logger:t,baseUrl:n,hooks:i,cookiePolicy:s,baseHeaders:r={},refreshCookieName:o,fetch:a})=>{return l=k({baseUrl:n||d,projectId:e,logger:t,hooks:i,cookiePolicy:s,baseConfig:{baseHeaders:r},refreshCookieName:o,fetch:a}),{accessKey:ne(l),otp:je(l),magicLink:Ie(l),enchantedLink:ge(l),oauth:Ee(l),saml:qe(l),totp:We(l),notp:at(l),webauthn:it(l),password:ze(l),flow:we(l),refresh:lt(((e,t)=>A(l.post(c.refresh,{},{token:e,queryParams:t})))),selectTenant:G([H("tenantId")],[V('"token" must be string or undefined')])(((e,t)=>A(l.post(c.selectTenant,{tenant:e},{token:t})))),logout:lt((e=>A(l.post(c.logout,{},{token:e})))),logoutAll:lt((e=>A(l.post(c.logoutAll,{},{token:e})))),me:lt((e=>A(l.get(c.me,{token:e})))),myTenants:G([z('"tenants" must a string array or a boolean')],[V('"token" must be string or undefined')])(((e,t)=>{const n={};return"boolean"==typeof e?n.dct=e:n.ids=e,A(l.post(c.myTenants,n,{token:t}))})),history:lt((e=>A(l.get(c.history,{token:e})))),isJwtExpired:ct(E),getTenants:ct(T),getJwtPermissions:ct(O),getJwtRoles:ct(U),getCurrentTenant:ct(j),httpClient:l};var l})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:t=>{var n;const i=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==i?void 0:i.reduce(((e,t)=>t(e)),t)},afterRequest:async(t,n)=>{var i;const s=[].concat((null===(i=e.hooks)||void 0===i?void 0:i.afterRequest)||[]);0!=s.length&&(await Promise.allSettled(null==s?void 0:s.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}}))})),ht=Object.assign(ut,{DeliveryMethods:ae});
|
|
2
2
|
/*! js-cookie v3.0.5 | MIT */
|
|
3
|
-
function pt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)e[i]=n[i]}return e}var gt=function e(t,n){function i(e,i,o){if("undefined"!=typeof document){"number"==typeof(o=pt({},n,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var r="";for(var s in o)o[s]&&(r+="; "+s,!0!==o[s]&&(r+="="+o[s].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+r}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],i={},o=0;o<n.length;o++){var r=n[o].split("="),s=r.slice(1).join("=");try{var a=decodeURIComponent(r[0]);if(i[a]=t.read(s,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",pt({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,pt({},this.attributes,t))},withConverter:function(t){return e(pt({},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 ft={default:"endpoint"},vt="Blocked by CSP",mt="The endpoint parameter is not a valid URL",bt="Failed to load the JS script of the agent",wt="9319";function yt(e,t){var n,i,o,r,s,a=[],l=(n=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var i,o=0,r=t.length;o<r;o++)!i&&o in t||(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||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,i=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,r++))},o=new Set,[n.current(),function(e,t){var r,s=t instanceof Error?t.message:"";if(s===vt||s===mt)n.exclude(),r=0;else if(s===wt)n.exclude();else if(s===bt){var a=Date.now()-e.getTime()<50,l=n.current();l&&a&&!o.has(l)&&(o.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()+i()-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,i=function(t){return a.push({url:e,startedAt:n,finishedAt:new Date,error:t})},o=t(e);return o.then((function(){return i()}),i),o.catch((function(e){if(null!=s||(s=e),a.length>=5)throw s;var t=d(n,e);if(!t)throw s;var i,o=t[0],r=t[1];return(i=r,new Promise((function(e){return setTimeout(e,i)}))).then((function(){return u(o)}))}))};return u(c).then((function(e){return[e,a]}))}var kt="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",It=kt;function St(n){var i;n.scriptUrlPattern;var o=n.token,r=n.apiKey,s=void 0===r?o:r,a=t(n,["scriptUrlPattern","token","apiKey"]),l=null!==(i=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(n,"scriptUrlPattern"))&&void 0!==i?i:kt,c=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,i){return e.addEventListener(t,n,i),function(){return e.removeEventListener(t,n,i)}}(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 yt(e,Ct)})).catch((function(e){throw u(),function(e){return e instanceof Error&&e.message===wt?new Error(bt):e}(e)})).then((function(t){var n=t[0],i=t[1];return u(),n.load(e(e({},a),{ldi:{attempts:i,visibilityStates:d}}))}))}function Ct(e){return function(e,t,n){var i,o=document,r="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),o=t.blockedURI;o!==n.href&&o!==n.protocol.slice(0,-1)&&o!==n.origin||(i=t,a())};o.addEventListener(r,s);var a=function(){return o.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(),i)return n(i);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(mt);var i=document.createElement("script"),o=function(){var e;return null===(e=i.parentNode)||void 0===e?void 0:e.removeChild(i)},r=document.head||document.getElementsByTagName("head")[0];i.onload=function(){o(),t()},i.onerror=function(){o(),n(new Error(bt))},i.async=!0,i.src=e,r.appendChild(i)}))}(e)}),(function(){throw new Error(vt)})).then(Ot)}function Ot(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,i=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==i?void 0:i.configurable)?delete e[t]:i&&!i.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(wt);return n}const xt=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,i)=>{var o;return n[i]=[].concat((null===(o=e.hooks)||void 0===o?void 0:o[i])||[]).concat((null==t?void 0:t[i])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},jt=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json());return(null==t?void 0:t.authInfo)||t||{}},At=async e=>{const t=await jt(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},Ut="undefined"!=typeof localStorage,Et=(e,t)=>Ut&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),Tt=e=>Ut&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Rt=e=>Ut&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),Lt=(...e)=>{console.debug(...e)},_t="undefined"!=typeof window,$t=Math.pow(2,31)-1,Pt="DS",Dt="DSR";function Mt(e=""){return Tt(`${e}${Dt}`)||""}function Nt(e=""){return gt.get(Pt)||Tt(`${e}${Pt}`)||""}function Wt(e=""){Rt(`${e}${Dt}`),Rt(`${e}${Pt}`),gt.remove(Pt)}const qt=_t&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",Ft="vsid",Bt="vrid",Vt="fp",Kt=(e=!1)=>{const t=localStorage.getItem(Vt);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},Ht=async(e,t=qt)=>{try{if(Kt())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const r=o.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",s=St({apiKey:e,endpoint:[i.toString(),ft],scriptUrlPattern:[r,It]}),a=await s,{requestId:l}=await a.get({linkedId:n}),c=((e,t)=>({[Ft]:e,[Bt]:t}))(n,l);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem(Vt,JSON.stringify(t))})(c)}catch(e){console.warn("Could not load fingerprint",e)}},Gt=e=>{const t=Kt(!0);return t&&e.body&&(e.body.fpData=t),e},Jt="dls_last_user_login_id",zt="dls_last_user_display_name",Xt=()=>Tt(Jt),Qt=()=>Tt(zt),Zt=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,i={}]=t,o=Xt(),r=Qt();return o&&(null!==(n=i.lastAuth)&&void 0!==n||(i.lastAuth={}),i.lastAuth.loginId=o,i.lastAuth.name=r),await e(...t)};function Yt(){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 en(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=an(n.publicKey.challenge),n.publicKey.user.id=an(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=an(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:ln(n.rawId),type:n.type,response:{attestationObject:ln(n.response.attestationObject),clientDataJSON:ln(n.response.clientDataJSON)}});var n}async function tn(e){const t=rn(e);return sn(await navigator.credentials.get(t))}async function nn(e,t){const n=rn(e);return n.signal=t.signal,n.mediation="conditional",sn(await navigator.credentials.get(n))}async function on(e=!1){if(!_t)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 rn(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=an(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=an(e.id)})),n}function sn(e){return JSON.stringify({id:e.id,rawId:ln(e.rawId),type:e.type,response:{authenticatorData:ln(e.response.authenticatorData),clientDataJSON:ln(e.response.clientDataJSON),signature:ln(e.response.signature),userHandle:e.response.userHandle?ln(e.response.userHandle):void 0}})}function an(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function ln(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var cn,dn=(cn=e=>({async signUp(t,n,i){const o=await e.webauthn.signUp.start(t,window.location.origin,n,i);if(!o.ok)return o;const r=await en(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,r)},async signIn(t,n){const i=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!i.ok)return i;const o=await tn(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,o)},async signUpOrIn(t,n){var i;const o=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!o.ok)return o;if(null===(i=o.data)||void 0===i?void 0:i.create){const t=await en(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await tn(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,t)}},async update(t,n,i){const o=await e.webauthn.update.start(t,window.location.origin,n,i);if(!o.ok)return o;const r=await en(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,r)},helpers:{create:en,get:tn,isSupported:on,conditional:nn}}),(...e)=>{const t=cn(...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 un="/fedcm/config";async function hn(e,t){var n,i,o;try{const o=await async function(e,t="google",n,i,o){const r=(()=>{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)})(),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(o&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==o||o(n),void d()}if(i&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==i||i(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!o.credential)return null;if(null==t?void 0:t.onCodeReceived){const i=await e.oauth.verifyOneTapIDToken(o.provider,o.credential,o.nonce,null==t?void 0:t.loginOptions);if(!i.ok||!i.data)throw new Error("Failed to verify OneTap client ID for provider "+o.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,i.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(o.provider,o.credential,o.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+o.provider);null===(i=null==t?void 0:t.onAuthenticated)||void 0===i||i.call(t,n.data)}}catch(e){null===(o=null==t?void 0:t.onFailed)||void 0===o||o.call(t,e)}}var pn=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await on(),i=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=i,e.flow.start(...t)}});const gn=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>n=>{var{fpKey:i,fpLoad:o}=n,r=t(n,["fpKey","fpLoad"]);return _t?(i&&o&&Ht(i).catch((()=>null)),e(xt(r,{beforeRequest:Gt}))):e(r)}),(e=>n=>{var{autoRefresh:i}=n,o=t(n,["autoRefresh"]);if(!i)return e(o);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;_t&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&l&&new Date>l&&(Lt("Expiration time passed, refreshing session"),d.refresh(Mt()||c))}));const d=e(xt(o,{afterRequest:async(e,t)=>{const{refreshJwt:n,sessionJwt:i,sessionExpiration:o}=await jt(t);if(401===(null==t?void 0:t.status))Lt("Received 401, canceling all timers"),r();else if(i||o){if(l=((e,t)=>{if(t)return new Date(1e3*t);Lt("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}})(i,o),!l)return void Lt("Could not extract expiration time from session token");c=n;const e=(e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>$t&&(Lt(`Timeout is too large (${t}ms), setting it to ${$t}ms`),t=$t),t})(l);if(r(),e<=2e4)return void Lt("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});Lt(`Setting refresh timer for ${t}. (${e}ms)`),s((()=>{Lt("Refreshing session due to timer"),d.refresh(Mt()||n)}),e)}}}));return ie(d,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return Lt("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.28.0"},t.baseHeaders)}))),(e=>t=>{const n=Yt(),i=Yt(),o=Yt(),r=e(xt(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))i.pub(null),o.pub(null),n.pub(null);else{const e=await At(t);e&&o.pub(e);const{sessionJwt:r,sessionExpiration:s}=await jt(t);r&&i.pub(r),(s||r)&&n.pub(s||42)}}})),s=ie(r,["logout","logoutAll"],(e=>async(...t)=>{const r=await e(...t);return i.pub(null),o.pub(null),n.pub(null),r}));return Object.assign(s,{onSessionTokenChange:i.sub,onUserChange:o.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(e=>n=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:o=!1}=n,r=t(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(e(r),{getLastUserLoginId:Xt,getLastUserDisplayName:Qt});const s=e(xt(r,{afterRequest:async(e,t)=>{var n;const i=await At(t),o=null===(n=null==i?void 0:i.loginIds)||void 0===n?void 0:n[0],r=null==i?void 0:i.name;o&&((e=>{Et(Jt,e)})(o),(e=>{Et(zt,e)})(r))}}));let a=ie(s,["flow.start"],Zt);return a=ie(a,["logout","logoutAll"],(e=>t=>async(...n)=>{const i=await t(...n);return e||(Rt(Jt),Rt(zt)),i})(o)),Object.assign(a,{getLastUserLoginId:Xt,getLastUserDisplayName:Qt})}),(e=>n=>{var{persistTokens:i,sessionTokenViaCookie:o,storagePrefix:r}=n,s=t(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!i||!_t)return e(s);const a=e(xt(s,{beforeRequest:(l=r,e=>Object.assign(e,{token:e.token||Mt(l)})),afterRequest:async(e,n)=>{const i=/^\/v\d+\/mgmt\//.test(e.path);401===(null==n?void 0:n.status)?i||Wt(r):((e={},n,i)=>{var o,{refreshJwt:r,sessionJwt:s}=e,a=t(e,["refreshJwt","sessionJwt"]);if(void 0===n&&(n=!1),void 0===i&&(i=""),r&&Et(`${i}${Dt}`,r),s)if(n){const e=n.sameSite||"Strict",t=null===(o=n.secure)||void 0===o||o;!function(e,t,{cookiePath:n,cookieDomain:i,cookieExpiration:o,cookieSameSite:r="Strict",cookieSecure:s=!0}){if(t){const a=new Date(1e3*o),l=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(i);gt.set(e,t,{path:n,domain:l?i:void 0,expires:a,sameSite:r,secure:s})}}(Pt,s,Object.assign(Object.assign({},a),{cookieSameSite:e,cookieSecure:t}))}else Et(`${i}${Pt}`,s)})(await jt(n),o,r)}}));var l;const c=ie(a,["logout","logoutAll"],(e=>t=>async(...n)=>{const i=await t(...n);return Wt(e),i})(r));return Object.assign(c,{getRefreshToken:()=>Mt(r),getSessionToken:()=>Nt(r)})}))(((...e)=>{const t=ht(...e);return Object.assign(Object.assign({},t),{refresh:e=>{const n=Nt(),i=Mt();return t.refresh(e,{dcs:n?"t":"f",dcr:i?"t":"f"})},flow:pn(t),webauthn:dn(t),fedcm:(n=t,i=e[0].projectId,{onetap:{requestExchangeCode(e){hn(n,e)},requestAuthentication(e){hn(n,e)}},oneTap(e,t,i,o,r){hn(n,{provider:e,oneTapConfig:t,loginOptions:i,onSkipped:o,onDismissed:r})},async launch(e){var t;const o={identity:{context:e||"signin",providers:[{configURL:n.httpClient.buildUrl(i+un),clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return n.refresh(r.token)},isSupported:()=>_t&&"IdentityCredential"in window,async isLoggedIn(e){var t;const o=n.httpClient.buildUrl(i+un);try{const n={identity:{context:e||"signin",providers:[{configURL:o,clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return!!r&&!!r.token}catch(e){return!1}}})});var n,i})),fn="undefined"!=typeof localStorage,vn="J151000",mn=fn&&localStorage.getItem("base.content.url")||"",bn="base.ui.components.url";fn&&localStorage.getItem(bn),fn&&localStorage.getItem(bn);const wn="descope-login-flow",yn="code",kn="data-exclude-field",In="data-exclude-next",Sn="dls_last_auth",Cn="state_id",On="saml_idp_state_id",xn="saml_idp_username",jn="descope_idp_initiated",An="sso_app_id",Un="third_party_app_id",En="third_party_app_state_id",Tn="oidc_login_hint",Rn="oidc_prompt",Ln="oidc_error_redirect_uri",_n="application_scopes",$n="data-type",Pn="redirect",Dn="poll",Mn="webauthnCreate",Nn="webauthnGet",Wn="nativeBridge",qn="loadForm",Fn="submit",Bn="polling",Vn=["descope-multi-select-combo-box","descope-text-area"],Kn=["cssVars","componentsConfig","inputs","errorText","errorType","clientScripts"];var Hn;!function(e){e.backward="backward",e.forward="forward"}(Hn||(Hn={}));const Gn=["descope-enriched-text"];function Jn(e){return new URLSearchParams(window.location.search).get(e)}function zn(e){if(window.history.replaceState&&Jn(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 Xn(e,t){if(!t)return;const n=+e,i=+t;return Number.isNaN(n)||Number.isNaN(i)?void 0:n>i?Hn.forward:n<i?Hn.backward:void 0}const Qn=e=>{let[t="",n=""]=(Jn(wn)||"").split("_");const i=(e=>{var t;return(null===(t=/(.*)\|#\|.*/.exec(e))||void 0===t?void 0:t[1])||""})(t);return(!e||i&&i!==e)&&(t="",n=""),{executionId:t,stepId:n,executionFlowId:i}};function Zn(){zn(wn)}const Yn=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),ei=(e,t)=>{const{executionId:n,stepId:i,executionFlowId:o}=Qn(e);if(o&&e!==o)return t.debug("Flow id does not match the execution flow id, skipping url params handling"),{ssoQueryParams:{}};(n||i)&&Zn();const r=Jn("t")||void 0;r&&zn("t");const s=Jn(yn)||void 0;s&&zn(yn);const a=Jn("err")||void 0;a&&zn("err");const{redirectAuthCodeChallenge:l,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:d,redirectAuthInitiator:u}={redirectAuthCodeChallenge:Jn("ra-challenge"),redirectAuthCallbackUrl:Jn("ra-callback"),redirectAuthBackupCallbackUri:Jn("ra-backup-callback"),redirectAuthInitiator:Jn("ra-initiator")},h=Jn(Cn);h&&zn(Cn);const p=Jn(On);p&&zn(On);const g=Jn(xn);p&&zn(xn);const f=Jn(jn);f&&zn(jn);const v=Jn(An);v&&zn(An);const m=Jn(Un);m&&zn(Un);const b=Jn(En);b&&zn(En);const w=Jn(_n);w&&zn(_n);const y=Jn(Tn);y&&zn(Tn);const k=Jn(Rn);k&&zn(Rn);const I=Jn(Ln);I&&zn(Ln);return{executionId:n,stepId:i,token:r,code:s,exchangeError:a,redirectAuthCodeChallenge:l,redirectAuthCallbackUrl:c,redirectAuthBackupCallbackUri:d,redirectAuthInitiator:u,ssoQueryParams:{oidcIdpStateId:h,samlIdpStateId:p,samlIdpUsername:g,descopeIdpInitiated:"true"===f,ssoAppId:v,oidcLoginHint:y,oidcPrompt:k,oidcErrorRedirectUri:I,thirdPartyAppId:m,thirdPartyAppStateId:b,applicationScopes:w}}},ti=e=>{let t,n;return Object.assign(((...i)=>{return t&&(r=i,(o=t).length===r.length&&o.every(((e,t)=>e===r[t])))||(t=i,n=e(...i)),n;var o,r}),{reset:()=>{t=void 0,n=void 0}})};function ni(e,t,n){return new Promise(((i,o)=>{let r=!1;const s=setTimeout((()=>{r=!0,void 0!==n?i(n):o(new Error(`Promise timed out after ${e} ms`))}),e);t.then((e=>{r||(clearTimeout(s),i(e))})).catch((e=>{r||(clearTimeout(s),o(e))}))}))}const ii=(e,{oidcIdpStateId:t,samlIdpStateId:n,samlIdpUsername:i,ssoAppId:o,oidcLoginHint:r,oidcPrompt:s,oidcErrorRedirectUri:a,thirdPartyAppId:l,thirdPartyAppStateId:c,applicationScopes:d})=>!(!e||t||n||i||o||r||s||a||l||c||d),oi=e=>null==e?void 0:e.submit(),ri=(e,t)=>{const n=t.find((t=>e[t]));return n?e[n]:null},si=(e,t=100)=>{let n;return function(...i){n||e.apply(this,i),clearTimeout(n),n=setTimeout((()=>{n=null}),t)}};function ai(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 li=e=>{const t=(n=e.screenState,i=(e,t)=>Kn.includes(t)||t.startsWith("_"),Object.fromEntries(Object.entries(n).filter((([e,t])=>!i(t,e)))));var n,i;const{screenState:{errorText:o,errorType:r}}=e;return(o||r)&&(t.error={text:o,type:r}),t};var ci,di,ui,hi;function pi(e,t){const n=Object.getOwnPropertyNames(e),i=Object.getOwnPropertyNames(t);if(n.length!==i.length)return!1;for(let i=0;i<n.length;i+=1){const o=n[i],r=e[o],s=t[o];if(null===r||null===s){if(r!==s)return!1}else if("object"==typeof r&&"object"==typeof s){if(!pi(r,s))return!1}else if(r!==s)return!1}return!0}class gi{constructor(e={},{forceUpdate:t=!1}={}){ci.set(this,void 0),di.set(this,{}),ui.set(this,0),hi.set(this,!0),this.update=e=>{const t="function"==typeof e?e(i(this,ci,"f")):e,n=Object.assign(Object.assign({},i(this,ci,"f")),t),r=i(this,ci,"f");o(this,ci,n,"f"),Object.freeze(i(this,ci,"f")),setTimeout((()=>{Object.values(i(this,di,"f")).forEach((({cb:e,selector:t})=>{const o=t(r),s=t(n);!i(this,hi,"f")&&(function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(s)?pi(o,s):o===s)||e(s,o,((e,t)=>n=>e[n]!==t[n])(s,o))}))}),0)},o(this,ci,e,"f"),o(this,hi,t,"f")}get current(){return Object.assign({},i(this,ci,"f"))}set forceUpdate(e){o(this,hi,e,"f")}subscribe(e,t=e=>e){return o(this,ui,i(this,ui,"f")+1,"f"),i(this,di,"f")[i(this,ui,"f")]={cb:e,selector:t},i(this,ui,"f").toString()}unsubscribe(e){const t=!!i(this,di,"f")[e];return t&&delete i(this,di,"f")[e],t}unsubscribeAll(){return o(this,di,{},"f"),!0}}ci=new WeakMap,di=new WeakMap,ui=new WeakMap,hi=new WeakMap;const fi=["*","#","/","(",")","[","]","_","<",">","`"],vi=e=>{const t=fi.map((t=>`${e}${t}`)).join("|");return new RegExp(`(${t})`,"g")},mi=["disabled"],bi=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${kn}])`)).forEach((e=>{e.value=n}))}))},wi=(e,t)=>t.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),e),yi=(e,t,n)=>e.replace(/{{(.+?)}}/g,((e,i)=>n?(e=>"string"!=typeof e?e:e.replace(vi("\\"),"\\$1"))(wi(t,i)):wi(t,i))),ki=(e,t)=>{e.querySelectorAll("descope-text,descope-link,descope-enriched-text,descope-code-snippet").forEach((e=>{const n=(i=e.localName,Gn.includes(i));var i;e.textContent=yi(e.textContent,t,n);const o=e.getAttribute("href");o&&e.setAttribute("href",yi(o,t))}))},Ii=(e,t,n)=>{e.querySelectorAll(`[${$n}="${t}"]`).forEach((e=>{e.setAttribute("href",n)}))},Si=(e,t,n)=>{var i,o;const r=null===(i=customElements.get(t))||void 0===i?void 0:i.cssVarList.url;n&&r&&(null===(o=null==e?void 0:e.style)||void 0===o||o.setProperty(r,`url(data:image/jpg;base64,${n})`))},Ci=(e,n,i,o,r)=>{var s,a;Ii(e,"totp-link",null===(s=null==n?void 0:n.totp)||void 0===s?void 0:s.provisionUrl),Ii(e,"notp-link",null===(a=null==n?void 0:n.notp)||void 0===a?void 0:a.redirectUrl),ki(e,n),((e,n,i)=>{if(!n)return;const{componentsDynamicAttrs:o}=n,r=t(n,["componentsDynamicAttrs"]),s=Object.keys(r).reduce(((e,t)=>(e[`[name=${t}]`]=r[t],e)),{});o&&Object.keys(o).forEach((e=>{const t=o[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 o=n[t];if("string"!=typeof o)try{o=JSON.stringify(o)}catch(e){i.error(`Could not stringify value "${o}" for "${t}"`,e.message),o=""}e.setAttribute(t,o)}))}))}))})(e,i,r),((e,t)=>{e.querySelectorAll("[data-has-dynamic-attr-values]").forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=yi(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])=>{mi.includes(t)&&e.setAttribute(t,n)}))}))}))})(e,o)},Oi=ti((()=>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)))),i=(()=>{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 ni(100,n,i)}catch(e){return console.error("Conditional login check failed",e),!1}})))),xi=(e,t,n,i={})=>{var o,r,s,a;return[Math.min(Math.max(t,("all"===i.left?e.offsetWidth:null!==(o=i.left)&&void 0!==o?o:0)-e.offsetWidth),window.innerWidth-("all"===i.right?e.offsetWidth:null!==(r=i.right)&&void 0!==r?r:0)),Math.min(Math.max(n,("all"===i.top?e.offsetHeight:null!==(s=i.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===i.bottom?e.offsetHeight:null!==(a=i.bottom)&&void 0!==a?a:0))]},ji="dls_ab_testing_id",Ai={"lastAuth.loginId":{"not-empty":e=>!!e.loginId,empty:e=>!e.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}};function Ui(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(Sn)))}catch(e){}return t}function Ei(...e){return t=>e.reduce(((e,t)=>t(e)),t)}const Ti=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 i=e(n);return i[t]=!0,i}},Ri=["error","warn","info","debug"],Li=Ti((e=>{var t,n,r,s;return s=class extends e{constructor(){super(...arguments),t.add(this),n.set(this,i(this,t,"m",r).call(this,console))}set logger(e){o(this,n,i(this,t,"m",r).call(this,e||console),"f")}get logger(){return i(this,n,"f")}onLogEvent(e,t){}},n=new WeakMap,t=new WeakSet,r=function(e){return Ri.reduce(((t,n)=>(t[n]=(...t)=>{var i;this.onLogEvent(n,t),null===(i=e[n])||void 0===i||i.call(e,...t)},t)),{})},s})),_i="undefined"!=typeof localStorage,$i=_i&&localStorage.getItem("base.content.url")||"",Pi=(e,t)=>!t&&`${e} cannot be empty, please make sure to set this attribute`,Di=Ti((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)&&i(this,t,"f")&&(o(this,t,!1,"f"),this.init())}async init(){}},t=new WeakMap,n})),Mi=Ti((e=>{var t,n;const o=Ei(Li,Di)(e);return n=class extends o{constructor(){super(...arguments),t.set(this,{})}async init(){var e,n,o;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),n=this,o=e=>{var n;null===(n=i(this,t,"f")[e])||void 0===n||n.forEach((t=>{t(e,this.getAttribute(e))}))},Array.from(n.attributes).forEach((e=>o(e.name))),new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&o(e.attributeName)}))})).observe(n,{attributes:!0})}observeAttribute(e,n){i(this,t,"f")[e]||(i(this,t,"f")[e]=[]);const o=i(this,t,"f")[e].push(n);return()=>i(this,t,"f")[e].splice(o,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})),Ni=e=>t=>{var n,o,r;const s=Ei(Li,Di,Mi)(t),a=Object.keys(e);return r=class extends s{constructor(...e){super(...e),n.add(this),this.observeAttributes(a,i(this,n,"m",o).bind(this))}async init(){var e;a.forEach((e=>i(this,n,"m",o).call(this,e,this.getAttribute(e)))),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},n=new WeakSet,o=function(t,n){const i=e[t],o="function"==typeof i?i(t,n):i;o&&this.logger.error(o)},r};Ni.missingAttrValidator=Pi;const Wi=Ti((e=>{const t=Ei(Ni({"project-id":Pi}))(e);return class extends t{get projectId(){return this.getAttribute("project-id")}}})),qi=Ti((e=>class extends e{get baseUrl(){return this.getAttribute("base-url")||""}})),Fi="Trying the next fallback URL...";function Bi({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:i="https://static.descope.com/pages"}){const o=new URL(i);return o.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(o.pathname,e,n,t),o.baseUrl=i,o}const Vi=Ti((e=>{var t,n,r,s,a;const l=Ei(Li,Wi,qi)(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=i(this,t,"m",s).call(this,e),l=Array.isArray(a)?e=>{if(e!==a.length-1){const{baseUrl:t}=a[e];o(this,r,t,"f")}}:null;try{const e=await(async(e,t,{logger:n,onSuccess:i})=>{const o=Array.isArray(e)?e:[e];for(let e=0;e<o.length;e++){const r=o[e],s=e===o.length-1;try{const o=await fetch(r.toString(),t);if(o.ok)return null==i||i(e),o;const a=`Error fetching URL ${r} [${o.status}]`;if(s)throw new Error(a);null==n||n.debug(`${a}. ${Fi}`)}catch(e){const t=`Error fetching URL ${r} [${e.message}]`;if(s)throw new Error(t);null==n||n.debug(`${t}. ${Fi}`)}}})(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=$i||this.baseStaticUrl;if(t)return Bi({projectId:this.projectId,filename:e,baseUrl:t});const s=i(this,n,"f")!==this.baseUrl,a=s&&!!this.baseUrl;s&&(o(this,n,this.baseUrl,"f"),o(this,r,void 0,"f"));const l=Bi({projectId:this.projectId,filename:e,baseUrl:i(this,r,"f")});if(!a)return l;return[Bi({projectId:this.projectId,filename:e,baseUrl:this.baseUrl+"/pages"}),l]},a})),Ki=Ti((e=>{var t,n;const o=Ei(Ni({"project-id":Pi}))(e);return n=class extends o{constructor(){super(...arguments),t.set(this,new Map)}onReset(e,n){if(i(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} already exists`);return i(this,t,"f").set(e,n),()=>{i(this,t,"f").delete(e)}}async reset(...e){0===e.length?await Promise.all(Array.from(i(this,t,"f").values()).map((e=>e()))):await Promise.all(e.map((e=>{var n;if(!i(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} does not exist`);return null===(n=i(this,t,"f").get(e))||void 0===n?void 0:n()})))}},t=new WeakMap,n})),Hi=Ti((e=>{var t,n,r,s,a;const l=Ei(Vi,Ki,Di)(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",i(this,t,"m",n).bind(this))}get config(){return i(this,r,"f")||o(this,r,i(this,s,"f").call(this),"f"),i(this,r,"f")}},r=new WeakMap,s=new WeakMap,t=new WeakSet,n=function(){o(this,r,void 0,"f")},a})),Gi="load-descope-ui",Ji="base.ui.components.url",zi=_i&&localStorage.getItem(Ji)||"https://descopecdn.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Xi=_i&&localStorage.getItem(Ji)||"https://static.descope.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Qi=_i&&localStorage.getItem(Ji)||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Zi=e=>{const t=document.createElement("script");return t.id=e,t},Yi=(e,t)=>e.replace("<version>",t),eo=Ti((e=>{var t,n,r,s,a,l,c,d,u,h,p,g;const f=Ei(Li,Hi)(e);return g=class extends f{constructor(){super(...arguments),t.add(this),n.set(this,Symbol("errorCbs")),r.set(this,Symbol("loadCbs")),u.set(this,void 0)}get descopeUi(){return i(this,u,"f")||o(this,u,i(this,t,"m",p).call(this),"f"),i(this,u,"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=>i(this,t,"m",h).call(this,e))))}get baseCdnUrl(){return this.getAttribute("base-cdn-url")}},n=new WeakMap,r=new WeakMap,u=new WeakMap,t=new WeakSet,s=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},a=function(e){const t=i(this,n,"f"),o=i(this,r,"f");e[t]=[],e[o]=[],Object.defineProperty(e,"onerror",{set(n){e[t].push(n)}}),Object.defineProperty(e,"onload",{set(t){e[o].push(t)}})},l=async function(e,n,o,r){this.logger.debug("Trying to load DescopeUI from a fallback URL");const a=Zi(o);document.body.append(a),a.addEventListener("error",(()=>{e.forEach((e=>e(`Cannot load DescopeUI from fallback URL, Make sure this URL is valid and return the correct script: "${a.src}"`)))})),a.addEventListener("load",(()=>{n.forEach((e=>e()))})),a.src=Yi(r,await i(this,t,"m",s).call(this))},c=function(e){e.addEventListener("error",(()=>{e[i(this,n,"f")].forEach((t=>t(`Cannot load DescopeUI from main URL, Make sure this URL is valid and return the correct script: "${e.src}"`))),i(this,t,"m",l).call(this,[i(this,t,"m",l).bind(this,e[i(this,n,"f")],e[i(this,r,"f")],"load-descope-ui-fallback-script-2",Qi),...e[i(this,n,"f")]],e[i(this,r,"f")],"load-descope-ui-fallback-script",Xi)})),e.addEventListener("load",(()=>{e[i(this,r,"f")].forEach((e=>e()))}))},d=async function(){if(document.querySelector(`script#${Gi}`))this.logger.debug("DescopeUI loading script already exists",this);else{this.logger.debug("DescopeUI loading script does not exist, creating it",this);const e=Zi(Gi);document.body.append(e),i(this,t,"m",a).call(this,e),i(this,t,"m",c).call(this,e),e.src=Yi(this.baseCdnUrl||zi,await i(this,t,"m",s).call(this))}return document.getElementById(Gi)},h=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(", ")}"`)},p=function(){return new Promise((e=>{globalThis.DescopeUI&&e(globalThis.DescopeUI),i(this,t,"m",d).call(this).then((t=>{t.onerror=this.logger.error,t.onload=()=>{this.logger.debug("DescopeUI was loaded"),e(globalThis.DescopeUI)},setTimeout((()=>{globalThis.DescopeUI&&e(globalThis.DescopeUI)}))}))}))},g})),to="content-root",no="root",io=Ti((e=>class extends e{constructor(...e){var t,n,i,o;super(...e),this.attachShadow({mode:"open"}).innerHTML=`\n <div id="${no}">\n <div id="${to}"></div>\n </div>\n `;const r=new CSSStyleSheet;r.replaceSync(`\n #${no}, #${to} {\n height: 100%;\n }\n #${no} {\n position: relative;\n height: fit-content;\n }\n `),null!==(t=(o=this.shadowRoot).adoptedStyleSheets)&&void 0!==t||(o.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,r],this.contentRootElement=null===(n=this.shadowRoot)||void 0===n?void 0:n.getElementById(to),this.rootElement=null===(i=this.shadowRoot)||void 0===i?void 0:i.getElementById(no)}})),oo=(e,t)=>!!t&&"light"!==t&&"dark"!==t&&'Supported theme values are "light", "dark", or leave empty for using the OS theme',ro=Ti((e=>{var t,n,r,s,a,l,c,d,u,h,p,g,f,v;const m=Ei(Ni({theme:oo}),Vi,Di,eo,Hi,io,Mi)(e);return v=class extends m{constructor(){super(...arguments),t.add(this),n.set(this,void 0),r.set(this,void 0),p.set(this,(()=>{i(this,t,"m",g).call(this),i(this,f,"f").call(this,"os"===this.getAttribute("theme"))})),f.set(this,(e=>{var n,o,r;const s=e?"addEventListener":"removeEventListener";null===(r=null===(o=null===(n=window.matchMedia)||void 0===n?void 0:n.call(window,"(prefers-color-scheme: dark)"))||void 0===o?void 0:o[s])||void 0===r||r.call(o,"change",(()=>i(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)),i(this,t,"m",l).call(this),i(this,t,"m",c).call(this),i(this,p,"f").call(this),this.observeAttributes(["theme"],i(this,p,"f")),this.observeAttributes(["style-id"],(()=>{o(this,r,null,"f"),i(this,t,"m",u).call(this),i(this,t,"m",l).call(this),i(this,t,"m",c).call(this)}))}},n=new WeakMap,r=new WeakMap,p=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 i(this,r,"f")||(o(this,r,i(this,t,"m",s).call(this),"f"),i(this,r,"f").then((e=>this.logger.debug("Fetched theme",e)))),i(this,r,"f")},l=async function(){var e,r,s,l;const c=await i(this,t,"a",a);c&&(i(this,n,"f")||(o(this,n,new CSSStyleSheet,"f"),null!==(e=(l=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(l.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,i(this,n,"f")]),i(this,n,"f").replaceSync(((null===(r=null==c?void 0:c.light)||void 0===r?void 0:r.globals)||"")+((null===(s=null==c?void 0:c.dark)||void 0===s?void 0:s.globals)||"")))},c=async function(){var e,n;const o=Object.assign({},await i(this,t,"a",a));if(!o)return;const r=await this.descopeUi;(null==r?void 0:r.componentsThemeManager)&&(r.componentsThemeManager.themes={light:null===(e=null==o?void 0:o.light)||void 0===e?void 0:e.components,dark:null===(n=null==o?void 0:o.dark)||void 0===n?void 0:n.components})},d=async function(){var e,t;const{projectConfig:n}=await this.config||{},i=null===(e=null==n?void 0:n.styles)||void 0===e?void 0:e[this.styleId],o=null==n?void 0:n.cssTemplate,r=i||o;return null===(t=null==r?void 0:r[this.theme])||void 0===t?void 0:t.fonts},u=async function(){const e=await i(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")},h=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(){i(this,t,"m",u).call(this),i(this,t,"m",h).call(this)},v})),so=(e,t="")=>Object.keys(e).reduce(((n,i)=>{var o;if("object"==typeof e[i]&&null!==e[i]&&!(null===(o=e[i])||void 0===o?void 0:o.value))return Object.assign(Object.assign({},n),so(e[i],`${t+i}.`));const r="object"==typeof e[i]?e[i]:{value:e[i]},s=Object.assign(Object.assign({},n),{[t+i]:r,[`form.${t}${i}`]:r});return"displayName"===i?Object.assign(Object.assign({},s),{[`${t}fullName`]:r,[`form.${t}fullName`]:r}):s}),[]),ao=Ti((e=>{var t,n,o,r;return r=class extends e{constructor(){super(...arguments),t.add(this)}connectedCallback(){var e;i(this,t,"m",n).call(this)&&i(this,t,"m",o).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)},o=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 lo,co,uo,ho,po,go,fo,vo,mo,bo,wo,yo,ko,Io,So,Co,Oo,xo,jo,Ao,Uo,Eo,To;const Ro=Ei(ro,Vi,ao)(HTMLElement);class Lo extends Ro{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","nonce"]}constructor(e){super(),lo.add(this),uo.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),i(this,lo,"m",Uo).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)}},ho.set(this,new gi),po.set(this,new gi),go.set(this,{}),this.getComponentsContext=()=>i(this,go,"f"),this.nextRequestStatus=new gi({isLoading:!1}),fo.set(this,void 0),vo.set(this,{popstate:i(this,lo,"m",ko).bind(this),componentsContext:i(this,lo,"m",xo).bind(this)}),mo.set(this,void 0),this.getConfig=()=>n(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),o(this,mo,e,"f"),i(this,lo,"m",wo).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 so(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 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(),i=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=i.version)&&void 0!==t||(i.version=0),i}))}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),i(this,po,"f").subscribe(i(this,lo,"m",Ao).bind(this)),i(this,po,"f").update({isDebug:this.debug}),i(this,lo,"m",yo).call(this),i(this,lo,"m",To).call(this),yield i(this,lo,"m",Co).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");i(this,lo,"m",Eo).call(this);const{executionId:r,stepId:s,token:a,code:l,exchangeError:c,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthCodeChallenge:h,redirectAuthInitiator:p,ssoQueryParams:g}=ei(this.flowId,this.loggerWrapper);window.addEventListener("popstate",i(this,vo,"f").popstate),window.addEventListener("components-context",i(this,vo,"f").componentsContext),i(this,ho,"f").subscribe(i(this,lo,"m",So).bind(this)),i(this,ho,"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,exchangeError:c,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthCodeChallenge:h,redirectAuthInitiator:p},g)),o(this,uo,!0,"f")}))}disconnectedCallback(){i(this,ho,"f").unsubscribeAll(),i(this,po,"f").unsubscribeAll(),i(this,lo,"m",jo).call(this),window.removeEventListener("popstate",i(this,vo,"f").popstate),window.removeEventListener("components-context",i(this,vo,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&i(this,uo,"f")&&t!==n&&co.observedAttributes.includes(e)){i(this,lo,"m",yo).call(this);const o=null===t;"nonce"===e&&i(this,lo,"m",To).call(this),i(this,ho,"f").update((({stepId:t,executionId:i})=>{let r=t,s=i;return o||(s=null,r=null,Zn()),{[Yn(e)]:n,stepId:r,executionId:s}})),i(this,po,"f").update({isDebug:this.debug})}}}function _o(e,t){return`sdkScriptsResults.${t?`${e}_${t}`:e}`}var $o,Po,Do,Mo,No,Wo,qo,Fo,Bo,Vo,Ko,Ho,Go,Jo,zo,Xo,Qo,Zo,Yo,er,tr,nr,ir,or,rr,sr,ar,lr,cr,dr,ur,hr,pr,gr,fr,vr,mr,br,wr,yr;co=Lo,uo=new WeakMap,ho=new WeakMap,po=new WeakMap,go=new WeakMap,fo=new WeakMap,vo=new WeakMap,mo=new WeakMap,lo=new WeakSet,bo=function(){var e,t;const n=new CSSStyleSheet;n.replaceSync("\n :host {\n all: initial;\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 transition: opacity 300ms 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;\n\t\t}\n\n .hidden {\n display: none;\n }\n "),null!==(e=(t=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(t.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,n]},wo=function(){i(this,lo,"m",bo).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},yo=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","nonce"];co.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[Yn(t)])throw Error(`${t} cannot be empty`)}))},ko=function(){const{stepId:e,executionId:t}=Qn(this.flowId);i(this,ho,"f").update({stepId:e,executionId:t})},Io=function(e,t){this.sdk=gn(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},co.sdkConfigOverrides),{projectId:e,baseUrl:t})),["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()}}}}))}))},So=function(e,t,o){return n(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:n}=e;if(o("projectId")||o("baseUrl")){if(!t)return;i(this,lo,"m",Io).call(this,t,n)}i(this,mo,"f").call(this,e)}))},Co=function(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield i(this,lo,"m",Oo).call(this))}))},Oo=function(){return n(this,void 0,void 0,(function*(){const e=function({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:i}){const o=new URL(mn||i||"https://static.descope.com/pages");return o.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(o.pathname,e,n,t),o.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}}))},xo=function(e){o(this,go,Object.assign(Object.assign({},i(this,go,"f")),e.detail),"f")},jo=function(){var e;null===(e=i(this,fo,"f"))||void 0===e||e.remove(),o(this,fo,null,"f")},Ao=function(e){return n(this,arguments,void 0,(function*({isDebug:e}){e?(o(this,fo,document.createElement("descope-debugger"),"f"),Object.assign(i(this,fo,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Cr})),document.body.appendChild(i(this,fo,"f"))):i(this,lo,"m",jo).call(this)}))},Uo=function(e,t){var n;e&&this.debug&&(null===(n=i(this,fo,"f"))||void 0===n||n.updateData({title:e,description:t}))},Eo=function(){this.rootElement.onkeydown=e=>{var t,n,i;const o=!!(null===(t=this.shadowRoot.activeElement)||void 0===t?void 0:t.getAttribute("href")),r=Vn.includes(null!==(i=null===(n=this.shadowRoot.activeElement)||void 0===n?void 0:n.localName)&&void 0!==i?i:"");if("Enter"!==e.key||o||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()}}},To=function(){this.getAttribute("nonce")&&(window.DESCOPE_NONCE=this.getAttribute("nonce"))},Lo.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.40.2"}};class kr extends Lo{static set sdkConfigOverrides(e){Lo.sdkConfigOverrides=e}static get sdkConfigOverrides(){return Lo.sdkConfigOverrides}constructor(){const e=new gi({deferredRedirect:!1});super(e.update.bind(e)),$o.add(this),this.stepState=new gi({}),Po.set(this,void 0),Do.set(this,null),Mo.set(this,null),No.set(this,{visibilitychange:i(this,$o,"m",Wo).bind(this)}),this.bridgeVersion=1,this.nativeResume=(e,t)=>{var n;const o=JSON.parse(t);if(this.logger.info(`nativeResume received payload of type '${e}'`),"oauthWeb"===e||"sso"===e){let{exchangeCode:e}=o;if(!e){e=null===(n=new URL(o.url).searchParams)||void 0===n?void 0:n.get(yn)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(o.url),t=e.searchParams.get("t"),n=e.searchParams.get(wn).split("_").pop();i(this,Go,"f").call(this),this.flowState.update({token:t,stepId:n,action:void 0})}else this.nativeComplete(o)},Ko.set(this,(e=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e)})),Ho.set(this,((e,t,r,s,a=!1)=>{if(this.flowState.current.action===Dn){this.logger.debug("polling - Scheduling polling request");const l=Date.now(),c=a?500:2e3;o(this,Po,setTimeout((()=>n(this,void 0,void 0,(function*(){var n;this.logger.debug("polling - Calling next");const o=this.sdk.flow.next(e,t,Bn,r,s,{}),d=document.hidden&&!a&&Date.now()-l>c+500;let u;d&&this.logger.debug("polling - The polling seems to be throttled");try{const e=d?1e3:6e3;u=yield ni(e,o)}catch(n){return this.logger.warn(`polling - The ${d?"throttled fetch":"fetch"} call timed out or was aborted`),void i(this,Ho,"f").call(this,e,t,r,s,d)}if((null===(n=null==u?void 0:u.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 i(this,Ho,"f").call(this,e,t,r,s);this.logger.debug("polling - Got a response"),(null==u?void 0:u.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(u.error,null,4)),i(this,Ho,"f").call(this,e,t,r,s),i(this,Jo,"f").call(this,u)}))),c),"f")}})),Go.set(this,(()=>{clearTimeout(i(this,Po,"f")),o(this,Po,null,"f")})),Jo.set(this,(e=>{var t,n,r,s,a,l,c,d,u,h,p,g,f;if(!(null==e?void 0:e.ok)){const o=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}`;i(this,$o,"m",cr).call(this,"error",(null==e?void 0:e.error)||{errorCode:"J151001",errorDescription:c,errorMessage:o}),this.loggerWrapper.error((null===(s=null==e?void 0:e.error)||void 0===s?void 0:s.errorDescription)||o,(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&&"E103205"!==d||!this.isRestartOnError||i(this,$o,"m",Bo).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:i}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](n,i):this.loggerWrapper.info(n,i)}));const v=null===(p=null===(h=null===(u=e.data)||void 0===u?void 0:u.screen)||void 0===h?void 0:h.state)||void 0===p?void 0:p.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}=e.data;if(y!==Dn&&i(this,Go,"f").call(this),"completed"===m)return this.storeLastAuthenticatedUser&&function(e){(null==e?void 0:e.authMethod)&&fn&&localStorage.setItem(Sn,JSON.stringify(e))}(w),void i(this,$o,"m",cr).call(this,"success",b);const{executionId:k,stepId:I,stepName:S,screen:C,redirect:O,openInNewTabUrl:x,webauthn:j,error:A,samlIdpResponse:U,nativeResponse:E}=e.data,T=Date.now();y!==Dn?(this.loggerWrapper.info(`Step "${S||`#${I}`}" is ${m}`,"",{screen:C,status:m,stepId:I,stepName:S,action:y,error:A}),(null===(f=C.state)||void 0===f?void 0:f.clientScripts)&&o(this,Mo,this.loadSdkScripts(C.state.clientScripts),"f"),this.flowState.update({stepId:I,stepName:S,executionId:k,action:y,redirectTo:null==O?void 0:O.url,openInNewTabUrl:x,screenId:null==C?void 0:C.id,screenState:null==C?void 0:C.state,webauthnTransactionId:null==j?void 0:j.transactionId,webauthnOptions:null==j?void 0:j.options,samlIdpResponseUrl:null==U?void 0:U.url,samlIdpResponseSamlResponse:null==U?void 0:U.samlResponse,samlIdpResponseRelayState:null==U?void 0:U.relayState,nativeResponseType:null==E?void 0:E.type,nativePayload:null==E?void 0:E.payload,reqTimestamp:T})):this.flowState.update({action:y,reqTimestamp:T})})),zo.set(this,ti((()=>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)}}))))),rr.set(this,si(((e,t)=>n(this,void 0,void 0,(function*(){var n,o;if("true"===e.getAttribute("formnovalidate")||i(this,$o,"m",Yo).call(this)){const r=null==e?void 0:e.getAttribute("id");i(this,$o,"m",tr).call(this,e);const s=yield i(this,$o,"m",er).call(this),a=(o=e,Array.from((null==o?void 0:o.attributes)||[]).reduce(((e,t)=>{var n;const i=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return i?Object.assign(e,{[i]:t.value}):e}),{}));if(this.nextRequestStatus.update({isLoading:!0}),i(this,Mo,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield i(this,Mo,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const l=this.loadSdkScriptsModules();if(l.length>0){const e=l.filter((e=>"function"==typeof e.refresh)).map((e=>e.refresh()));e.length>0&&(yield ni(5e3,Promise.all(e),null))}const c=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},c),a),s),{origin:(null===(n=this.nativeOptions)||void 0===n?void 0:n.origin)||window.location.origin});yield t(r,d),this.nextRequestStatus.update({isLoading:!1}),i(this,$o,"m",nr).call(this,s)}}))))),this.flowState=e}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:{[_o(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 i=Promise.all(null==e?void 0:e.map((e=>n(this,void 0,void 0,(function*(){var i;const o=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(o){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=o;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}const r=yield function(e){return n(this,void 0,void 0,(function*(){let t;switch(e){case"forter":return t=yield Promise.resolve().then((function(){return xr})),t.default;case"fingerprint":return t=yield Promise.resolve().then((function(){return Ar})),t.default;case"fingerprintDescope":return t=yield Promise.resolve().then((function(){return Er})),t.default;case"grecaptcha":return t=yield Promise.resolve().then((function(){return Lr})),t.default;default:throw new Error(`Unknown script id: ${e}`)}}))}(e.id);return new Promise(((n,i)=>{try{const i=r(e.initArgs,{baseUrl:this.baseUrl},t(e,n));if(i){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=i,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=i.stop)||void 0===t||t.call(i)}))}}catch(e){i(e)}}))}))))),o=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),5e3)}));return Promise.race([i,o])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.isDescopeBridge)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)),i(this,$o,"m",Fo).call(this),window.addEventListener("visibilitychange",i(this,No,"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(),null===(e=i(this,Do,"f"))||void 0===e||e.abort(),o(this,Do,null,"f"),window.removeEventListener("visibilitychange",i(this,No,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return n(this,void 0,void 0,(function*(){let n;const i=ai(e),o=yield this.getTargetLocales();return o.includes(i.locale)?n=`${t}-${i.locale}.html`:o.includes(i.fallback)&&(n=`${t}-${i.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:h,executionId:p,action:g,screenId:f,screenState:v,redirectTo:m,openInNewTabUrl:b,redirectUrl:w,token:y,code:k,exchangeError:I,webauthnTransactionId:S,webauthnOptions:C,redirectAuthCodeChallenge:O,redirectAuthCallbackUrl:x,redirectAuthBackupCallbackUri:j,redirectAuthInitiator:A,locale:U,samlIdpResponseUrl:E,samlIdpResponseSamlResponse:T,samlIdpResponseRelayState:R,nativeResponseType:L,nativePayload:_,reqTimestamp:$}=e,P=t(e,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let D,M,N;const W=(()=>{const e=localStorage.getItem(ji);if(!e){const e=Math.floor(100*Math.random()+1);return localStorage.setItem(ji,e.toString()),e}return Number(e)})(),q=this.sdk.getLastUserLoginId(),F=yield this.getFlowConfig(),B=yield this.getProjectConfig(),V=Object.entries(B.flows||{}).reduce(((e,[t,n])=>(e[t]=n.version,e)),{}),K=x&&O?{callbackUrl:x,codeChallenge:O,backupCallbackUri:j}:void 0,H=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let G={};if(!p){const e=[...F.clientScripts||[],...F.sdkScripts||[]];if(F.conditions){let t=[];({startScreenId:D,conditionInteractionId:N,startScreenName:M,clientScripts:t,componentsConfig:G}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n,predicate:i})=>{var o;if("ELSE"===t)return!0;const r=null===(o=Ai[t])||void 0===o?void 0:o[n];return!!(null==r?void 0:r(e,i))}));return n?{startScreenId:n.met.screenId,startScreenName:n.met.screenName,conditionInteractionId:n.met.interactionId,clientScripts:n.met.clientScripts,componentsConfig:n.met.componentsConfig}:{}})({loginId:q,code:k,token:y,abTestingKey:W},F.conditions)),e.push(...t||[])}else F.condition?({startScreenId:D,conditionInteractionId:N}=((e,t)=>{var n;const i=null===(n=Ai[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!i)return{};const o=i(t,e.predicate)?e.met:e.unmet;return{startScreenId:null==o?void 0:o.screenId,startScreenName:null==o?void 0:o.screenName,conditionInteractionId:null==o?void 0:o.interactionId}})(F.condition,{loginId:q,code:k,token:y,abTestingKey:W})):(M=F.startScreenName,D=F.startScreenId);if(o(this,Mo,this.loadSdkScripts(e),"f"),F.fingerprintEnabled&&F.fingerprintKey?yield Ht(F.fingerprintKey,this.baseUrl):localStorage.removeItem(Vt),!ii(D,P)){const e=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:K},P),{client:this.client}),w&&{redirectUrl:w}),{lastAuth:Ui(q),abTestingKey:W,locale:ai(U).locale,nativeOptions:H}),N,"",B.componentsVersion,V,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),k?{exchangeCode:k,idpInitiated:!0}:{}),P.descopeIdpInitiated&&{idpInitiated:!0}),y?{token:y}:{}),P.oidcLoginHint?{externalId:P.oidcLoginHint}:{}));return i(this,Jo,"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(p&&(s("token")&&y||s("code")&&k||s("exchangeError")&&I)){const e=yield this.sdk.flow.next(p,h,Fn,F.version,B.componentsVersion,{token:y,exchangeCode:k,exchangeError:I});return i(this,Jo,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===qn&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>s(e)))){if(!E||!T)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,i)=>{const o=document.createElement("form");o.method="POST",o.action=e,o.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(o),i(o)})(E,T,R||"",oi)}if(g===Pn&&(s("redirectTo")||s("deferredRedirect")))return m?"android"===A&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(m):void this.loggerWrapper.error("Did not get redirect url");if(g===Mn||g===Nn){if(!S||!C)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(l=i(this,Do,"f"))||void 0===l||l.abort(),o(this,Do,null,"f");try{e=g===Mn?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(p,h,Fn,F.version,B.componentsVersion,{transactionId:S,response:e,failure:t});i(this,Jo,"f").call(this,n)}if(g===Wn)return this.nativeComplete=e=>n(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(p,h,Fn,F.version,B.componentsVersion,e);i(this,Jo,"f").call(this,t)})),void i(this,$o,"m",cr).call(this,"bridge",{type:L,payload:_});if(s("action")&&i(this,Ho,"f").call(this,p,h,F.version,B.componentsVersion),!f&&!D)return void this.loggerWrapper.warn("No screen was found to show");const J=D||f,z=yield this.getHtmlFilenameWithLocale(U,J),{oidcLoginHint:X,oidcPrompt:Q,oidcErrorRedirectUri:Z,samlIdpUsername:Y}=P,ee={direction:Xn(h,r.stepId),screenState:Object.assign(Object.assign({},v),{form:Object.assign(Object.assign({},this.formConfigValues),null==v?void 0:v.form),lastAuth:{loginId:q,name:this.sdk.getLastUserDisplayName()||q},componentsConfig:Object.assign(Object.assign(Object.assign({},F.componentsConfig),G),null==v?void 0:v.componentsConfig)}),htmlFilename:`${J}.html`,htmlLocaleFilename:z,screenId:J,stepName:e.stepName||M,samlIdpUsername:Y,oidcLoginHint:X,oidcPrompt:Q,oidcErrorRedirectUri:Z,openInNewTabUrl:b},te=Ui(q);ii(D,P)?ee.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:K},P),{lastAuth:te,preview:this.preview,abTestingKey:W,client:this.client}),w&&{redirectUrl:w}),{locale:ai(U).locale,nativeOptions:H}),N,e,B.componentsVersion,V,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),t),k&&{exchangeCode:k,idpInitiated:!0}),P.descopeIdpInitiated&&{idpInitiated:!0}),y&&{token:y}));return i(this,Jo,"f").call(this,n),n})):(s("projectId")||s("baseUrl")||s("executionId")||s("stepId"))&&(ee.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=yield this.sdk.flow.next(p,h,e,F.version,B.componentsVersion,t);return i(this,Jo,"f").call(this,n),n}))),this.loggerWrapper.debug("Got a screen with id",ee.screenId),yield i(this,$o,"m",Vo).call(this,ee),this.stepState.update(ee)}))}onStepChange(e,t){return n(this,void 0,void 0,(function*(){var o,r;const{htmlFilename:s,htmlLocaleFilename:a,direction:l,next:c,screenState:d,openInNewTabUrl:u}=e;this.loggerWrapper.debug("Rendering a flow screen");const h=document.createElement("template");h.innerHTML=yield this.getPageContent(s,a);const p=h.content.cloneNode(!0),g=this.loadDescopeUiComponents(h);this.sdk.webauthn.helpers.isSupported()?yield i(this,$o,"m",Qo).call(this,p,c):p.querySelectorAll(`descope-button[${$n}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(o=d.form)||void 0===o?void 0:o.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),Ci(p,d,d.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(p,f);const v=()=>n(this,void 0,void 0,(function*(){var n,o;yield g;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===(o=null==d?void 0:d.notp)||void 0===o?void 0:o.image),((e,t,n,i)=>{n&&Object.keys(n).forEach((o=>{t.querySelector(o)||i.debug(`Skipping css vars for component "${o}}"`,`Got css vars for component ${o} but Could not find it on next page`);const r=customElements.get(o);r?Object.keys(n[o]).forEach((t=>{var s;const a=n[o],l=null===(s=null==r?void 0:r.cssVarList)||void 0===s?void 0:s[t];if(!l)return void i.info(`Could not find css variable name for ${t} in ${o}`,"Check if the css variable is defined in the component");const c=a[t];e.style.setProperty(l,c)})):i.info(`Could not find component class for ${o}`,"Check if the component is registered")}))})(r,p,d.cssVars,this.loggerWrapper),r.replaceChildren(p);const l=!t.htmlFilename;setTimeout((()=>{i(this,$o,"m",ir).call(this),this.validateOnBlur&&(e=>{e.querySelectorAll("*[name]").forEach((e=>{e.addEventListener("blur",(()=>{var t;const n=e.focus;e.focus=()=>{},null===(t=e.reportValidity)||void 0===t||t.call(e),setTimeout((()=>{e.focus=n}))}))}))})(r),((e,t)=>{bi(e,null==t?void 0:t.inputs),bi(e,null==t?void 0:t.form)})(r,d),i(this,$o,"m",Zo).call(this,{isFirstScreen:l,stepName:e.stepName}),((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}})(r,this.autoFocus,l)})),i(this,$o,"m",ar).call(this,c);r.querySelector(`[${$n}="polling"]`)&&c(Bn,{}),u&&!t.openInNewTabUrl&&window.open(u,"_blank")}));l?i(this,$o,"m",lr).call(this,v,l):v()}))}}Po=new WeakMap,Do=new WeakMap,Mo=new WeakMap,No=new WeakMap,Ko=new WeakMap,Ho=new WeakMap,Go=new WeakMap,Jo=new WeakMap,zo=new WeakMap,rr=new WeakMap,$o=new WeakSet,Wo=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},qo=function({errorText:e,errorType:t}){const n=()=>{var n;let i=e;try{i=(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(`[${$n}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(this.contentRootElement,"error-message",i)};this.addEventListener("screen-updated",n,{once:!0}),n()},Fo=function(){var e,n;null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this),(e=>{var n=e.screenState,i=t(void 0===n?{}:n,["errorText","errorType"]),o=t(e,["screenState"]);return Object.assign(Object.assign({},o),{screenState:i})})),null===(n=this.stepState)||void 0===n||n.subscribe(i(this,$o,"m",qo).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}}))},Bo=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")}))},Vo=function(e){return n(this,void 0,void 0,(function*(){var n;const o=Object.assign(Object.assign({},this.stepState.current),e),{next:r,stepName:s}=o,a=t(o,["next","stepName"]),l=Boolean(yield null===(n=this.onScreenUpdate)||void 0===n?void 0:n.call(this,s,li(a),r,this));if(l){this.loggerWrapper.debug("Rendering a custom screen"),this.contentRootElement.innerHTML="",i(this,$o,"m",Zo).call(this,{isFirstScreen:!this.stepState.current.htmlFilename,stepName:e.stepName}),this.stepState.unsubscribeAll();const t=this.stepState.subscribe((()=>{this.stepState.unsubscribe(t),i(this,$o,"m",Fo).call(this)}))}this.stepState.forceUpdate=l,i(this,Ko,"f").call(this,l)}))},Xo=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)}))}},Qo=function(e,t){return n(this,void 0,void 0,(function*(){var r;null===(r=i(this,Do,"f"))||void 0===r||r.abort();const s=e.querySelector('*[autocomplete="webauthn"]');if(s&&(yield Oi())){const{options:e,transactionId:r}=(yield i(this,zo,"f").call(this))||{};e&&r&&(i(this,$o,"m",Xo).call(this,s),o(this,Do,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(e,i(this,Do,"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)})))}}))},Zo=function({isFirstScreen:e,stepName:t}){e&&i(this,$o,"m",cr).call(this,"ready",{}),i(this,$o,"m",cr).call(this,"page-updated",{screenName:t}),i(this,$o,"m",cr).call(this,"screen-updated",{screenName:t})},Yo=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var n,i;"slot"!==t.localName&&(null===(n=t.reportValidity)||void 0===n||n.call(t),e&&(e=null===(i=t.checkValidity)||void 0===i?void 0:i.call(t)))})),e},er=function(){return n(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${kn}])`));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})),{})}))},tr=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},nr=function(e={}){var t,n;const i=ri(e,["externalId","email","phone"]),o=ri(e,["newPassword","password"]);if(i&&o)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:i,password:o});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)}},ir=function(){document.querySelectorAll('[data-hidden-input="true"]').forEach((e=>e.remove()));this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((e=>i(this,$o,"m",or).call(this,e)))},or=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const n=t.getAttribute("slot"),i=`input-${e.id}-${n}`,o=document.createElement("slot");o.setAttribute("name",i),o.setAttribute("slot",n),e.appendChild(o),t.setAttribute("slot",i),this.appendChild(t)}))},sr=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))&&i(this,rr,"f").call(this,t,e)}))}))},ar=function(e){this.contentRootElement.querySelectorAll(`descope-button:not([${In}]), [data-type="button"]:not([${In}]`).forEach((t=>{t.onclick=()=>{i(this,rr,"f").call(this,t,e)}})),i(this,$o,"m",sr).call(this,e),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${kn}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},lr=function(e,t){this.contentRootElement.addEventListener("transitionend",(()=>{this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===Hn.forward?"slide-forward":"slide-backward";Array.from(this.contentRootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(n)})),this.contentRootElement.classList.add("fade-out")},cr=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.get("descope-wc")?console.log("descope-wc is already defined"):customElements.define("descope-wc",kr);const Ir=document.createElement("template");Ir.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';class Sr extends HTMLElement{constructor(){super(),dr.add(this),ur.set(this,new gi({messages:[]})),hr.set(this,void 0),pr.set(this,void 0),gr.set(this,void 0),fr.set(this,{resize:i(this,dr,"m",yr).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Ir.content.cloneNode(!0)),o(this,hr,this.shadowRoot.querySelector(".debugger"),"f"),o(this,pr,i(this,hr,"f").querySelector(".content"),"f"),o(this,gr,i(this,hr,"f").querySelector(".header"),"f"),i(this,dr,"m",vr).call(this)}updateData(e){i(this,ur,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let i=0,o=0,r=0,s=0;function a(t){t.preventDefault(),i=r-t.clientX,o=s-t.clientY,r=t.clientX,s=t.clientY;const[a,l]=xi(e,e.offsetLeft-i,e.offsetTop-o,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})(i(this,hr,"f"),i(this,gr,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",i(this,fr,"f").resize),(e=i(this,hr,"f")).onmousemove=t=>{(t.target.w&&t.target.w!==t.target.offsetWidth||t.target.h&&t.target.h!==t.target.offsetHeight)&&e.onresize(t),t.target.w=t.target.offsetWidth,t.target.h=t.target.offsetHeight},i(this,hr,"f").onresize=i(this,dr,"m",wr).bind(this),i(this,ur,"f").subscribe(i(this,dr,"m",mr).bind(this))}disconnectedCallback(){i(this,ur,"f").unsubscribeAll(),window.removeEventListener("resize",i(this,fr,"f").resize)}}ur=new WeakMap,hr=new WeakMap,pr=new WeakMap,gr=new WeakMap,fr=new WeakMap,dr=new WeakSet,vr=function(){var e,t;const n=new CSSStyleSheet;n.replaceSync('\n .debugger {\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'),null!==(e=(t=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(t.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,n],i(this,hr,"f").style.top="32px",i(this,hr,"f").style.left=window.innerWidth-300-32+"px"},mr=function(e){i(this,dr,"m",br).call(this,e),i(this,dr,"m",wr).call(this)},br=function(e){i(this,pr,"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("")},wr=function(){i(this,pr,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,i=t.clientHeight>20;n||i?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},yr=function(){const[e,t]=xi(i(this,hr,"f"),Number.parseInt(i(this,hr,"f").style.left,10),Number.parseInt(i(this,hr,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});i(this,hr,"f").style.top=`${t}px`,i(this,hr,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",Sr);var Cr=Object.freeze({__proto__:null,default:Sr});const Or='\n(function () {\nvar merchantConfig = {\n csp: false\n};\n\nvar siteId = "{{SITE_ID}}";\nfunction t(t,n){for(var e=t.split(""),r=0;r<e.length;++r)e[r]=String.fromCharCode(e[r].charCodeAt(0)+n);return e.join("")}function n(n){return t(n,-L).replace(/%SN%/g,siteId)}function e(){var t="no"+"op"+"fn",n="g"+"a",e="n"+"ame";return window[n]&&window[n][e]===t}function r(){return!(!navigator.brave||"function"!=typeof navigator.brave.isBrave)}function o(){return document.currentScript&&document.currentScript.src}function i(t){try{if("number"==typeof t&&window.location&&window.location.pathname){for(var n=window.location.pathname.split("/"),e=[],r=0;r<=Math.min(n.length-1,Math.abs(t));r++)e.push(n[r]);return e.join("/")||"/"}}catch(t){}return"/"}function c(t){try{G.ex=t,e()&&-1===G.ex.indexOf(B.uB)&&(G.ex+=B.uB),r()&&-1===G.ex.indexOf(B.uBr)&&(G.ex+=B.uBr),o()&&-1===G.ex.indexOf(B.nIL)&&(G.ex+=B.nIL),window.ftr__snp_cwc||(G.ex+=B.s),M(G)}catch(t){}}function a(t,n){function e(o){try{o.blockedURI===t&&(n(),document.removeEventListener(r,e))}catch(t){document.removeEventListener(r,e)}}var r="securitypolicyviolation";document.addEventListener(r,e),setTimeout(function(){document.removeEventListener(r,e)},2*60*1e3)}function u(t,n,e,r){var o=!1;t="https://"+t,a(t,function(){r(!0),o=!0});var i=document.createElement("script");i.onerror=function(){if(!o)try{r(!1),o=!0}catch(t){}},i.onload=e,i.type="text/javascript",i.id="ftr__script",i.async=!0,i.src=t;var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(i,c)}function f(){J(B.uDF),setTimeout(h,I,B.uDF)}function d(t,n,e,r){var o=!1,i=new XMLHttpRequest;if(a("https:"+t,function(){e(new Error("CSP Violation"),!0),o=!0}),"//"===t.slice(0,2)&&(t="https:"+t),"withCredentials"in i)i.open("GET",t,!0);else{if("undefined"==typeof XDomainRequest)return;i=new XDomainRequest,i.open("GET",t)}Object.keys(r).forEach(function(t){i.setRequestHeader(t,r[t])}),i.onload=function(){"function"==typeof n&&n(i)},i.onerror=function(t){if("function"==typeof e&&!o)try{e(t,!1),o=!0}catch(t){}},i.onprogress=function(){},i.ontimeout=function(){"function"==typeof e&&e("tim"+"eo"+"ut",!1)},setTimeout(function(){i.send()},0)}function s(t,siteId,n){function e(t){var n=t.toString(16);return n.length%2?"0"+n:n}function r(t){if(t<=0)return"";for(var n="0123456789abcdef",e="",r=0;r<t;r++)e+=n[Math.floor(Math.random()*n.length)];return e}function o(t){for(var n="",r=0;r<t.length;r++)n+=e(t.charCodeAt(r));return n}function i(t){for(var n=t.split(""),e=0;e<n.length;++e)n[e]=String.fromCharCode(255^n[e].charCodeAt(0));return n.join("")}n=n?"1":"0";var c=[];return c.push(t),c.push(siteId),c.push(n),function(t){var n=40,e="";return t.length<n/2&&(e=","+r(n/2-t.length-1)),o(i(t+e))}(c.join(","))}function w(){function t(){D&&(J(B.dUAL),setTimeout(h,I,B.dUAL))}function n(t,n){c(n?B.uAS+B.uF+B.cP:B.uAS+B.uF)}window.ftr__fdad(t,n)}function h(t){try{var n;switch(t){case B.uFP:n=q;break;case B.uDF:n=E;break;default:n=D}if(!n)return;u(n,void 0,function(){try{K(),c(t+B.uS)}catch(t){}},function(n){try{K(),G.td=1*new Date-G.ts,c(n?t+B.uF+B.cP:t+B.uF),t===B.uFP&&f(),t===B.uDF&&w()}catch(t){c(B.eUoe)}})}catch(n){c(t+B.eTlu)}}var m="22ge:t7mj8unkn;1forxgiurqw1qhw2vwdwxv",v="fort",l="erTo",p="ken";window.ftr__config={m:merchantConfig,s:"23",si:siteId};var g=!1,_=v+l+p,y=400*24*60,T=10,k={write:function(t,n,e,r){void 0===r&&(r=!0);var o=0;window.ftr__config&&window.ftr__config.m&&window.ftr__config.m.ckDepth&&(o=window.ftr__config.m.ckDepth);var c,a,u=i(o);if(e?(c=new Date,c.setTime(c.getTime()+60*e*1e3),a="; expires="+c.toGMTString()):a="",!r)return void(document.cookie=escape(t)+"="+escape(n)+a+"; path="+u);for(var f=1,d=document.domain.split("."),s=T,w=!0;w&&d.length>=f&&s>0;){var h=d.slice(-f).join(".");document.cookie=escape(t)+"="+escape(n)+a+"; path="+u+"; domain="+h;var m=k.read(t);null!=m&&m==n||(h="."+h,document.cookie=escape(t)+"="+escape(n)+a+"; path="+u+"; domain="+h),w=-1===document.cookie.indexOf(t+"="+n),f++,s--}},read:function(t){var n=null;try{for(var e=escape(t)+"=",r=document.cookie.split(";"),o=32,i=0;i<r.length;i++){for(var c=r[i];c.charCodeAt(0)===o;)c=c.substring(1,c.length);0===c.indexOf(e)&&(n=unescape(c.substring(e.length,c.length)))}}finally{return n}}},S=window.ftr__config.s;S+="ck";var x=function(t){var n=!1,e=null,r=function(){try{if(!e||!n)return;e.remove&&"function"==typeof e.remove?e.remove():document.head.removeChild(e),n=!1}catch(t){}};document.head&&(!function(){e=document.createElement("link"),e.setAttribute("rel","pre"+"con"+"nect"),e.setAttribute("cros"+"sori"+"gin","anonymous"),e.onload=r,e.onerror=r,e.setAttribute("href",t),document.head.appendChild(e),n=!0}(),setTimeout(r,3e3))},L=3,A=n(m||"22ge:t7mj8unkn;1forxgiurqw1qhw2vwdwxv"),F=t("[0Uhtxhvw0LG",-L),U=t("[0Fruuhodwlrq0LG",-L),b=t("Li0Qrqh0Pdwfk",-L),D,C="fgq71iruwhu1frp",E=n("(VQ(1"+C+"2vq2(VQ(2vfulsw1mv"),V=n("(VQ(1"+C+"2vqV2(VQ(2vfulsw1mv"),q;window.ftr__config&&window.ftr__config.m&&window.ftr__config.m.fpi&&(q=window.ftr__config.m.fpi+n("2vq2(VQ(2vfulsw1mv"));var I=10;window.ftr__startScriptLoad=1*new Date;var R=function(t){var n="ft"+"r:tok"+"enR"+"eady";window.ftr__tt&&clearTimeout(window.ftr__tt),window.ftr__tt=setTimeout(function(){try{delete window.ftr__tt,t+="_tt";var e=document.createEvent("Event");e.initEvent(n,!1,!1),e.detail=t,document.dispatchEvent(e)}catch(t){}},1e3)},M=function(t){var n=function(t){return t||""},e=n(t.id)+"_"+n(t.ts)+"_"+n(t.td)+"_"+n(t.ex)+"_"+n(S),r=y;!isNaN(window.ftr__config.m.ckTTL)&&window.ftr__config.m.ckTTL&&(r=window.ftr__config.m.ckTTL),k.write(_,e,r,!0),R(e),window.ftr__gt=e},P=function(){var t=k.read(_)||"",n=t.split("_"),e=function(t){return n[t]||void 0};return{id:e(0),ts:e(1),td:e(2),ex:e(3),vr:e(4)}},j=function(){for(var t={},n="fgu",e=[],r=0;r<256;r++)e[r]=(r<16?"0":"")+r.toString(16);var o=function(t,n,r,o,i){var c=i?"-":"";return e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]+c+e[255&n]+e[n>>8&255]+c+e[n>>16&15|64]+e[n>>24&255]+c+e[63&r|128]+e[r>>8&255]+c+e[r>>16&255]+e[r>>24&255]+e[255&o]+e[o>>8&255]+e[o>>16&255]+e[o>>24&255]},i=function(){if(window.Uint32Array&&window.crypto&&window.crypto.getRandomValues){var t=new window.Uint32Array(4);return window.crypto.getRandomValues(t),{d0:t[0],d1:t[1],d2:t[2],d3:t[3]}}return{d0:4294967296*Math.random()>>>0,d1:4294967296*Math.random()>>>0,d2:4294967296*Math.random()>>>0,d3:4294967296*Math.random()>>>0}},c=function(){var t="",n=function(t,n){for(var e="",r=t;r>0;--r)e+=n.charAt(1e3*Math.random()%n.length);return e};return t+=n(2,"0123456789"),t+=n(1,"123456789"),t+=n(8,"0123456789")};return t.safeGenerateNoDash=function(){try{var t=i();return o(t.d0,t.d1,t.d2,t.d3,!1)}catch(t){try{return n+c()}catch(t){}}},t.isValidNumericalToken=function(t){return t&&t.toString().length<=11&&t.length>=9&&parseInt(t,10).toString().length<=11&&parseInt(t,10).toString().length>=9},t.isValidUUIDToken=function(t){return t&&32===t.toString().length&&/^[a-z0-9]+$/.test(t)},t.isValidFGUToken=function(t){return 0==t.indexOf(n)&&t.length>=12},t}(),B={uDF:"UDF",dUAL:"dUAL",uAS:"UAS",uFP:"UFP",mLd:"1",eTlu:"2",eUoe:"3",uS:"4",uF:"9",tmos:["T5","T10","T15","T30","T60"],tmosSecs:[5,10,15,30,60],bIR:"43",uB:"u",uBr:"b",cP:"c",nIL:"i",s:"s"};try{var G=P();try{G.id&&(j.isValidNumericalToken(G.id)||j.isValidUUIDToken(G.id)||j.isValidFGUToken(G.id))?window.ftr__ncd=!1:(G.id=j.safeGenerateNoDash(),window.ftr__ncd=!0),G.ts=window.ftr__startScriptLoad,M(G),window.ftr__snp_cwc=!!k.read(_),window.ftr__snp_cwc||(E=V);for(var N="for"+"ter"+".co"+"m",O="ht"+"tps://c"+"dn9."+N,Q="ht"+"tps://"+G.id+"-"+siteId+".cd"+"n."+N,H="http"+"s://cd"+"n3."+N,X=[O,Q,H],z=0;z<X.length;z++)x(X[z]);var $=new Array(B.tmosSecs.length),J=function(t){for(var n=0;n<B.tmosSecs.length;n++)$[n]=setTimeout(c,1e3*B.tmosSecs[n],t+B.tmos[n])},K=function(){for(var t=0;t<B.tmosSecs.length;t++)clearTimeout($[t])};window.ftr__fdad=function(n,e){if(!g){g=!0;var r={};r[b]=s(window.ftr__config.s,siteId,window.ftr__config.m.csp),d(A,function(e){try{var r=e.getAllResponseHeaders().toLowerCase();if(r.indexOf(U.toLowerCase())>=0){var o=e.getResponseHeader(U);window.ftr__altd2=t(atob(o),-L-1)}if(r.indexOf(F.toLowerCase())<0)return;var i=e.getResponseHeader(F),c=t(atob(i),-L-1);if(c){var a=c.split(":");if(a&&2===a.length){for(var u=a[0],f=a[1],d="",s=0,w=0;s<20;++s)d+=s%3>0&&w<12?siteId.charAt(w++):G.id.charAt(s);var h=f.split(",");if(h.length>1){var m=h[0],v=h[1];D=u+"/"+m+"."+d+"."+v}}}n()}catch(t){}},function(t,n){e&&e(t,n)},r)}};var W=q?B.uFP:B.uDF;J(W),setTimeout(h,I,W)}catch(t){c(B.mLd)}}catch(t){}})();\n';var xr=Object.freeze({__proto__:null,default:(e,t,i)=>n(void 0,void 0,void 0,(function*(){const{siteId:t}=e,n=Or.replace(/{{SITE_ID}}/g,t),o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("id",t),o.text=n,document.body.appendChild(o),document.addEventListener("ftr:tokenReady",(e=>{i(e.detail)}))}))});const jr=(e,t,i)=>n(void 0,void 0,void 0,(function*(){try{const{publicApiKey:t,useCloudflareIntegration:n,cloudflareScriptUrl:o,cloudflareEndpointUrl:r}=e;let s=[];s=n&&r?[r,ft]:[ft];let a=[];if(n&&o){const e=new URL(o);a=[`${e.toString()}?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>`,It]}else a=[It];const l=St({apiKey:t,endpoint:s,scriptUrlPattern:a}),c=yield l,{requestId:d}=yield c.get();i(d)}catch(e){console.warn("Could not load fingerprint",e)}}));var Ar=Object.freeze({__proto__:null,default:jr,loadFingerprint:jr});const Ur=(e,t,i)=>n(void 0,void 0,void 0,(function*(){try{const{customDomain:n,publicApiKey:o,cloudflareEndpointPath:r,cloudflareScriptPath:s}=e,{baseUrl:a}=t;let l;l=n?`https://${n}`:a||"https://api.descope.com";const c=new URL(l);c.pathname=r;const d=new URL(l);d.pathname=s;const u=`${d.toString()}?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>`,h=St({apiKey:o,endpoint:[c.toString(),ft],scriptUrlPattern:[u,It]}),p=yield h,{requestId:g}=yield p.get();i(g)}catch(e){console.warn("Could not load descope fingerprint",e)}}));var Er=Object.freeze({__proto__:null,default:Ur,loadFingerprint:Ur});const Tr=105e3,Rr=(e,t,i)=>{let o=(new Date).getTime();const r=()=>{var t;return e.enterprise?null===(t=window.grecaptcha)||void 0===t?void 0:t.enterprise:window.grecaptcha};let s,a;const l=(t,n)=>{t.ready((()=>{e.siteKey&&(null==t||t.execute(a,{action:"load"}).then(((e,n)=>{n?console.warn("could not execute recaptcha",n):(i(e),o=(new Date).getTime(),s=setTimeout((()=>{l(t)}),Tr))})))}))},c=()=>{clearTimeout(s)},d=(()=>{const e=document.createElement("div");return e.style.display="none",e.id="recaptcha",document.body.appendChild(e)})(),u=()=>{const e=r();e&&l(e)};return window.onRecaptchaLoadCallback=()=>{const t=d;if(t.hasChildNodes())return;const n=r();n&&setTimeout((()=>{a=n.render(t,{sitekey:e.siteKey,badge:"inline",size:"invisible"}),l(n)}),0)},(()=>{const t=document.createElement("script");t.src=(()=>{const t=new URL("https://www.google.com/recaptcha/");return t.pathname+=(e.enterprise?"enterprise":"api")+".js",t.searchParams.append("onload","onRecaptchaLoadCallback"),t.searchParams.append("render","explicit"),t.toString()})(),t.async=!0,t.id="recaptcha-script",t.defer=!0,document.body.appendChild(t)})(),{stop:c,start:u,refresh:()=>n(void 0,void 0,void 0,(function*(){if(Date.now()-o>Tr){c();const e=o;return u(),new Promise((t=>{const n=setTimeout((()=>{console.warn("reCAPTCHA token refresh timed out"),t()}),5e3),i=()=>{o!==e?(clearTimeout(n),t()):setTimeout(i,150)};i()}))}return Promise.resolve()}))}};var Lr=Object.freeze({__proto__:null,default:Rr,loadGRecaptcha:Rr})}();
|
|
3
|
+
function pt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)e[i]=n[i]}return e}var gt=function e(t,n){function i(e,i,s){if("undefined"!=typeof document){"number"==typeof(s=pt({},n,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var r="";for(var o in s)s[o]&&(r+="; "+o,!0!==s[o]&&(r+="="+s[o].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+r}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],i={},s=0;s<n.length;s++){var r=n[s].split("="),o=r.slice(1).join("=");try{var a=decodeURIComponent(r[0]);if(i[a]=t.read(o,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",pt({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,pt({},this.attributes,t))},withConverter:function(t){return e(pt({},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 ft={default:"endpoint"},mt="Blocked by CSP",wt="The endpoint parameter is not a valid URL",vt="Failed to load the JS script of the agent",_t="9319";function yt(e,t){var n,i,s,r,o,a=[],c=(n=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var i,s=0,r=t.length;s<r;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||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,i=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,r++))},s=new Set,[n.current(),function(e,t){var r,o=t instanceof Error?t.message:"";if(o===mt||o===wt)n.exclude(),r=0;else if(o===_t)n.exclude();else if(o===vt){var a=Date.now()-e.getTime()<50,c=n.current();c&&a&&!s.has(c)&&(s.add(c),r=0),n.postpone()}else n.postpone();var l=n.current();return void 0===l?void 0:[l,null!=r?r:e.getTime()+i()-Date.now()]}]),l=c[0],d=c[1];if(void 0===l)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var u=function(e){var n=new Date,i=function(t){return a.push({url:e,startedAt:n,finishedAt:new Date,error:t})},s=t(e);return s.then((function(){return i()}),i),s.catch((function(e){if(null!=o||(o=e),a.length>=5)throw o;var t=d(n,e);if(!t)throw o;var i,s=t[0],r=t[1];return(i=r,new Promise((function(e){return setTimeout(e,i)}))).then((function(){return u(s)}))}))};return u(l).then((function(e){return[e,a]}))}var bt="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",St=bt;function kt(n){var i;n.scriptUrlPattern;var s=n.token,r=n.apiKey,o=void 0===r?s:r,a=t(n,["scriptUrlPattern","token","apiKey"]),c=null!==(i=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(n,"scriptUrlPattern"))&&void 0!==i?i:bt,l=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,i){return e.addEventListener(t,n,i),function(){return e.removeEventListener(t,n,i)}}(document,"visibilitychange",t);return t(),[e,n]}(),d=l[0],u=l[1];return Promise.resolve().then((function(){if(!o||"string"!=typeof o)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)}))}(c,o);return yt(e,It)})).catch((function(e){throw u(),function(e){return e instanceof Error&&e.message===_t?new Error(vt):e}(e)})).then((function(t){var n=t[0],i=t[1];return u(),n.load(e(e({},a),{ldi:{attempts:i,visibilityStates:d}}))}))}function It(e){return function(e,t,n){var i,s=document,r="securitypolicyviolation",o=function(t){var n=new URL(e,location.href),s=t.blockedURI;s!==n.href&&s!==n.protocol.slice(0,-1)&&s!==n.origin||(i=t,a())};s.addEventListener(r,o);var a=function(){return s.removeEventListener(r,o)};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(),i)return n(i);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(wt);var i=document.createElement("script"),s=function(){var e;return null===(e=i.parentNode)||void 0===e?void 0:e.removeChild(i)},r=document.head||document.getElementsByTagName("head")[0];i.onload=function(){s(),t()},i.onerror=function(){s(),n(new Error(vt))},i.async=!0,i.src=e,r.appendChild(i)}))}(e)}),(function(){throw new Error(mt)})).then(xt)}function xt(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,i=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==i?void 0:i.configurable)?delete e[t]:i&&!i.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(_t);return n}const Ct=e=>{try{return a(e).exp}catch(e){return null}},Et=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:Ct(n)},Tt=e=>{const{expires_in:t,expires_at:n,access_token:i}=e;return n||(t?Math.floor(Date.now()/1e3)+t:i?Ct(i):void 0)},Ot=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,i)=>{var s;return n[i]=[].concat((null===(s=e.hooks)||void 0===s?void 0:s[i])||[]).concat((null==t?void 0:t[i])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},Ut=async e=>{if(!(null==e?void 0:e.ok))return{};const n=await(null==e?void 0:e.clone().json());return(e=>{const{access_token:n,id_token:i,refresh_token:s,refresh_expire_in:r}=e,o=t(e,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:e.sessionJwt||n,idToken:i,refreshJwt:e.refreshJwt||s,sessionExpiration:e.sessionExpiration||Tt(e),cookieExpiration:e.cookieExpiration||Et(e)},o)})((null==n?void 0:n.authInfo)||n||{})},Rt=async e=>{const t=await Ut(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},At="undefined"!=typeof localStorage,jt=(e,t)=>At&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),Pt=e=>At&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Lt=e=>At&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),qt=(...e)=>{console.debug(...e)},$t="3.2.0",Nt="undefined"!=typeof window,Mt=Math.pow(2,31)-1,Dt=`https://descopecdn.com/npm/oidc-client-ts@${$t}/dist/browser/oidc-client-ts.min.js`,Wt=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${$t}/dist/browser/oidc-client-ts.min.js`,Ft="DS",Ht="DSR",Kt="DSI";function Jt(e=""){return Pt(`${e}${Ht}`)||""}function Bt(e=""){return gt.get(Ft)||Pt(`${e}${Ft}`)||""}function Vt(e=""){return Pt(`${e}${Kt}`)||""}function zt(e=""){Lt(`${e}${Ht}`),Lt(`${e}${Ft}`),Lt(`${e}${Kt}`),gt.remove(Ft)}const Gt=Nt&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",Qt="vsid",Xt="vrid",Zt="fp",Yt=(e=!1)=>{const t=localStorage.getItem(Zt);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},en=async(e,t=Gt)=>{try{if(Yt())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const s=new URL(t);s.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const r=s.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",o=kt({apiKey:e,endpoint:[i.toString(),ft],scriptUrlPattern:[r,St]}),a=await o,{requestId:c}=await a.get({linkedId:n}),l=((e,t)=>({[Qt]:e,[Xt]:t}))(n,c);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem(Zt,JSON.stringify(t))})(l)}catch(e){console.warn("Could not load fingerprint",e)}},tn=e=>{const t=Yt(!0);return t&&e.body&&(e.body.fpData=t),e},nn="dls_last_user_login_id",sn="dls_last_user_display_name",rn=()=>Pt(nn),on=()=>Pt(sn),an=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,i={}]=t,s=rn(),r=on();return s&&(null!==(n=i.lastAuth)&&void 0!==n||(i.lastAuth={}),i.lastAuth.loginId=s,i.lastAuth.name=r),await e(...t)};function cn(){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 ln(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=fn(n.publicKey.challenge),n.publicKey.user.id=fn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=fn(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:mn(n.rawId),type:n.type,response:{attestationObject:mn(n.response.attestationObject),clientDataJSON:mn(n.response.clientDataJSON)}});var n}async function dn(e){const t=pn(e);return gn(await navigator.credentials.get(t))}async function un(e,t){const n=pn(e);return n.signal=t.signal,n.mediation="conditional",gn(await navigator.credentials.get(n))}async function hn(e=!1){if(!Nt)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 pn(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=fn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=fn(e.id)})),n}function gn(e){return JSON.stringify({id:e.id,rawId:mn(e.rawId),type:e.type,response:{authenticatorData:mn(e.response.authenticatorData),clientDataJSON:mn(e.response.clientDataJSON),signature:mn(e.response.signature),userHandle:e.response.userHandle?mn(e.response.userHandle):void 0}})}function fn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function mn(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var wn,vn=(wn=e=>({async signUp(t,n,i){const s=await e.webauthn.signUp.start(t,window.location.origin,n,i);if(!s.ok)return s;const r=await ln(s.data.options);return await e.webauthn.signUp.finish(s.data.transactionId,r)},async signIn(t,n){const i=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!i.ok)return i;const s=await dn(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,s)},async signUpOrIn(t,n){var i;const s=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!s.ok)return s;if(null===(i=s.data)||void 0===i?void 0:i.create){const t=await ln(s.data.options);return await e.webauthn.signUp.finish(s.data.transactionId,t)}{const t=await dn(s.data.options);return await e.webauthn.signIn.finish(s.data.transactionId,t)}},async update(t,n,i){const s=await e.webauthn.update.start(t,window.location.origin,n,i);if(!s.ok)return s;const r=await ln(s.data.options);return await e.webauthn.update.finish(s.data.transactionId,r)},helpers:{create:ln,get:dn,isSupported:hn,conditional:un}}),(...e)=>{const t=wn(...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 _n="/fedcm/config";async function yn(e,t){var n,i,s;try{const s=await async function(e,t="google",n,i,s){const r=(()=>{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)})(),o=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 c=a.data.clientId;return new Promise((e=>{var a,l;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};o.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===(l=null==n?void 0:n.use_fedcm_for_prompt)||void 0===l||l,client_id:c,callback:d,nonce:r})),o.prompt((e=>{var t,n;if(s&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==s||s(n),void d()}if(i&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==i||i(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!s.credential)return null;if(null==t?void 0:t.onCodeReceived){const i=await e.oauth.verifyOneTapIDToken(s.provider,s.credential,s.nonce,null==t?void 0:t.loginOptions);if(!i.ok||!i.data)throw new Error("Failed to verify OneTap client ID for provider "+s.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,i.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(s.provider,s.credential,s.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+s.provider);null===(i=null==t?void 0:t.onAuthenticated)||void 0===i||i.call(t,n.data)}}catch(e){null===(s=null==t?void 0:t.onFailed)||void 0===s||s.call(t,e)}}var bn=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await hn(),i=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=i,e.flow.start(...t)}});let Sn;const kn=(e,t)=>new Promise(((n,i)=>{if(!e.length)return i(new Error("No URLs provided to loadScriptWithFallback"));const s=t();if(s)return n(s);const r=e.shift(),o=document.createElement("script");o.src=r,o.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),o.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},o.addEventListener("error",(()=>{kn(e,t),o.setAttribute("data-error","true")})),document.body.appendChild(o)})),In=(e,t,n)=>{const i=async()=>{let i,s;return i&&s||({client:i,stateUserKey:s}=await(async(e,t,n)=>{Sn||(Sn=(async()=>{try{return Promise.resolve().then((function(){return qo}))}catch(e){return kn([Dt,Wt],(()=>window.oidc))}})());const{OidcClient:i,WebStorageStateStore:s}=await Sn;if(!i)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=t,o=(null==n?void 0:n.redirectUri)||window.location.href,a=(null==n?void 0:n.scope)||"openid email roles descope.custom_claims offline_access",c=`${r}_user`;let l=e.httpClient.buildUrl(t);(null==n?void 0:n.applicationId)&&(l=`${l}/${n.applicationId}`);const d={authority:l,client_id:t,redirect_uri:o,response_type:"code",scope:a,stateStore:new s({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 i(d),stateUserKey:c}})(e,t,n)),{client:i,stateUserKey:s}},s=async(t="")=>{var n;const{client:s,stateUserKey:r}=await i(),o=await s.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(o)))),window.localStorage.setItem(r,JSON.stringify({id_token:(a=o).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())})(),o};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await i(),s=await n.createSigninRequest(e),{url:r}=s;return t||(window.location.href=r),{ok:!0,data:s}},finishLogin:s,finishLoginIfNeed:async(e="")=>{if(window.location.search.includes("code")&&window.location.search.includes("state"))return await s(e)},refreshToken:async t=>{var n;const{client:s,stateUserKey:r}=await i(),o=(e=>{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null})(r);if(!o)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 c=await s.useRefreshToken({state:{refresh_token:a,session_state:o.session_state,profile:o.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:n,stateUserKey:s}=await i();e||(e={}),e.id_token_hint=e.id_token_hint||Vt(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:o}=r;return window.localStorage.removeItem(s),t||window.location.replace(o),r}}},xn=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>n=>{var{fpKey:i,fpLoad:s}=n,r=t(n,["fpKey","fpLoad"]);return Nt?(i&&s&&en(i).catch((()=>null)),e(Ot(r,{beforeRequest:tn}))):e(r)}),(e=>n=>{var{autoRefresh:i}=n,s=t(n,["autoRefresh"]);if(!i)return e(s);const{clearAllTimers:r,setTimer:o}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let c,l;Nt&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&c&&new Date>c&&(qt("Expiration time passed, refreshing session"),d.refresh(Jt()||l))}));const d=e(Ot(s,{afterRequest:async(e,t)=>{const{sessionJwt:n,refreshJwt:i,sessionExpiration:s}=await Ut(t);if(401===(null==t?void 0:t.status))qt("Received 401, canceling all timers"),r();else if(n||s){if(c=((e,t)=>{if(t)return new Date(1e3*t);qt("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,s),!c)return void qt("Could not extract expiration time from session token");l=i;const e=(e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>Mt&&(qt(`Timeout is too large (${t}ms), setting it to ${Mt}ms`),t=Mt),t})(c);if(r(),e<=2e4)return void qt("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});qt(`Setting refresh timer for ${t}. (${e}ms)`),o((()=>{qt("Refreshing session due to timer"),d.refresh(Jt()||i)}),e)}}}));return ie(d,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return qt("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.29.0"},t.baseHeaders)}))),(e=>t=>{const n=cn(),i=cn(),s=cn(),r=e(Ot(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))i.pub(null),s.pub(null),n.pub(null);else{const e=await Rt(t);e&&s.pub(e);const{sessionJwt:r,sessionExpiration:o}=await Ut(t);r&&i.pub(r),(o||r)&&n.pub(o||42)}}})),o=ie(r,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const r=await e(...t);return i.pub(null),s.pub(null),n.pub(null),r}));return Object.assign(o,{onSessionTokenChange:i.sub,onUserChange:s.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(e=>n=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:s=!1}=n,r=t(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(e(r),{getLastUserLoginId:rn,getLastUserDisplayName:on});const o=e(Ot(r,{afterRequest:async(e,t)=>{var n;const i=await Rt(t),s=null===(n=null==i?void 0:i.loginIds)||void 0===n?void 0:n[0],r=null==i?void 0:i.name;s&&((e=>{jt(nn,e)})(s),(e=>{jt(sn,e)})(r))}}));let a=ie(o,["flow.start"],an);return a=ie(a,["logout","logoutAll"],(e=>t=>async(...n)=>{const i=await t(...n);return e||(Lt(nn),Lt(sn)),i})(s)),Object.assign(a,{getLastUserLoginId:rn,getLastUserDisplayName:on})}),(e=>n=>{var{persistTokens:i,sessionTokenViaCookie:s,storagePrefix:r}=n,o=t(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!i||!Nt)return e(o);const a=e(Ot(o,{beforeRequest:(c=r,e=>Object.assign(e,{token:e.token||Jt(c)})),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?n||zt(r):((e={},t=!1,n="")=>{var i;const{sessionJwt:s,refreshJwt:r}=e;if(r&&jt(`${n}${Ht}`,r),s)if(t){const n=t.sameSite||"Strict",r=null===(i=t.secure)||void 0===i||i;!function(e,t,n){if(t){const{cookieDomain:i,cookiePath:s,cookieSameSite:r,cookieExpiration:o,cookieSecure:a}=n,c=new Date(1e3*o),l=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(i);gt.set(e,t,{path:s,domain:l?i:void 0,expires:c,sameSite:r,secure:a})}}(Ft,s,Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:r}))}else jt(`${n}${Ft}`,s);e.idToken&&jt(`${n}${Kt}`,e.idToken)})(await Ut(t),s,r)}}));var c;const l=ie(a,["logout","logoutAll","oidc.logout"],(e=>t=>async(...n)=>{const i=await t(...n);return zt(e),i})(r));return Object.assign(l,{getRefreshToken:()=>Jt(r),getSessionToken:()=>Bt(r),getIdToken:()=>Vt(r)})}))((e=>{const t=ht(e),n=In(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async i=>{if(e.oidcConfig)try{return await n.refreshToken(i),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=Bt(),r=Jt();return t.refresh(i,{dcs:s?"t":"f",dcr:r?"t":"f"})},logout:async i=>{if(e.oidcConfig)try{return await n.logout({id_token_hint:i}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(i)},flow:bn(t),webauthn:vn(t),fedcm:(i=t,s=e.projectId,{onetap:{requestExchangeCode(e){yn(i,e)},requestAuthentication(e){yn(i,e)}},oneTap(e,t,n,s,r){yn(i,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:s,onDismissed:r})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:i.httpClient.buildUrl(s+_n),clientId:s}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return i.refresh(r.token)},isSupported:()=>Nt&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=i.httpClient.buildUrl(s+_n);try{const i={identity:{context:e||"signin",providers:[{configURL:n,clientId:s}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(i));return!!r&&!!r.token}catch(e){return!1}}}),oidc:n});var i,s})),Cn="undefined"!=typeof localStorage,En="J151000",Tn=Cn&&localStorage.getItem("base.content.url")||"",On="base.ui.components.url";Cn&&localStorage.getItem(On),Cn&&localStorage.getItem(On);const Un="descope-login-flow",Rn="code",An="data-exclude-field",jn="data-exclude-next",Pn="dls_last_auth",Ln="state_id",qn="saml_idp_state_id",$n="saml_idp_username",Nn="descope_idp_initiated",Mn="sso_app_id",Dn="third_party_app_id",Wn="third_party_app_state_id",Fn="oidc_login_hint",Hn="oidc_prompt",Kn="oidc_error_redirect_uri",Jn="application_scopes",Bn="data-type",Vn="redirect",zn="poll",Gn="webauthnCreate",Qn="webauthnGet",Xn="nativeBridge",Zn="loadForm",Yn="submit",ei="polling",ti=["descope-multi-select-combo-box","descope-text-area"],ni=["cssVars","componentsConfig","inputs","errorText","errorType","clientScripts"];var ii;!function(e){e.backward="backward",e.forward="forward"}(ii||(ii={}));const si=["descope-enriched-text"];function ri(e){return new URLSearchParams(window.location.search).get(e)}function oi(e){if(window.history.replaceState&&ri(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 ai(e,t){if(!t)return;const n=+e,i=+t;return Number.isNaN(n)||Number.isNaN(i)?void 0:n>i?ii.forward:n<i?ii.backward:void 0}const ci=e=>{let[t="",n=""]=(ri(Un)||"").split("_");const i=(e=>{var t;return(null===(t=/(.*)\|#\|.*/.exec(e))||void 0===t?void 0:t[1])||""})(t);return(!e||i&&i!==e)&&(t="",n=""),{executionId:t,stepId:n,executionFlowId:i}};function li(){oi(Un)}const di=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),ui=(e,t)=>{const{executionId:n,stepId:i,executionFlowId:s}=ci(e);if(s&&e!==s)return t.debug("Flow id does not match the execution flow id, skipping url params handling"),{ssoQueryParams:{}};(n||i)&&li();const r=ri("t")||void 0;r&&oi("t");const o=ri(Rn)||void 0;o&&oi(Rn);const a=ri("err")||void 0;a&&oi("err");const{redirectAuthCodeChallenge:c,redirectAuthCallbackUrl:l,redirectAuthBackupCallbackUri:d,redirectAuthInitiator:u}={redirectAuthCodeChallenge:ri("ra-challenge"),redirectAuthCallbackUrl:ri("ra-callback"),redirectAuthBackupCallbackUri:ri("ra-backup-callback"),redirectAuthInitiator:ri("ra-initiator")},h=ri(Ln);h&&oi(Ln);const p=ri(qn);p&&oi(qn);const g=ri($n);p&&oi($n);const f=ri(Nn);f&&oi(Nn);const m=ri(Mn);m&&oi(Mn);const w=ri(Dn);w&&oi(Dn);const v=ri(Wn);v&&oi(Wn);const _=ri(Jn);_&&oi(Jn);const y=ri(Fn);y&&oi(Fn);const b=ri(Hn);b&&oi(Hn);const S=ri(Kn);S&&oi(Kn);return{executionId:n,stepId:i,token:r,code:o,exchangeError:a,redirectAuthCodeChallenge:c,redirectAuthCallbackUrl:l,redirectAuthBackupCallbackUri:d,redirectAuthInitiator:u,ssoQueryParams:{oidcIdpStateId:h,samlIdpStateId:p,samlIdpUsername:g,descopeIdpInitiated:"true"===f,ssoAppId:m,oidcLoginHint:y,oidcPrompt:b,oidcErrorRedirectUri:S,thirdPartyAppId:w,thirdPartyAppStateId:v,applicationScopes:_}}},hi=e=>{let t,n;return Object.assign(((...i)=>{return t&&(r=i,(s=t).length===r.length&&s.every(((e,t)=>e===r[t])))||(t=i,n=e(...i)),n;var s,r}),{reset:()=>{t=void 0,n=void 0}})};function pi(e,t,n){return new Promise(((i,s)=>{let r=!1;const o=setTimeout((()=>{r=!0,void 0!==n?i(n):s(new Error(`Promise timed out after ${e} ms`))}),e);t.then((e=>{r||(clearTimeout(o),i(e))})).catch((e=>{r||(clearTimeout(o),s(e))}))}))}const gi=(e,{oidcIdpStateId:t,samlIdpStateId:n,samlIdpUsername:i,ssoAppId:s,oidcLoginHint:r,oidcPrompt:o,oidcErrorRedirectUri:a,thirdPartyAppId:c,thirdPartyAppStateId:l,applicationScopes:d})=>!(!e||t||n||i||s||r||o||a||c||l||d),fi=e=>null==e?void 0:e.submit(),mi=(e,t)=>{const n=t.find((t=>e[t]));return n?e[n]:null},wi=(e,t=100)=>{let n;return function(...i){n||e.apply(this,i),clearTimeout(n),n=setTimeout((()=>{n=null}),t)}};function vi(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 _i=e=>{const t=(n=e.screenState,i=(e,t)=>ni.includes(t)||t.startsWith("_"),Object.fromEntries(Object.entries(n).filter((([e,t])=>!i(t,e)))));var n,i;const{screenState:{errorText:s,errorType:r}}=e;return(s||r)&&(t.error={text:s,type:r}),t};var yi,bi,Si,ki;function Ii(e,t){const n=Object.getOwnPropertyNames(e),i=Object.getOwnPropertyNames(t);if(n.length!==i.length)return!1;for(let i=0;i<n.length;i+=1){const s=n[i],r=e[s],o=t[s];if(null===r||null===o){if(r!==o)return!1}else if("object"==typeof r&&"object"==typeof o){if(!Ii(r,o))return!1}else if(r!==o)return!1}return!0}let xi=class{constructor(e={},{forceUpdate:t=!1}={}){yi.set(this,void 0),bi.set(this,{}),Si.set(this,0),ki.set(this,!0),this.update=e=>{const t="function"==typeof e?e(i(this,yi,"f")):e,n=Object.assign(Object.assign({},i(this,yi,"f")),t),r=i(this,yi,"f");s(this,yi,n,"f"),Object.freeze(i(this,yi,"f")),setTimeout((()=>{Object.values(i(this,bi,"f")).forEach((({cb:e,selector:t})=>{const s=t(r),o=t(n);!i(this,ki,"f")&&(function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(o)?Ii(s,o):s===o)||e(o,s,((e,t)=>n=>e[n]!==t[n])(o,s))}))}),0)},s(this,yi,e,"f"),s(this,ki,t,"f")}get current(){return Object.assign({},i(this,yi,"f"))}set forceUpdate(e){s(this,ki,e,"f")}subscribe(e,t=e=>e){return s(this,Si,i(this,Si,"f")+1,"f"),i(this,bi,"f")[i(this,Si,"f")]={cb:e,selector:t},i(this,Si,"f").toString()}unsubscribe(e){const t=!!i(this,bi,"f")[e];return t&&delete i(this,bi,"f")[e],t}unsubscribeAll(){return s(this,bi,{},"f"),!0}};yi=new WeakMap,bi=new WeakMap,Si=new WeakMap,ki=new WeakMap;const Ci=["*","#","/","(",")","[","]","_","<",">","`"],Ei=e=>{const t=Ci.map((t=>`${e}${t}`)).join("|");return new RegExp(`(${t})`,"g")},Ti=["disabled"],Oi=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${An}])`)).forEach((e=>{e.value=n}))}))},Ui=(e,t)=>t.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),e),Ri=(e,t,n)=>e.replace(/{{(.+?)}}/g,((e,i)=>n?(e=>"string"!=typeof e?e:e.replace(Ei("\\"),"\\$1"))(Ui(t,i)):Ui(t,i))),Ai=(e,t)=>{e.querySelectorAll("descope-text,descope-link,descope-enriched-text,descope-code-snippet").forEach((e=>{const n=(i=e.localName,si.includes(i));var i;e.textContent=Ri(e.textContent,t,n);const s=e.getAttribute("href");s&&e.setAttribute("href",Ri(s,t))}))},ji=(e,t,n)=>{e.querySelectorAll(`[${Bn}="${t}"]`).forEach((e=>{e.setAttribute("href",n)}))},Pi=(e,t,n)=>{var i,s;const r=null===(i=customElements.get(t))||void 0===i?void 0:i.cssVarList.url;n&&r&&(null===(s=null==e?void 0:e.style)||void 0===s||s.setProperty(r,`url(data:image/jpg;base64,${n})`))},Li=(e,n,i,s,r)=>{var o,a;ji(e,"totp-link",null===(o=null==n?void 0:n.totp)||void 0===o?void 0:o.provisionUrl),ji(e,"notp-link",null===(a=null==n?void 0:n.notp)||void 0===a?void 0:a.redirectUrl),Ai(e,n),((e,n,i)=>{if(!n)return;const{componentsDynamicAttrs:s}=n,r=t(n,["componentsDynamicAttrs"]),o=Object.keys(r).reduce(((e,t)=>(e[`[name=${t}]`]=r[t],e)),{});s&&Object.keys(s).forEach((e=>{const t=s[e];if(t){const{attributes:n}=t;n&&Object.keys(n).length&&(o[e]=n)}})),Object.keys(o).forEach((t=>{e.querySelectorAll(t).forEach((e=>{const n=o[t];Object.keys(n).forEach((t=>{let s=n[t];if("string"!=typeof s)try{s=JSON.stringify(s)}catch(e){i.error(`Could not stringify value "${s}" for "${t}"`,e.message),s=""}e.setAttribute(t,s)}))}))}))})(e,i,r),((e,t)=>{e.querySelectorAll("[data-has-dynamic-attr-values]").forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=Ri(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])=>{Ti.includes(t)&&e.setAttribute(t,n)}))}))}))})(e,s)},qi=hi((()=>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)))),i=(()=>{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 pi(100,n,i)}catch(e){return console.error("Conditional login check failed",e),!1}})))),$i=(e,t,n,i={})=>{var s,r,o,a;return[Math.min(Math.max(t,("all"===i.left?e.offsetWidth:null!==(s=i.left)&&void 0!==s?s:0)-e.offsetWidth),window.innerWidth-("all"===i.right?e.offsetWidth:null!==(r=i.right)&&void 0!==r?r:0)),Math.min(Math.max(n,("all"===i.top?e.offsetHeight:null!==(o=i.top)&&void 0!==o?o:0)-e.offsetHeight),window.innerHeight-("all"===i.bottom?e.offsetHeight:null!==(a=i.bottom)&&void 0!==a?a:0))]},Ni="dls_ab_testing_id",Mi={"lastAuth.loginId":{"not-empty":e=>!!e.loginId,empty:e=>!e.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}};function Di(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(Pn)))}catch(e){}return t}function Wi(...e){return t=>e.reduce(((e,t)=>t(e)),t)}const Fi=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 i=e(n);return i[t]=!0,i}},Hi=["error","warn","info","debug"],Ki=Fi((e=>{var t,n,r,o;return o=class extends e{constructor(){super(...arguments),t.add(this),n.set(this,i(this,t,"m",r).call(this,console))}set logger(e){s(this,n,i(this,t,"m",r).call(this,e||console),"f")}get logger(){return i(this,n,"f")}onLogEvent(e,t){}},n=new WeakMap,t=new WeakSet,r=function(e){return Hi.reduce(((t,n)=>(t[n]=(...t)=>{var i;this.onLogEvent(n,t),null===(i=e[n])||void 0===i||i.call(e,...t)},t)),{})},o})),Ji="undefined"!=typeof localStorage,Bi=Ji&&localStorage.getItem("base.content.url")||"",Vi=(e,t)=>!t&&`${e} cannot be empty, please make sure to set this attribute`,zi=Fi((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)&&i(this,t,"f")&&(s(this,t,!1,"f"),this.init())}async init(){}},t=new WeakMap,n})),Gi=Fi((e=>{var t,n;const s=Wi(Ki,zi)(e);return n=class extends s{constructor(){super(...arguments),t.set(this,{})}async init(){var e,n,s;await(null===(e=super.init)||void 0===e?void 0:e.call(this)),n=this,s=e=>{var n;null===(n=i(this,t,"f")[e])||void 0===n||n.forEach((t=>{t(e,this.getAttribute(e))}))},Array.from(n.attributes).forEach((e=>s(e.name))),new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&s(e.attributeName)}))})).observe(n,{attributes:!0})}observeAttribute(e,n){i(this,t,"f")[e]||(i(this,t,"f")[e]=[]);const s=i(this,t,"f")[e].push(n);return()=>i(this,t,"f")[e].splice(s,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})),Qi=e=>t=>{var n,s,r;const o=Wi(Ki,zi,Gi)(t),a=Object.keys(e);return r=class extends o{constructor(...e){super(...e),n.add(this),this.observeAttributes(a,i(this,n,"m",s).bind(this))}async init(){var e;a.forEach((e=>i(this,n,"m",s).call(this,e,this.getAttribute(e)))),await(null===(e=super.init)||void 0===e?void 0:e.call(this))}},n=new WeakSet,s=function(t,n){const i=e[t],s="function"==typeof i?i(t,n):i;s&&this.logger.error(s)},r};Qi.missingAttrValidator=Vi;const Xi=Fi((e=>{const t=Wi(Qi({"project-id":Vi}))(e);return class extends t{get projectId(){return this.getAttribute("project-id")}}})),Zi=Fi((e=>class extends e{get baseUrl(){return this.getAttribute("base-url")||""}})),Yi="Trying the next fallback URL...";function es({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:i="https://static.descope.com/pages"}){const s=new URL(i);return s.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(s.pathname,e,n,t),s.baseUrl=i,s}const ts=Fi((e=>{var t,n,r,o,a;const c=Wi(Ki,Xi,Zi)(e);return a=class extends c{constructor(){super(...arguments),t.add(this),n.set(this,void 0),r.set(this,void 0)}async fetchStaticResource(e,n){const a=i(this,t,"m",o).call(this,e),c=Array.isArray(a)?e=>{if(e!==a.length-1){const{baseUrl:t}=a[e];s(this,r,t,"f")}}:null;try{const e=await(async(e,t,{logger:n,onSuccess:i})=>{const s=Array.isArray(e)?e:[e];for(let e=0;e<s.length;e++){const r=s[e],o=e===s.length-1;try{const s=await fetch(r.toString(),t);if(s.ok)return null==i||i(e),s;const a=`Error fetching URL ${r} [${s.status}]`;if(o)throw new Error(a);null==n||n.debug(`${a}. ${Yi}`)}catch(e){const t=`Error fetching URL ${r} [${e.message}]`;if(o)throw new Error(t);null==n||n.debug(`${t}. ${Yi}`)}}})(a,{cache:"default"},{logger:this.logger,onSuccess:c});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,o=function(e){const t=Bi||this.baseStaticUrl;if(t)return es({projectId:this.projectId,filename:e,baseUrl:t});const o=i(this,n,"f")!==this.baseUrl,a=o&&!!this.baseUrl;o&&(s(this,n,this.baseUrl,"f"),s(this,r,void 0,"f"));const c=es({projectId:this.projectId,filename:e,baseUrl:i(this,r,"f")});if(!a)return c;return[es({projectId:this.projectId,filename:e,baseUrl:this.baseUrl+"/pages"}),c]},a})),ns=Fi((e=>{var t,n;const s=Wi(Qi({"project-id":Vi}))(e);return n=class extends s{constructor(){super(...arguments),t.set(this,new Map)}onReset(e,n){if(i(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} already exists`);return i(this,t,"f").set(e,n),()=>{i(this,t,"f").delete(e)}}async reset(...e){0===e.length?await Promise.all(Array.from(i(this,t,"f").values()).map((e=>e()))):await Promise.all(e.map((e=>{var n;if(!i(this,t,"f").has(e))throw new Error(`Callback for sectionId ${e} does not exist`);return null===(n=i(this,t,"f").get(e))||void 0===n?void 0:n()})))}},t=new WeakMap,n})),is=Fi((e=>{var t,n,r,o,a;const c=Wi(ts,ns,zi)(e);return a=class extends c{constructor(){super(...arguments),t.add(this),r.set(this,void 0),o.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",i(this,t,"m",n).bind(this))}get config(){return i(this,r,"f")||s(this,r,i(this,o,"f").call(this),"f"),i(this,r,"f")}},r=new WeakMap,o=new WeakMap,t=new WeakSet,n=function(){s(this,r,void 0,"f")},a})),ss="load-descope-ui",rs="base.ui.components.url",os=Ji&&localStorage.getItem(rs)||"https://descopecdn.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",as=Ji&&localStorage.getItem(rs)||"https://static.descope.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",cs=Ji&&localStorage.getItem(rs)||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",ls=e=>{const t=document.createElement("script");return t.id=e,t},ds=(e,t)=>e.replace("<version>",t),us=Fi((e=>{var t,n,r,o,a,c,l,d,u,h,p,g;const f=Wi(Ki,is)(e);return g=class extends f{constructor(){super(...arguments),t.add(this),n.set(this,Symbol("errorCbs")),r.set(this,Symbol("loadCbs")),u.set(this,void 0)}get descopeUi(){return i(this,u,"f")||s(this,u,i(this,t,"m",p).call(this),"f"),i(this,u,"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=>i(this,t,"m",h).call(this,e))))}get baseCdnUrl(){return this.getAttribute("base-cdn-url")}},n=new WeakMap,r=new WeakMap,u=new WeakMap,t=new WeakSet,o=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},a=function(e){const t=i(this,n,"f"),s=i(this,r,"f");e[t]=[],e[s]=[],Object.defineProperty(e,"onerror",{set(n){e[t].push(n)}}),Object.defineProperty(e,"onload",{set(t){e[s].push(t)}})},c=async function(e,n,s,r){this.logger.debug("Trying to load DescopeUI from a fallback URL");const a=ls(s);document.body.append(a),a.addEventListener("error",(()=>{e.forEach((e=>e(`Cannot load DescopeUI from fallback URL, Make sure this URL is valid and return the correct script: "${a.src}"`)))})),a.addEventListener("load",(()=>{n.forEach((e=>e()))})),a.src=ds(r,await i(this,t,"m",o).call(this))},l=function(e){e.addEventListener("error",(()=>{e[i(this,n,"f")].forEach((t=>t(`Cannot load DescopeUI from main URL, Make sure this URL is valid and return the correct script: "${e.src}"`))),i(this,t,"m",c).call(this,[i(this,t,"m",c).bind(this,e[i(this,n,"f")],e[i(this,r,"f")],"load-descope-ui-fallback-script-2",cs),...e[i(this,n,"f")]],e[i(this,r,"f")],"load-descope-ui-fallback-script",as)})),e.addEventListener("load",(()=>{e[i(this,r,"f")].forEach((e=>e()))}))},d=async function(){if(document.querySelector(`script#${ss}`))this.logger.debug("DescopeUI loading script already exists",this);else{this.logger.debug("DescopeUI loading script does not exist, creating it",this);const e=ls(ss);document.body.append(e),i(this,t,"m",a).call(this,e),i(this,t,"m",l).call(this,e),e.src=ds(this.baseCdnUrl||os,await i(this,t,"m",o).call(this))}return document.getElementById(ss)},h=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(", ")}"`)},p=function(){return new Promise((e=>{globalThis.DescopeUI&&e(globalThis.DescopeUI),i(this,t,"m",d).call(this).then((t=>{t.onerror=this.logger.error,t.onload=()=>{this.logger.debug("DescopeUI was loaded"),e(globalThis.DescopeUI)},setTimeout((()=>{globalThis.DescopeUI&&e(globalThis.DescopeUI)}))}))}))},g})),hs="content-root",ps="root",gs=Fi((e=>class extends e{constructor(...e){var t,n,i,s;super(...e),this.attachShadow({mode:"open"}).innerHTML=`\n <div id="${ps}">\n <div id="${hs}"></div>\n </div>\n `;const r=new CSSStyleSheet;r.replaceSync(`\n #${ps}, #${hs} {\n height: 100%;\n }\n #${ps} {\n position: relative;\n height: fit-content;\n }\n `),null!==(t=(s=this.shadowRoot).adoptedStyleSheets)&&void 0!==t||(s.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,r],this.contentRootElement=null===(n=this.shadowRoot)||void 0===n?void 0:n.getElementById(hs),this.rootElement=null===(i=this.shadowRoot)||void 0===i?void 0:i.getElementById(ps)}})),fs=(e,t)=>!!t&&"light"!==t&&"dark"!==t&&'Supported theme values are "light", "dark", or leave empty for using the OS theme',ms=Fi((e=>{var t,n,r,o,a,c,l,d,u,h,p,g,f,m;const w=Wi(Qi({theme:fs}),ts,zi,us,is,gs,Gi)(e);return m=class extends w{constructor(){super(...arguments),t.add(this),n.set(this,void 0),r.set(this,void 0),p.set(this,(()=>{i(this,t,"m",g).call(this),i(this,f,"f").call(this,"os"===this.getAttribute("theme"))})),f.set(this,(e=>{var n,s,r;const o=e?"addEventListener":"removeEventListener";null===(r=null===(s=null===(n=window.matchMedia)||void 0===n?void 0:n.call(window,"(prefers-color-scheme: dark)"))||void 0===s?void 0:s[o])||void 0===r||r.call(s,"change",(()=>i(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)),i(this,t,"m",c).call(this),i(this,t,"m",l).call(this),i(this,p,"f").call(this),this.observeAttributes(["theme"],i(this,p,"f")),this.observeAttributes(["style-id"],(()=>{s(this,r,null,"f"),i(this,t,"m",u).call(this),i(this,t,"m",c).call(this),i(this,t,"m",l).call(this)}))}},n=new WeakMap,r=new WeakMap,p=new WeakMap,f=new WeakMap,t=new WeakSet,o=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 i(this,r,"f")||(s(this,r,i(this,t,"m",o).call(this),"f"),i(this,r,"f").then((e=>this.logger.debug("Fetched theme",e)))),i(this,r,"f")},c=async function(){var e,r,o,c;const l=await i(this,t,"a",a);l&&(i(this,n,"f")||(s(this,n,new CSSStyleSheet,"f"),null!==(e=(c=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(c.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,i(this,n,"f")]),i(this,n,"f").replaceSync(((null===(r=null==l?void 0:l.light)||void 0===r?void 0:r.globals)||"")+((null===(o=null==l?void 0:l.dark)||void 0===o?void 0:o.globals)||"")))},l=async function(){var e,n;const s=Object.assign({},await i(this,t,"a",a));if(!s)return;const r=await this.descopeUi;(null==r?void 0:r.componentsThemeManager)&&(r.componentsThemeManager.themes={light:null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.components,dark:null===(n=null==s?void 0:s.dark)||void 0===n?void 0:n.components})},d=async function(){var e,t;const{projectConfig:n}=await this.config||{},i=null===(e=null==n?void 0:n.styles)||void 0===e?void 0:e[this.styleId],s=null==n?void 0:n.cssTemplate,r=i||s;return null===(t=null==r?void 0:r[this.theme])||void 0===t?void 0:t.fonts},u=async function(){const e=await i(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")},h=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(){i(this,t,"m",u).call(this),i(this,t,"m",h).call(this)},m})),ws=(e,t="")=>Object.keys(e).reduce(((n,i)=>{var s;if("object"==typeof e[i]&&null!==e[i]&&!(null===(s=e[i])||void 0===s?void 0:s.value))return Object.assign(Object.assign({},n),ws(e[i],`${t+i}.`));const r="object"==typeof e[i]?e[i]:{value:e[i]},o=Object.assign(Object.assign({},n),{[t+i]:r,[`form.${t}${i}`]:r});return"displayName"===i?Object.assign(Object.assign({},o),{[`${t}fullName`]:r,[`form.${t}fullName`]:r}):o}),[]),vs=Fi((e=>{var t,n,s,r;return r=class extends e{constructor(){super(...arguments),t.add(this)}connectedCallback(){var e;i(this,t,"m",n).call(this)&&i(this,t,"m",s).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)},s=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 _s,ys,bs,Ss,ks,Is,xs,Cs,Es,Ts,Os,Us,Rs,As,js,Ps,Ls,qs,$s,Ns,Ms,Ds,Ws;const Fs=Wi(ms,ts,vs)(HTMLElement);class Hs extends Fs{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","nonce"]}constructor(e){super(),_s.add(this),bs.set(this,!1),this.flowStatus="initial",this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),i(this,_s,"m",Ms).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)}},Ss.set(this,new xi),ks.set(this,new xi),Is.set(this,{}),this.getComponentsContext=()=>i(this,Is,"f"),this.nextRequestStatus=new xi({isLoading:!1}),xs.set(this,void 0),Cs.set(this,{popstate:i(this,_s,"m",Rs).bind(this),componentsContext:i(this,_s,"m",qs).bind(this)}),Es.set(this,void 0),this.getConfig=()=>n(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),s(this,Es,e,"f"),i(this,_s,"m",Os).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 ws(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 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(),i=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=i.version)&&void 0!==t||(i.version=0),i}))}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),i(this,ks,"f").subscribe(i(this,_s,"m",Ns).bind(this)),i(this,ks,"f").update({isDebug:this.debug}),i(this,_s,"m",Us).call(this),i(this,_s,"m",Ws).call(this),yield i(this,_s,"m",Ps).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");i(this,_s,"m",Ds).call(this);const{executionId:r,stepId:o,token:a,code:c,exchangeError:l,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthCodeChallenge:h,redirectAuthInitiator:p,ssoQueryParams:g}=ui(this.flowId,this.loggerWrapper);window.addEventListener("popstate",i(this,Cs,"f").popstate),window.addEventListener("components-context",i(this,Cs,"f").componentsContext),i(this,Ss,"f").subscribe(i(this,_s,"m",js).bind(this)),i(this,Ss,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:o,executionId:r,token:a,code:c,exchangeError:l,redirectAuthCallbackUrl:d,redirectAuthBackupCallbackUri:u,redirectAuthCodeChallenge:h,redirectAuthInitiator:p},g)),s(this,bs,!0,"f")}))}disconnectedCallback(){i(this,Ss,"f").unsubscribeAll(),i(this,ks,"f").unsubscribeAll(),i(this,_s,"m",$s).call(this),window.removeEventListener("popstate",i(this,Cs,"f").popstate),window.removeEventListener("components-context",i(this,Cs,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&i(this,bs,"f")&&t!==n&&ys.observedAttributes.includes(e)){i(this,_s,"m",Us).call(this);const s=null===t;"nonce"===e&&i(this,_s,"m",Ws).call(this),i(this,Ss,"f").update((({stepId:t,executionId:i})=>{let r=t,o=i;return s||(o=null,r=null,li()),{[di(e)]:n,stepId:r,executionId:o}})),i(this,ks,"f").update({isDebug:this.debug})}}}function Ks(e,t){return`sdkScriptsResults.${t?`${e}_${t}`:e}`}var Js,Bs,Vs,zs,Gs,Qs,Xs,Zs,Ys,er,tr,nr,ir,sr,rr,or,ar,cr,lr,dr,ur,hr,pr,gr,fr,mr,wr,vr,_r;ys=Hs,bs=new WeakMap,Ss=new WeakMap,ks=new WeakMap,Is=new WeakMap,xs=new WeakMap,Cs=new WeakMap,Es=new WeakMap,_s=new WeakSet,Ts=function(){var e,t;const n=new CSSStyleSheet;n.replaceSync("\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 300ms 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;\n\t\t}\n\n .hidden {\n display: none;\n }\n "),null!==(e=(t=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(t.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,n]},Os=function(){i(this,_s,"m",Ts).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},Us=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","nonce"];ys.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[di(t)])throw Error(`${t} cannot be empty`)}))},Rs=function(){const{stepId:e,executionId:t}=ci(this.flowId);i(this,Ss,"f").update({stepId:e,executionId:t})},As=function(e,t){this.sdk=xn(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},ys.sdkConfigOverrides),{projectId:e,baseUrl:t})),["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:En,errorDescription:e.toString()}}}}))}))},js=function(e,t,s){return n(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:n}=e;if(s("projectId")||s("baseUrl")){if(!t)return;i(this,_s,"m",As).call(this,t,n)}i(this,Es,"f").call(this,e)}))},Ps=function(){return n(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield i(this,_s,"m",Ls).call(this))}))},Ls=function(){return n(this,void 0,void 0,(function*(){const e=function({projectId:e,filename:t,assetsFolder:n="v2-beta",baseUrl:i}){const s=new URL(Tn||i||"https://static.descope.com/pages");return s.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(s.pathname,e,n,t),s.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}}))},qs=function(e){s(this,Is,Object.assign(Object.assign({},i(this,Is,"f")),e.detail),"f")},$s=function(){var e;null===(e=i(this,xs,"f"))||void 0===e||e.remove(),s(this,xs,null,"f")},Ns=function(e){return n(this,arguments,void 0,(function*({isDebug:e}){e?(s(this,xs,document.createElement("descope-debugger"),"f"),Object.assign(i(this,xs,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Mo})),document.body.appendChild(i(this,xs,"f"))):i(this,_s,"m",$s).call(this)}))},Ms=function(e,t){var n;e&&this.debug&&(null===(n=i(this,xs,"f"))||void 0===n||n.updateData({title:e,description:t}))},Ds=function(){this.rootElement.onkeydown=e=>{var t,n,i;const s=!!(null===(t=this.shadowRoot.activeElement)||void 0===t?void 0:t.getAttribute("href")),r=ti.includes(null!==(i=null===(n=this.shadowRoot.activeElement)||void 0===n?void 0:n.localName)&&void 0!==i?i:"");if("Enter"!==e.key||s||r)return;e.preventDefault();const o=this.rootElement.querySelectorAll("descope-button");if(1===o.length&&"false"!==o[0].getAttribute("auto-submit"))return void o[0].click();const a=Array.from(o).filter((e=>"true"===e.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const c=Array.from(o).filter((e=>"button"===e.getAttribute("data-type")));if(1===c.length)"false"!==c[0].getAttribute("auto-submit")&&c[0].click();else if(0===c.length){const e=Array.from(o).filter((e=>"sso"===e.getAttribute("data-type")));1===e.length&&"false"!==e[0].getAttribute("auto-submit")&&e[0].click()}}},Ws=function(){this.getAttribute("nonce")&&(window.DESCOPE_NONCE=this.getAttribute("nonce"))},Hs.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.40.4"}};class yr extends Hs{static set sdkConfigOverrides(e){Hs.sdkConfigOverrides=e}static get sdkConfigOverrides(){return Hs.sdkConfigOverrides}constructor(){const e=new xi({deferredRedirect:!1});super(e.update.bind(e)),Js.add(this),this.stepState=new xi({}),Bs.set(this,void 0),Vs.set(this,null),zs.set(this,null),Gs.set(this,{visibilitychange:i(this,Js,"m",Qs).bind(this)}),this.bridgeVersion=1,this.nativeResume=(e,t)=>{var n;const s=JSON.parse(t);if(this.logger.info(`nativeResume received payload of type '${e}'`),"oauthWeb"===e||"sso"===e){let{exchangeCode:e}=s;if(!e){e=null===(n=new URL(s.url).searchParams)||void 0===n?void 0:n.get(Rn)}this.nativeComplete({exchangeCode:e,idpInitiated:!0})}else if("magicLink"===e){const e=new URL(s.url),t=e.searchParams.get("t"),n=e.searchParams.get(Un).split("_").pop();i(this,ir,"f").call(this),this.flowState.update({token:t,stepId:n,action:void 0})}else this.nativeComplete(s)},tr.set(this,(e=>{this.contentRootElement.classList.toggle("hidden",e),this.slotElement.classList.toggle("hidden",!e)})),nr.set(this,((e,t,r,o,a=!1)=>{if(this.flowState.current.action===zn){this.logger.debug("polling - Scheduling polling request");const c=Date.now(),l=a?500:2e3;s(this,Bs,setTimeout((()=>n(this,void 0,void 0,(function*(){var n;this.logger.debug("polling - Calling next");const s=this.sdk.flow.next(e,t,ei,r,o,{}),d=document.hidden&&!a&&Date.now()-c>l+500;let u;d&&this.logger.debug("polling - The polling seems to be throttled");try{const e=d?1e3:6e3;u=yield pi(e,s)}catch(n){return this.logger.warn(`polling - The ${d?"throttled fetch":"fetch"} call timed out or was aborted`),void i(this,nr,"f").call(this,e,t,r,o,d)}if((null===(n=null==u?void 0:u.error)||void 0===n?void 0:n.errorCode)===En)return this.logger.debug("polling - Got a generic error due to exception in fetch call"),void i(this,nr,"f").call(this,e,t,r,o);this.logger.debug("polling - Got a response"),(null==u?void 0:u.error)&&this.logger.debug("polling - Response has an error",JSON.stringify(u.error,null,4)),i(this,nr,"f").call(this,e,t,r,o),i(this,sr,"f").call(this,u)}))),l),"f")}})),ir.set(this,(()=>{clearTimeout(i(this,Bs,"f")),s(this,Bs,null,"f")})),sr.set(this,(e=>{var t,n,r,o,a,c,l,d,u,h,p,g,f;if(!(null==e?void 0:e.ok)){const s=null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url,l=`${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}`;i(this,Js,"m",_r).call(this,"error",(null==e?void 0:e.error)||{errorCode:"J151001",errorDescription:l,errorMessage:s}),this.loggerWrapper.error((null===(o=null==e?void 0:e.error)||void 0===o?void 0:o.errorDescription)||s,(null===(a=null==e?void 0:e.error)||void 0===a?void 0:a.errorMessage)||l);const d=null===(c=null==e?void 0:e.error)||void 0===c?void 0:c.errorCode;return void("E102004"!==d&&"E103205"!==d||!this.isRestartOnError||i(this,Js,"m",Ys).call(this))}null===(d=null===(l=e.data)||void 0===l?void 0:l.runnerLogs)||void 0===d||d.forEach((e=>{const{level:t,title:n,log:i}=e;t&&this.loggerWrapper[t]?this.loggerWrapper[t](n,i):this.loggerWrapper.info(n,i)}));const m=null===(p=null===(h=null===(u=e.data)||void 0===u?void 0:u.screen)||void 0===h?void 0:h.state)||void 0===p?void 0:p.errorText;(null===(g=e.data)||void 0===g?void 0:g.error)?this.loggerWrapper.error(`[${e.data.error.code}]: ${e.data.error.description}`,`${m?`${m} - `:""}${e.data.error.message}`):m&&this.loggerWrapper.error(m);const{status:w,authInfo:v,lastAuth:_,action:y}=e.data;if(y!==zn&&i(this,ir,"f").call(this),"completed"===w)return this.storeLastAuthenticatedUser&&function(e){(null==e?void 0:e.authMethod)&&Cn&&localStorage.setItem(Pn,JSON.stringify(e))}(_),void i(this,Js,"m",_r).call(this,"success",v);const{executionId:b,stepId:S,stepName:k,screen:I,redirect:x,openInNewTabUrl:C,webauthn:E,error:T,samlIdpResponse:O,nativeResponse:U}=e.data,R=Date.now();y!==zn?(this.loggerWrapper.info(`Step "${k||`#${S}`}" is ${w}`,"",{screen:I,status:w,stepId:S,stepName:k,action:y,error:T}),(null===(f=I.state)||void 0===f?void 0:f.clientScripts)&&s(this,zs,this.loadSdkScripts(I.state.clientScripts),"f"),this.flowState.update({stepId:S,stepName:k,executionId:b,action:y,redirectTo:null==x?void 0:x.url,openInNewTabUrl:C,screenId:null==I?void 0:I.id,screenState:null==I?void 0:I.state,webauthnTransactionId:null==E?void 0:E.transactionId,webauthnOptions:null==E?void 0:E.options,samlIdpResponseUrl:null==O?void 0:O.url,samlIdpResponseSamlResponse:null==O?void 0:O.samlResponse,samlIdpResponseRelayState:null==O?void 0:O.relayState,nativeResponseType:null==U?void 0:U.type,nativePayload:null==U?void 0:U.payload,reqTimestamp:R})):this.flowState.update({action:y,reqTimestamp:R})})),rr.set(this,hi((()=>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)}}))))),fr.set(this,wi(((e,t)=>n(this,void 0,void 0,(function*(){var n,s;if("true"===e.getAttribute("formnovalidate")||i(this,Js,"m",lr).call(this)){const r=null==e?void 0:e.getAttribute("id");i(this,Js,"m",ur).call(this,e);const o=yield i(this,Js,"m",dr).call(this),a=(s=e,Array.from((null==s?void 0:s.attributes)||[]).reduce(((e,t)=>{var n;const i=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return i?Object.assign(e,{[i]:t.value}):e}),{}));if(this.nextRequestStatus.update({isLoading:!0}),i(this,zs,"f")){this.loggerWrapper.debug("Waiting for sdk scripts to load");const e=Date.now();yield i(this,zs,"f"),this.loggerWrapper.debug("Sdk scripts loaded for",(Date.now()-e).toString())}const c=this.loadSdkScriptsModules();if(c.length>0){const e=c.filter((e=>"function"==typeof e.refresh)).map((e=>e.refresh()));e.length>0&&(yield pi(5e3,Promise.all(e),null))}const l=this.getComponentsContext(),d=Object.assign(Object.assign(Object.assign(Object.assign({},l),a),o),{origin:(null===(n=this.nativeOptions)||void 0===n?void 0:n.origin)||window.location.origin});yield t(r,d),this.nextRequestStatus.update({isLoading:!1}),i(this,Js,"m",hr).call(this,o)}}))))),this.flowState=e}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:{[Ks(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 i=Promise.all(null==e?void 0:e.map((e=>n(this,void 0,void 0,(function*(){var i;const s=this.shadowRoot.querySelector(`[data-script-id="${e.id}"]`);if(s){this.loggerWrapper.debug("Script already loaded",e.id);const{moduleRes:t}=s;return null===(i=null==t?void 0:t.start)||void 0===i||i.call(t),t}const r=yield function(e){return n(this,void 0,void 0,(function*(){let t;switch(e){case"forter":return t=yield Promise.resolve().then((function(){return Wo})),t.default;case"fingerprint":return t=yield Promise.resolve().then((function(){return Ho})),t.default;case"fingerprintDescope":return t=yield Promise.resolve().then((function(){return Jo})),t.default;case"grecaptcha":return t=yield Promise.resolve().then((function(){return zo})),t.default;default:throw new Error(`Unknown script id: ${e}`)}}))}(e.id);return new Promise(((n,i)=>{try{const i=r(e.initArgs,{baseUrl:this.baseUrl},t(e,n));if(i){const t=document.createElement("div");t.setAttribute("data-script-id",e.id),t.moduleRes=i,this.shadowRoot.appendChild(t),this.nextRequestStatus.subscribe((()=>{var t;this.loggerWrapper.debug("Unloading script",e.id),null===(t=i.stop)||void 0===t||t.call(i)}))}}catch(e){i(e)}}))}))))),s=new Promise((e=>{setTimeout((()=>{this.loggerWrapper.warn("SDK scripts loading timeout"),e(!0)}),5e3)}));return Promise.race([i,s])}get isDismissScreenErrorOnInput(){return"true"===this.getAttribute("dismiss-screen-error-on-input")}init(){if(!window.isDescopeBridge)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)),i(this,Js,"m",Zs).call(this),window.addEventListener("visibilitychange",i(this,Gs,"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(),null===(e=i(this,Vs,"f"))||void 0===e||e.abort(),s(this,Vs,null,"f"),window.removeEventListener("visibilitychange",i(this,Gs,"f").visibilitychange)}getHtmlFilenameWithLocale(e,t){return n(this,void 0,void 0,(function*(){let n;const i=vi(e),s=yield this.getTargetLocales();return s.includes(i.locale)?n=`${t}-${i.locale}.html`:s.includes(i.fallback)&&(n=`${t}-${i.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,o){return n(this,void 0,void 0,(function*(){var a,c;const{projectId:l,flowId:d,tenant:u,stepId:h,executionId:p,action:g,screenId:f,screenState:m,redirectTo:w,openInNewTabUrl:v,redirectUrl:_,token:y,code:b,exchangeError:S,webauthnTransactionId:k,webauthnOptions:I,redirectAuthCodeChallenge:x,redirectAuthCallbackUrl:C,redirectAuthBackupCallbackUri:E,redirectAuthInitiator:T,locale:O,samlIdpResponseUrl:U,samlIdpResponseSamlResponse:R,samlIdpResponseRelayState:A,nativeResponseType:j,nativePayload:P,reqTimestamp:L}=e,q=t(e,["projectId","flowId","tenant","stepId","executionId","action","screenId","screenState","redirectTo","openInNewTabUrl","redirectUrl","token","code","exchangeError","webauthnTransactionId","webauthnOptions","redirectAuthCodeChallenge","redirectAuthCallbackUrl","redirectAuthBackupCallbackUri","redirectAuthInitiator","locale","samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState","nativeResponseType","nativePayload","reqTimestamp"]);let $,N,M;const D=(()=>{const e=localStorage.getItem(Ni);if(!e){const e=Math.floor(100*Math.random()+1);return localStorage.setItem(Ni,e.toString()),e}return Number(e)})(),W=this.sdk.getLastUserLoginId(),F=yield this.getFlowConfig(),H=yield this.getProjectConfig(),K=Object.entries(H.flows||{}).reduce(((e,[t,n])=>(e[t]=n.version,e)),{}),J=C&&x?{callbackUrl:C,codeChallenge:x,backupCallbackUri:E}:void 0,B=this.nativeOptions?{platform:this.nativeOptions.platform,oauthProvider:this.nativeOptions.oauthProvider,oauthRedirect:this.nativeOptions.oauthRedirect,magicLinkRedirect:this.nativeOptions.magicLinkRedirect,ssoRedirect:this.nativeOptions.ssoRedirect}:void 0;let V={};if(!p){const e=[...F.clientScripts||[],...F.sdkScripts||[]];if(F.conditions){let t=[];({startScreenId:$,conditionInteractionId:M,startScreenName:N,clientScripts:t,componentsConfig:V}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n,predicate:i})=>{var s;if("ELSE"===t)return!0;const r=null===(s=Mi[t])||void 0===s?void 0:s[n];return!!(null==r?void 0:r(e,i))}));return n?{startScreenId:n.met.screenId,startScreenName:n.met.screenName,conditionInteractionId:n.met.interactionId,clientScripts:n.met.clientScripts,componentsConfig:n.met.componentsConfig}:{}})({loginId:W,code:b,token:y,abTestingKey:D},F.conditions)),e.push(...t||[])}else F.condition?({startScreenId:$,conditionInteractionId:M}=((e,t)=>{var n;const i=null===(n=Mi[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!i)return{};const s=i(t,e.predicate)?e.met:e.unmet;return{startScreenId:null==s?void 0:s.screenId,startScreenName:null==s?void 0:s.screenName,conditionInteractionId:null==s?void 0:s.interactionId}})(F.condition,{loginId:W,code:b,token:y,abTestingKey:D})):(N=F.startScreenName,$=F.startScreenId);if(s(this,zs,this.loadSdkScripts(e),"f"),F.fingerprintEnabled&&F.fingerprintKey?yield en(F.fingerprintKey,this.baseUrl):localStorage.removeItem(Zt),!gi($,q)){const e=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:J},q),{client:this.client}),_&&{redirectUrl:_}),{lastAuth:Di(W),abTestingKey:D,locale:vi(O).locale,nativeOptions:B}),M,"",H.componentsVersion,K,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),b?{exchangeCode:b,idpInitiated:!0}:{}),q.descopeIdpInitiated&&{idpInitiated:!0}),y?{token:y}:{}),q.oidcLoginHint?{externalId:q.oidcLoginHint}:{}));return i(this,sr,"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(p&&(o("token")&&y||o("code")&&b||o("exchangeError")&&S)){const e=yield this.sdk.flow.next(p,h,Yn,F.version,H.componentsVersion,{token:y,exchangeCode:b,exchangeError:S});return i(this,sr,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if(g===Zn&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>o(e)))){if(!U||!R)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,i)=>{const s=document.createElement("form");s.method="POST",s.action=e,s.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(s),i(s)})(U,R,A||"",fi)}if(g===Vn&&(o("redirectTo")||o("deferredRedirect")))return w?"android"===T&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(w):void this.loggerWrapper.error("Did not get redirect url");if(g===Gn||g===Qn){if(!k||!I)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(c=i(this,Vs,"f"))||void 0===c||c.abort(),s(this,Vs,null,"f");try{e=g===Gn?yield this.sdk.webauthn.helpers.create(I):yield this.sdk.webauthn.helpers.get(I)}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(p,h,Yn,F.version,H.componentsVersion,{transactionId:k,response:e,failure:t});i(this,sr,"f").call(this,n)}if(g===Xn)return this.nativeComplete=e=>n(this,void 0,void 0,(function*(){const t=yield this.sdk.flow.next(p,h,Yn,F.version,H.componentsVersion,e);i(this,sr,"f").call(this,t)})),void i(this,Js,"m",_r).call(this,"bridge",{type:j,payload:P});if(o("action")&&i(this,nr,"f").call(this,p,h,F.version,H.componentsVersion),!f&&!$)return void this.loggerWrapper.warn("No screen was found to show");const z=$||f,G=yield this.getHtmlFilenameWithLocale(O,z),{oidcLoginHint:Q,oidcPrompt:X,oidcErrorRedirectUri:Z,samlIdpUsername:Y}=q,ee={direction:ai(h,r.stepId),screenState:Object.assign(Object.assign({},m),{form:Object.assign(Object.assign({},this.formConfigValues),null==m?void 0:m.form),lastAuth:{loginId:W,name:this.sdk.getLastUserDisplayName()||W},componentsConfig:Object.assign(Object.assign(Object.assign({},F.componentsConfig),V),null==m?void 0:m.componentsConfig)}),htmlFilename:`${z}.html`,htmlLocaleFilename:G,screenId:z,stepName:e.stepName||N,samlIdpUsername:Y,oidcLoginHint:Q,oidcPrompt:X,oidcErrorRedirectUri:Z,openInNewTabUrl:v},te=Di(W);gi($,q)?ee.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=yield this.sdk.flow.start(d,Object.assign(Object.assign(Object.assign(Object.assign({tenant:u,redirectAuth:J},q),{lastAuth:te,preview:this.preview,abTestingKey:D,client:this.client}),_&&{redirectUrl:_}),{locale:vi(O).locale,nativeOptions:B}),M,e,H.componentsVersion,K,Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.formConfigValues),t),b&&{exchangeCode:b,idpInitiated:!0}),q.descopeIdpInitiated&&{idpInitiated:!0}),y&&{token:y}));return i(this,sr,"f").call(this,n),n})):(o("projectId")||o("baseUrl")||o("executionId")||o("stepId"))&&(ee.next=(e,t)=>n(this,void 0,void 0,(function*(){const n=yield this.sdk.flow.next(p,h,e,F.version,H.componentsVersion,t);return i(this,sr,"f").call(this,n),n}))),this.loggerWrapper.debug("Got a screen with id",ee.screenId),yield i(this,Js,"m",er).call(this,ee),this.stepState.update(ee)}))}onStepChange(e,t){return n(this,void 0,void 0,(function*(){var s,r;const{htmlFilename:o,htmlLocaleFilename:a,direction:c,next:l,screenState:d,openInNewTabUrl:u}=e;this.loggerWrapper.debug("Rendering a flow screen");const h=document.createElement("template");h.innerHTML=yield this.getPageContent(o,a);const p=h.content.cloneNode(!0),g=this.loadDescopeUiComponents(h);this.sdk.webauthn.helpers.isSupported()?yield i(this,Js,"m",ar).call(this,p,l):p.querySelectorAll(`descope-button[${Bn}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(s=d.form)||void 0===s?void 0:s.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),Li(p,d,d.componentsConfig,this.formConfig,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(p,f);const m=()=>n(this,void 0,void 0,(function*(){var n,s;yield g;const r=this.contentRootElement;var o,a;o=r,a=null===(n=null==d?void 0:d.totp)||void 0===n?void 0:n.image,Pi(o,"descope-totp-image",a),((e,t)=>{Pi(e,"descope-notp-image",t)})(r,null===(s=null==d?void 0:d.notp)||void 0===s?void 0:s.image),((e,t,n,i)=>{n&&Object.keys(n).forEach((s=>{t.querySelector(s)||i.debug(`Skipping css vars for component "${s}}"`,`Got css vars for component ${s} but Could not find it on next page`);const r=customElements.get(s);r?Object.keys(n[s]).forEach((t=>{var o;const a=n[s],c=null===(o=null==r?void 0:r.cssVarList)||void 0===o?void 0:o[t];if(!c)return void i.info(`Could not find css variable name for ${t} in ${s}`,"Check if the css variable is defined in the component");const l=a[t];e.style.setProperty(c,l)})):i.info(`Could not find component class for ${s}`,"Check if the component is registered")}))})(r,p,d.cssVars,this.loggerWrapper),r.replaceChildren(p);const c=!t.htmlFilename;setTimeout((()=>{i(this,Js,"m",pr).call(this),this.validateOnBlur&&(e=>{e.querySelectorAll("*[name]").forEach((e=>{e.addEventListener("blur",(()=>{var t;const n=e.focus;e.focus=()=>{},null===(t=e.reportValidity)||void 0===t||t.call(e),setTimeout((()=>{e.focus=n}))}))}))})(r),((e,t)=>{Oi(e,null==t?void 0:t.inputs),Oi(e,null==t?void 0:t.form)})(r,d),i(this,Js,"m",cr).call(this,{isFirstScreen:c,stepName:e.stepName}),((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}})(r,this.autoFocus,c)})),i(this,Js,"m",wr).call(this,l);r.querySelector(`[${Bn}="polling"]`)&&l(ei,{}),u&&!t.openInNewTabUrl&&window.open(u,"_blank")}));c?i(this,Js,"m",vr).call(this,m,c):m()}))}}Bs=new WeakMap,Vs=new WeakMap,zs=new WeakMap,Gs=new WeakMap,tr=new WeakMap,nr=new WeakMap,ir=new WeakMap,sr=new WeakMap,rr=new WeakMap,fr=new WeakMap,Js=new WeakSet,Qs=function(){document.hidden||setTimeout((()=>{this.flowState.update({deferredRedirect:!1})}),300)},Xs=function({errorText:e,errorType:t}){const n=()=>{var n;let i=e;try{i=(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(`[${Bn}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(this.contentRootElement,"error-message",i)};this.addEventListener("screen-updated",n,{once:!0}),n()},Zs=function(){var e,n;null===(e=this.stepState)||void 0===e||e.subscribe(this.onStepChange.bind(this),(e=>{var n=e.screenState,i=t(void 0===n?{}:n,["errorText","errorType"]),s=t(e,["screenState"]);return Object.assign(Object.assign({},s),{screenState:i})})),null===(n=this.stepState)||void 0===n||n.subscribe(i(this,Js,"m",Xs).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}}))},Ys=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")}))},er=function(e){return n(this,void 0,void 0,(function*(){var n;const s=Object.assign(Object.assign({},this.stepState.current),e),{next:r,stepName:o}=s,a=t(s,["next","stepName"]),c=Boolean(yield null===(n=this.onScreenUpdate)||void 0===n?void 0:n.call(this,o,_i(a),r,this));if(c){this.loggerWrapper.debug("Rendering a custom screen"),this.contentRootElement.innerHTML="",i(this,Js,"m",cr).call(this,{isFirstScreen:!this.stepState.current.htmlFilename,stepName:e.stepName}),this.stepState.unsubscribeAll();const t=this.stepState.subscribe((()=>{this.stepState.unsubscribe(t),i(this,Js,"m",Zs).call(this)}))}this.stepState.forceUpdate=c,i(this,tr,"f").call(this,c)}))},or=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)}))}},ar=function(e,t){return n(this,void 0,void 0,(function*(){var r;null===(r=i(this,Vs,"f"))||void 0===r||r.abort();const o=e.querySelector('*[autocomplete="webauthn"]');if(o&&(yield qi())){const{options:e,transactionId:r}=(yield i(this,rr,"f").call(this))||{};e&&r&&(i(this,Js,"m",or).call(this,o),s(this,Vs,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(e,i(this,Vs,"f")).then((e=>n(this,void 0,void 0,(function*(){t(o.id,{transactionId:r,response:e})})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},cr=function({isFirstScreen:e,stepName:t}){e&&i(this,Js,"m",_r).call(this,"ready",{}),i(this,Js,"m",_r).call(this,"page-updated",{screenName:t}),i(this,Js,"m",_r).call(this,"screen-updated",{screenName:t})},lr=function(){let e=!0;return Array.from(this.shadowRoot.querySelectorAll("*[name]")).reverse().forEach((t=>{var n,i;"slot"!==t.localName&&(null===(n=t.reportValidity)||void 0===n||n.call(t),e&&(e=null===(i=t.checkValidity)||void 0===i?void 0:i.call(t)))})),e},dr=function(){return n(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${An}])`));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})),{})}))},ur=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},hr=function(e={}){var t,n;const i=mi(e,["externalId","email","phone"]),s=mi(e,["newPassword","password"]);if(i&&s)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:i,password:s});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)}},pr=function(){document.querySelectorAll('[data-hidden-input="true"]').forEach((e=>e.remove()));this.contentRootElement.querySelectorAll('[external-input="true"]').forEach((e=>i(this,Js,"m",gr).call(this,e)))},gr=function(e){if(!e)return;e.querySelectorAll("input").forEach((t=>{const n=t.getAttribute("slot"),i=`input-${e.id}-${n}`,s=document.createElement("slot");s.setAttribute("name",i),s.setAttribute("slot",n),e.appendChild(s),t.setAttribute("slot",i),this.appendChild(t)}))},mr=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))&&i(this,fr,"f").call(this,t,e)}))}))},wr=function(e){this.contentRootElement.querySelectorAll(`descope-button:not([${jn}]), [data-type="button"]:not([${jn}]`).forEach((t=>{t.onclick=()=>{i(this,fr,"f").call(this,t,e)}})),i(this,Js,"m",mr).call(this,e),this.isDismissScreenErrorOnInput&&this.contentRootElement.querySelectorAll(`*[name]:not([${An}])`).forEach((e=>{e.addEventListener("input",(()=>{this.stepState.update((e=>Object.assign(Object.assign({},e),{screenState:Object.assign(Object.assign({},e.screenState),{errorText:"",errorType:""})})))}))}))},vr=function(e,t){this.contentRootElement.addEventListener("transitionend",(()=>{this.contentRootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===ii.forward?"slide-forward":"slide-backward";Array.from(this.contentRootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(n)})),this.contentRootElement.classList.add("fade-out")},_r=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.get("descope-wc")?console.log("descope-wc is already defined"):customElements.define("descope-wc",yr);var br,Sr,kr,Ir={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},xr=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(xr||{});(kr=xr||(xr={})).reset=function(){br=3,Sr=Ir},kr.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");br=e},kr.setLogger=function(e){Sr=e};var Cr=class e{constructor(e){this._name=e}debug(...t){br>=4&&Sr.debug(e._format(this._name,this._method),...t)}info(...t){br>=3&&Sr.info(e._format(this._name,this._method),...t)}warn(...t){br>=2&&Sr.warn(e._format(this._name,this._method),...t)}error(...t){br>=1&&Sr.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,n){const i=new e(`${t}.${n}`);return i.debug("begin"),i}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(t,...n){br>=4&&Sr.debug(e._format(t),...n)}static info(t,...n){br>=3&&Sr.info(e._format(t),...n)}static warn(t,...n){br>=2&&Sr.warn(e._format(t),...n)}static error(t,...n){br>=1&&Sr.error(e._format(t),...n)}};xr.reset();var Er=class{static decode(e){try{return a(e)}catch(e){throw Cr.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,n){const i=`${Ur.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${Ur.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,(new TextEncoder).encode(i));return`${i}.${Ur.encodeBase64Url(new Uint8Array(s))}`}},Tr=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),Or=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){const t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16)));return t.replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Tr(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw Cr.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const n=(new TextEncoder).encode([e,t].join(":"));return Tr(n)}static async hash(e,t){const n=(new TextEncoder).encode(t),i=await crypto.subtle.digest(e,n);return new Uint8Array(i)}static async customCalculateJwkThumbprint(t){let n;switch(t.kty){case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":n={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const i=await e.hash("SHA-256",JSON.stringify(n));return e.encodeBase64Url(i)}static async generateDPoPProof({url:t,accessToken:n,httpMethod:i,keyPair:s,nonce:r}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=i?i:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};n&&(o=await e.hash("SHA-256",n),a=e.encodeBase64Url(o),c.ath=a),r&&(c.nonce=r);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await Er.generateSignedJwt(t,c,s.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const n=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(n)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};Or.encodeBase64Url=e=>Tr(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Ur=Or,Rr=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Cr(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},Ar=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},jr=class e extends Rr{constructor(){super(...arguments),this._logger=new Cr(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const n=this._logger.create("init");t=Math.max(Math.floor(t),1);const i=e.getEpochTime()+t;if(this.expiration===i&&this._timerHandle)return void n.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),n.debug("using duration",t),this._expiration=i;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},Pr=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},Lr=";",qr=class extends Error{constructor(e,t){var n,i,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw Cr.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(i=e.error_uri)?i:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},$r=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},Nr=class{constructor(e){this._logger=new Cr("AccessTokenEvents"),this._expiringTimer=new jr("Access token expiring"),this._expiredTimer=new jr("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const i=n+1;t.debug("registering expired timer, raising in",i,"seconds"),this._expiredTimer.init(i)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},Mr=class{constructor(e,t,n,i,s){this._callback=e,this._client_id=t,this._intervalInSeconds=i,this._stopOnError=s,this._logger=new Cr("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const r=new URL(n);this._frame_origin=r.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=r.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},Dr=class{constructor(){this._logger=new Cr("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},Wr=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},Fr=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new Cr("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...i}=t;if(!n)return await fetch(e,i);const s=new AbortController,r=setTimeout((()=>s.abort()),1e3*n);try{return await fetch(e,{...t,signal:s.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new $r("Network timed out");throw e}finally{clearTimeout(r)}}async getJson(e,{token:t,credentials:n,timeoutInSeconds:i}={}){const s=this._logger.create("getJson"),r={Accept:this._contentTypes.join(", ")};let o;t&&(s.debug("token passed, setting Authorization header"),r.Authorization="Bearer "+t),this._appendExtraHeaders(r);try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:r,timeoutInSeconds:i,credentials:n})}catch(e){throw s.error("Network Error"),e}s.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(s.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(s.error("Error from server:",c),c.error)throw new qr(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:i,initCredentials:s,extraHeaders:r}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...r};let c;void 0!==n&&(a.Authorization="Basic "+n),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:i,credentials:s})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const d=await c.text();let u={};if(d)try{u=JSON.parse(d)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",u),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new Wr(e,`${JSON.stringify(u)}`)}if(u.error)throw new qr(u,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`)}return u}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),i=["accept","content-type"],s=["authorization"];0!==n.length&&n.forEach((n=>{if(i.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be set",n,i);if(s.includes(n.toLocaleLowerCase())&&Object.keys(e).includes(n))return void t.warn("Header could not be overridden",n,s);const r="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];r&&""!==r&&(e[n]=r)}))}},Hr=class{constructor(e){this._settings=e,this._logger=new Cr("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Fr(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const n=this._logger.create(`_getMetadataProperty('${e}')`),i=await this.getMetadata();if(n.debug("resolved"),void 0===i[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return i[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const n=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},Kr=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new Cr("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let n=0;n<e;n++){const e=await this._store.key(n);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Jr=class{constructor({authority:e,metadataUrl:t,metadata:n,signingKeys:i,metadataSeed:s,client_id:r,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:d,client_authentication:u="client_secret_post",prompt:h,display:p,max_age:g,ui_locales:f,acr_values:m,resource:w,response_mode:v,filterProtocolClaims:_=!0,loadUserInfo:y=!1,requestTimeoutInSeconds:b,staleStateAgeInSeconds:S=900,mergeClaimsStrategy:k={array:"replace"},disablePKCE:I=!1,stateStore:x,revokeTokenAdditionalContentTypes:C,fetchRequestCredentials:E,refreshTokenAllowedScope:T,extraQueryParams:O={},extraTokenParams:U={},extraHeaders:R={},dpop:A,omitScopeWhenRequesting:j=!1}){var P;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=n,this.metadataSeed=s,this.signingKeys=i,this.client_id=r,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=d,this.client_authentication=u,this.prompt=h,this.display=p,this.max_age=g,this.ui_locales=f,this.acr_values=m,this.resource=w,this.response_mode=v,this.filterProtocolClaims=null==_||_,this.loadUserInfo=!!y,this.staleStateAgeInSeconds=S,this.mergeClaimsStrategy=k,this.omitScopeWhenRequesting=j,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=C,this.fetchRequestCredentials=E||"same-origin",this.requestTimeoutInSeconds=b,x)this.stateStore=x;else{const e="undefined"!=typeof window?window.localStorage:new Dr;this.stateStore=new Kr({store:e})}if(this.refreshTokenAllowedScope=T,this.extraQueryParams=O,this.extraTokenParams=U,this.extraHeaders=R,this.dpop=A,this.dpop&&!(null==(P=this.dpop)?void 0:P.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Br=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Cr("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const n=Er.decode(e);return t.debug("JWT decoding successful"),n}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new Fr(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const i=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",i),i}},Vr=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Cr("TokenClient"),this._jsonService=new Fr(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:i=this._settings.client_secret,extraHeaders:s,...r}){const o=this._logger.create("exchangeCode");n||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),r.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(r))null!=t&&a.set(e,t);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==i)throw o.throw(new Error("A client_secret is required")),null;c=Ur.generateBasicAuth(n,i);break;case"client_secret_post":a.append("client_id",n),i&&a.append("client_secret",i)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),d}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:i=this._settings.scope,...s}){const r=this._logger.create("exchangeCredentials");t||r.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",i);for(const[e,t]of Object.entries(s))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw r.throw(new Error("A client_secret is required")),null;a=Ur.generateBasicAuth(t,n);break;case"client_secret_post":o.append("client_id",t),n&&o.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:i,extraHeaders:s,...r}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),r.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(r))Array.isArray(t)?t.forEach((t=>a.append(e,t))):null!=t&&a.set(e,t);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;c=Ur.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),d}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const i=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[t,n]of Object.entries(e))null!=n&&s.set(t,n);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(i,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),n.debug("got response")}},zr=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new Cr("ResponseValidator"),this._userInfoService=new Br(this._settings,this._metadataService),this._tokenClient=new Vr(this._settings,this._metadataService)}async validateSigninResponse(e,t,n){const i=this._logger.create("validateSigninResponse");this._processSigninState(e,t),i.debug("state processed"),await this._processCode(e,t,n),i.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),i.debug("claims processed")}async validateCredentialsResponse(e,t){const n=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const i=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,i),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new qr(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new qr(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const i=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void i.debug("not loading user info");i.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);i.debug("user info claims received from user info endpoint"),n&&s.sub!==e.profile.sub&&i.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),i.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,n){const i=this._logger.create("_processCode");if(e.code){i.debug("Validating code");const s=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:n,...t.extraTokenParams});Object.assign(e,s)}else i.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const s=Er.decode(null!=(n=e.id_token)?n:"");if(s.sub||i.throw(new Error("ID Token is missing a subject claim")),t){const e=Er.decode(t);s.sub!==e.sub&&i.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&i.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},Gr=class e{constructor(e){this.id=e.id||Ur.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=jr.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Cr("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return Cr.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,n){const i=Cr.createStatic("State","clearStaleState"),s=jr.getEpochTime()-n,r=await t.getAllKeys();i.debug("got keys",r);for(let n=0;n<r.length;n++){const o=r[n],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);i.debug("got item from key:",o,t.created),t.created<=s&&(c=!0)}catch(e){i.error("Error parsing state for key:",o,e),c=!0}else i.debug("no item in storage for key:",o),c=!0;c&&(i.debug("removed item for key:",o),t.remove(o))}}},Qr=class e extends Gr{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const n=!0===t.code_verifier?Ur.generateCodeVerifier():t.code_verifier||void 0,i=n?await Ur.generateCodeChallenge(n):void 0;return new e({...t,code_verifier:n,code_challenge:i})}toStorageString(){return new Cr("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){Cr.createStatic("SigninState","fromStorageString");const n=JSON.parse(t);return e.create(n)}},Xr=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:n,client_id:i,redirect_uri:s,response_type:r,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:d,nonce:u,url_state:h,resource:p,skipUserInfo:g,extraQueryParams:f,extraTokenParams:m,disablePKCE:w,dpopJkt:v,omitScopeWhenRequesting:_,...y}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!i)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!r)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const b=await Qr.create({data:a,request_type:l,url_state:h,code_verifier:!w,client_id:i,authority:n,redirect_uri:s,response_mode:c,client_secret:d,scope:o,extraTokenParams:m,skipUserInfo:g}),S=new URL(t);S.searchParams.append("client_id",i),S.searchParams.append("redirect_uri",s),S.searchParams.append("response_type",r),_||S.searchParams.append("scope",o),u&&S.searchParams.append("nonce",u),v&&S.searchParams.append("dpop_jkt",v);let k=b.id;if(h&&(k=`${k}${Lr}${h}`),S.searchParams.append("state",k),b.code_challenge&&(S.searchParams.append("code_challenge",b.code_challenge),S.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach((e=>S.searchParams.append("resource",e)))}for(const[e,t]of Object.entries({response_mode:c,...y,...f}))null!=t&&S.searchParams.append(e,t.toString());return new e({url:S.href,state:b})}};Xr._logger=new Cr("SigninRequest");var Zr,Yr,eo,to,no,io,so,ro,oo,ao,co,lo=Xr,uo=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(Lr);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Lr))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-jr.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+jr.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},ho=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:i,extraQueryParams:s,request_type:r,client_id:o,url_state:a}){if(this._logger=new Cr("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(n&&c.searchParams.append("id_token_hint",n),o&&c.searchParams.append("client_id",o),i&&(c.searchParams.append("post_logout_redirect_uri",i),t||a)){this.state=new Gr({data:t,request_type:r,url_state:a});let e=this.state.id;a&&(e=`${e}${Lr}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...s}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},po=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(Lr);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Lr))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},go=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],fo=["sub","iss","aud","exp","iat"],mo=class{constructor(e){this._settings=e,this._logger=new Cr("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:go;for(const n of e)fo.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[e,i]of Object.entries(t))if(n[e]!==i)if(Array.isArray(n[e])||Array.isArray(i))if("replace"==this._settings.mergeClaimsStrategy.array)n[e]=i;else{const t=Array.isArray(n[e])?n[e]:[n[e]];for(const e of Array.isArray(i)?i:[i])t.includes(e)||t.push(e);n[e]=t}else"object"==typeof n[e]&&"object"==typeof i?n[e]=this.mergeClaims(n[e],i):n[e]=i;return n}},wo=class{constructor(e,t){this.keys=e,this.nonce=t}},vo=class{constructor(e,t){this._logger=new Cr("OidcClient"),this.settings=e instanceof Jr?e:new Jr(e),this.metadataService=null!=t?t:new Hr(this.settings),this._claimsService=new mo(this.settings),this._validator=new zr(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Vr(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:i,id_token_hint:s,login_hint:r,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:d=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:g=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:w=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:_=this.settings.extraQueryParams,extraTokenParams:y=this.settings.extraTokenParams,dpopJkt:b,omitScopeWhenRequesting:S=this.settings.omitScopeWhenRequesting}){const k=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();k.debug("Received authorization endpoint",I);const x=await lo.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:l,scope:d,state_data:e,url_state:c,prompt:h,display:p,max_age:g,ui_locales:f,id_token_hint:s,login_hint:r,acr_values:m,dpopJkt:b,resource:w,request:t,request_uri:n,extraQueryParams:_,extraTokenParams:y,request_type:i,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:S});await this.clearStaleState();const C=x.state;return await this.settings.stateStore.set(C.id,C.toStorageString()),x}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),i=new uo(Pr.readParams(e,this.settings.response_mode));if(!i.state)throw n.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](i.state);if(!s)throw n.throw(new Error("No matching state found in storage")),null;return{state:await Qr.fromStorageString(s),response:i}}async processSigninResponse(e,t,n=!0){const i=this._logger.create("processSigninResponse"),{state:s,response:r}=await this.readSigninResponseState(e,n);if(i.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(r,s,t)}catch(e){if(!(e instanceof Wr&&this.settings.dpop))throw e;{const n=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=n,await this._validator.validateSigninResponse(r,s,t)}}return r}async getDpopProof(e,t){let n,i;return(await e.getAllKeys()).includes(this.settings.client_id)?(i=await e.get(this.settings.client_id),i.nonce!==t&&t&&(i.nonce=t,await e.set(this.settings.client_id,i))):(n=await Ur.generateDPoPKeys(),i=new wo(n,t),await e.set(this.settings.client_id,i)),await Ur.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:i.keys,nonce:i.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:i={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...i}),r=new uo(new URLSearchParams);return Object.assign(r,s),await this._validator.validateCredentialsResponse(r,n),r}async useRefreshToken({state:e,redirect_uri:t,resource:n,timeoutInSeconds:i,extraHeaders:s,extraTokenParams:r}){var o;const a=this._logger.create("useRefreshToken");let c,l;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);s={...s,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:n,timeoutInSeconds:i,extraHeaders:s,...r})}catch(o){if(!(o instanceof Wr&&this.settings.dpop))throw o;s.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:n,timeoutInSeconds:i,extraHeaders:s,...r})}const d=new uo(new URLSearchParams);return Object.assign(d,l),a.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...e,scope:c}),d}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:i,url_state:s,post_logout_redirect_uri:r=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),n||!r||t||(n=this.settings.client_id);const l=new ho({url:c,id_token_hint:t,client_id:n,post_logout_redirect_uri:r,state_data:e,extraQueryParams:o,request_type:i,url_state:s});await this.clearStaleState();const d=l.state;return d&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(d.id,d.toStorageString())),l}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),i=new po(Pr.readParams(e,this.settings.response_mode));if(!i.state){if(n.debug("No state in response"),i.error)throw n.warn("Response was error:",i.error),new qr(i);return{state:void 0,response:i}}const s=await this.settings.stateStore[t?"remove":"get"](i.state);if(!s)throw n.throw(new Error("No matching state found in storage")),null;return{state:await Gr.fromStorageString(s),response:i}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:i}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,n)):t.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),Gr.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},_o=class{constructor(e){this._userManager=e,this._logger=new Cr("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const i=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,r=this._userManager.settings.stopCheckSessionOnError,o=new Mr(this._callback,i,e,s,r);await o.load(),this._checkSessionIFrame=o,o.start(t)}else n.warn("no check session iframe found in the metadata")}catch(e){n.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),n?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},yo=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-jr.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+jr.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new Cr("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return Cr.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},bo="oidc-client",So=class{constructor(){this._abort=new Rr("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:n,keepOpen:i}=await new Promise(((n,i)=>{const s=s=>{var r;const o=s.data,a=null!=(r=e.scriptOrigin)?r:window.location.origin;if(s.origin===a&&(null==o?void 0:o.source)===bo){try{const n=Pr.readParams(o.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),s.source!==this._window&&n!==e.state)return}catch{this._dispose(),i(new Error("Invalid response from window"))}n(o)}};window.addEventListener("message",s,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",s,!1))),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),i(e)})))}));return t.debug("got response from window"),this._dispose(),i||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,i=window.location.origin){e.postMessage({source:bo,url:t,keepOpen:n},i)}},ko={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Io="_blank",xo=60,Co=2,Eo=class extends Jr{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:i=ko,popupWindowTarget:s=Io,redirectMethod:r="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:d=e.redirect_uri,silentRequestTimeoutInSeconds:u,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:g=!1,monitorSession:f=!1,monitorAnonymousSession:m=!1,checkSessionIntervalInSeconds:w=Co,query_status_response_type:v="code",stopCheckSessionOnError:_=!0,revokeTokenTypes:y=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:S=!1,accessTokenExpiringNotificationTimeInSeconds:k=xo,userStore:I}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=i,this.popupWindowTarget=s,this.redirectMethod=r,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=d,this.silentRequestTimeoutInSeconds=u||l||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=g,this.monitorSession=f,this.monitorAnonymousSession=m,this.checkSessionIntervalInSeconds=w,this.stopCheckSessionOnError=_,this.query_status_response_type=v,this.revokeTokenTypes=y,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=S,this.accessTokenExpiringNotificationTimeInSeconds=k,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new Dr;this.userStore=new Kr({store:e})}}},To=class e extends So{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new Cr("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new $r("IFrame timed out without a response"))}),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const n=e.target;null==(t=n.parentNode)||t.removeChild(n),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},Oo=class{constructor(e){this._settings=e,this._logger=new Cr("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new To({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),To.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Uo=class extends So{constructor({popupWindowTarget:e=Io,popupWindowFeatures:t={},popupSignal:n}){super(),this._logger=new Cr("PopupWindow");const i=Ar.center({...ko,...t});this._window=window.open(void 0,e,Ar.serialize(i)),n&&n.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=n.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const n=setInterval((()=>{this._window&&!this._window.closed||this._abort.raise(new Error("Popup closed by user"))}),500);return this._disposeHandlers.add((()=>clearInterval(n))),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,e,t)}},Ro=class{constructor(e){this._settings=e,this._logger=new Cr("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:n}){return new Uo({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Uo.notifyOpener(e,t)}},Ao=class{constructor(e){this._settings=e,this._logger=new Cr("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let i=window.self;"top"===t&&(i=null!=(n=window.top)?n:window.self);const s=i.location[e].bind(i.location);let r;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{r=t}));return s(e.url),await t},close:()=>{this._logger.create("close"),null==r||r(new Error("Redirect aborted")),i.stop()}}}async callback(){}},jo=class extends Nr{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new Cr("UserManagerEvents"),this._userLoaded=new Rr("User loaded"),this._userUnloaded=new Rr("User unloaded"),this._silentRenewError=new Rr("Silent renew error"),this._userSignedIn=new Rr("User signed in"),this._userSignedOut=new Rr("User signed out"),this._userSessionChanged=new Rr("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Po=class{constructor(e){this._userManager=e,this._logger=new Cr("SilentRenewService"),this._isStarted=!1,this._retryTimer=new jr("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof $r)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Lo=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},qo=Object.freeze({__proto__:null,AccessTokenEvents:Nr,CheckSessionIFrame:Mr,DPoPState:wo,ErrorResponse:qr,ErrorTimeout:$r,InMemoryWebStorage:Dr,IndexedDbDPoPStore:class{constructor(){this._dbName="oidc",this._storeName="dpop"}async set(e,t){const n=await this.createStore(this._dbName,this._storeName);await n("readwrite",(n=>(n.put(t,e),this.promisifyRequest(n.transaction))))}async get(e){const t=await this.createStore(this._dbName,this._storeName);return await t("readonly",(t=>this.promisifyRequest(t.get(e))))}async remove(e){const t=await this.get(e),n=await this.createStore(this._dbName,this._storeName);return await n("readwrite",(t=>this.promisifyRequest(t.delete(e)))),t}async getAllKeys(){const e=await this.createStore(this._dbName,this._storeName);return await e("readonly",(e=>this.promisifyRequest(e.getAllKeys())))}promisifyRequest(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}async createStore(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const i=await this.promisifyRequest(n);return async(e,n)=>{const s=i.transaction(t,e).objectStore(t);return await n(s)}}},get Log(){return xr},Logger:Cr,MetadataService:Hr,OidcClient:vo,OidcClientSettingsStore:Jr,SessionMonitor:_o,SigninResponse:uo,SigninState:Qr,SignoutResponse:po,State:Gr,User:yo,UserManager:class{constructor(e,t,n,i){this._logger=new Cr("UserManager"),this.settings=new Eo(e),this._client=new vo(e),this._redirectNavigator=null!=t?t:new Ao(this.settings),this._popupNavigator=null!=n?n:new Ro(this.settings),this._iframeNavigator=null!=i?i:new Oo(this.settings),this._events=new jo(this.settings),this._silentRenewService=new Po(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new _o(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),n=await this._loadUser();return n?(t.info("user loaded"),await this._events.load(n,e),n):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:n,...i}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const r=await this._redirectNavigator.prepare({redirectMethod:n});await this._signinStart({request_type:"si:r",dpopJkt:s,...i},r)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const i=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});i.debug("got signin response");const r=await this._buildUser(s);return r.profile&&r.profile.sub?i.info("success, signed in subject",r.profile.sub):i.info("no subject"),r}async signinPopup(e={}){var t;const n=this._logger.create("signinPopup");let i;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(i=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:r,popupSignal:o,...a}=e,c=this.settings.popup_redirect_uri;c||n.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:r,popupSignal:o}),d=await this._signin({request_type:"si:p",redirect_uri:c,display:"popup",dpopJkt:i,...a},l);return d&&(d.profile&&d.profile.sub?n.info("success, signed in subject",d.profile.sub):n.info("no subject")),d}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t,n;const i=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...r}=e;let o,a=await this._loadUser();if(null==a?void 0:a.refresh_token){i.debug("using refresh token");const e=new Lo(a);return await this._useRefreshToken({state:e,redirect_uri:r.redirect_uri,resource:r.resource,extraTokenParams:r.extraTokenParams,timeoutInSeconds:s})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let l;c||i.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(i.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const d=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...r},d,l),a&&((null==(n=a.profile)?void 0:n.sub)?i.info("success, signed in subject",a.profile.sub):i.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),n=new yo({...e.state,...t});return await this.storeUser(n),await this._events.load(n),n}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:n,...i}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const r=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==r?void 0:r.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...i},o);try{const e={},n=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),n.session_state&&n.profile.sub?(t.info("success for subject",n.profile.sub),{session_state:n.session_state,sub:n.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof qr)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,n){const i=await this._signinStart(e,t);return await this._signinEnd(i.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const i=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:i.url,state:i.state.id,response_mode:i.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),i=await this._client.processSigninResponse(e,{});n.debug("got signin response");return await this._buildUser(i,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),i=new yo(e);if(t){if(t!==i.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",i.profile.sub),new qr({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(i),n.debug("user stored"),await this._events.load(i),i}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...i}=e,s=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...i},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:i,popupSignal:s,...r}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:i,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...r},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const i=this._logger.create("_signoutStart");try{const s=await this._loadUser();i.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const r=e.id_token_hint||s&&s.id_token;r&&(i.debug("setting id_token_hint in signout request"),e.id_token_hint=r),await this.removeUser(),i.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return i.debug("got signout request"),await t.navigate({url:o.url,state:null==(n=o.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:i,...s}=e,r=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:r,...s},a),n.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const n=this._logger.create("_revokeInternal");if(!e)return;const i=t.filter((t=>"string"==typeof e[t]));if(i.length){for(const t of i)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),await this._events.load(e)}else n.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),yo.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,n,i){var s,r;const o=await(null==(r=null==(s=this.settings.dpop)?void 0:s.store)?void 0:r.get(this.settings.client_id));if(o)return await Ur.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:n,keyPair:o.keys,nonce:i})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const n=await Ur.generateDPoPKeys();t=new wo(n),await e.store.set(this.settings.client_id,t)}return await Ur.generateDPoPJkt(t.keys)}},UserManagerSettingsStore:Eo,Version:"3.2.0",WebStorageStateStore:Kr});const $o=document.createElement("template");$o.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';class No extends HTMLElement{constructor(){super(),Zr.add(this),Yr.set(this,new xi({messages:[]})),eo.set(this,void 0),to.set(this,void 0),no.set(this,void 0),io.set(this,{resize:i(this,Zr,"m",co).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild($o.content.cloneNode(!0)),s(this,eo,this.shadowRoot.querySelector(".debugger"),"f"),s(this,to,i(this,eo,"f").querySelector(".content"),"f"),s(this,no,i(this,eo,"f").querySelector(".header"),"f"),i(this,Zr,"m",so).call(this)}updateData(e){i(this,Yr,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let i=0,s=0,r=0,o=0;function a(t){t.preventDefault(),i=r-t.clientX,s=o-t.clientY,r=t.clientX,o=t.clientY;const[a,c]=$i(e,e.offsetLeft-i,e.offsetTop-s,n);e.style.top=`${c}px`,e.style.left=`${a}px`}function c(){document.onmouseup=null,document.onmousemove=null}function l(e){e.preventDefault(),r=e.clientX,o=e.clientY,document.onmouseup=c,document.onmousemove=a}t?t.onmousedown=l:e.onmousedown=l})(i(this,eo,"f"),i(this,no,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",i(this,io,"f").resize),(e=i(this,eo,"f")).onmousemove=t=>{(t.target.w&&t.target.w!==t.target.offsetWidth||t.target.h&&t.target.h!==t.target.offsetHeight)&&e.onresize(t),t.target.w=t.target.offsetWidth,t.target.h=t.target.offsetHeight},i(this,eo,"f").onresize=i(this,Zr,"m",ao).bind(this),i(this,Yr,"f").subscribe(i(this,Zr,"m",ro).bind(this))}disconnectedCallback(){i(this,Yr,"f").unsubscribeAll(),window.removeEventListener("resize",i(this,io,"f").resize)}}Yr=new WeakMap,eo=new WeakMap,to=new WeakMap,no=new WeakMap,io=new WeakMap,Zr=new WeakSet,so=function(){var e,t;const n=new CSSStyleSheet;n.replaceSync('\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'),null!==(e=(t=this.shadowRoot).adoptedStyleSheets)&&void 0!==e||(t.adoptedStyleSheets=[]),this.shadowRoot.adoptedStyleSheets=[...this.shadowRoot.adoptedStyleSheets,n],i(this,eo,"f").style.top="32px",i(this,eo,"f").style.left=window.innerWidth-300-32+"px"},ro=function(e){i(this,Zr,"m",oo).call(this,e),i(this,Zr,"m",ao).call(this)},oo=function(e){i(this,to,"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("")},ao=function(){i(this,to,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,i=t.clientHeight>20;n||i?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},co=function(){const[e,t]=$i(i(this,eo,"f"),Number.parseInt(i(this,eo,"f").style.left,10),Number.parseInt(i(this,eo,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});i(this,eo,"f").style.top=`${t}px`,i(this,eo,"f").style.left=`${e}px`},customElements.get("descope-debugger")||customElements.define("descope-debugger",No);var Mo=Object.freeze({__proto__:null,default:No});const Do='\n(function () {\nvar merchantConfig = {\n csp: false\n};\n\nvar siteId = "{{SITE_ID}}";\nfunction t(t,n){for(var e=t.split(""),r=0;r<e.length;++r)e[r]=String.fromCharCode(e[r].charCodeAt(0)+n);return e.join("")}function n(n){return t(n,-L).replace(/%SN%/g,siteId)}function e(){var t="no"+"op"+"fn",n="g"+"a",e="n"+"ame";return window[n]&&window[n][e]===t}function r(){return!(!navigator.brave||"function"!=typeof navigator.brave.isBrave)}function o(){return document.currentScript&&document.currentScript.src}function i(t){try{if("number"==typeof t&&window.location&&window.location.pathname){for(var n=window.location.pathname.split("/"),e=[],r=0;r<=Math.min(n.length-1,Math.abs(t));r++)e.push(n[r]);return e.join("/")||"/"}}catch(t){}return"/"}function c(t){try{G.ex=t,e()&&-1===G.ex.indexOf(B.uB)&&(G.ex+=B.uB),r()&&-1===G.ex.indexOf(B.uBr)&&(G.ex+=B.uBr),o()&&-1===G.ex.indexOf(B.nIL)&&(G.ex+=B.nIL),window.ftr__snp_cwc||(G.ex+=B.s),M(G)}catch(t){}}function a(t,n){function e(o){try{o.blockedURI===t&&(n(),document.removeEventListener(r,e))}catch(t){document.removeEventListener(r,e)}}var r="securitypolicyviolation";document.addEventListener(r,e),setTimeout(function(){document.removeEventListener(r,e)},2*60*1e3)}function u(t,n,e,r){var o=!1;t="https://"+t,a(t,function(){r(!0),o=!0});var i=document.createElement("script");i.onerror=function(){if(!o)try{r(!1),o=!0}catch(t){}},i.onload=e,i.type="text/javascript",i.id="ftr__script",i.async=!0,i.src=t;var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(i,c)}function f(){J(B.uDF),setTimeout(h,I,B.uDF)}function d(t,n,e,r){var o=!1,i=new XMLHttpRequest;if(a("https:"+t,function(){e(new Error("CSP Violation"),!0),o=!0}),"//"===t.slice(0,2)&&(t="https:"+t),"withCredentials"in i)i.open("GET",t,!0);else{if("undefined"==typeof XDomainRequest)return;i=new XDomainRequest,i.open("GET",t)}Object.keys(r).forEach(function(t){i.setRequestHeader(t,r[t])}),i.onload=function(){"function"==typeof n&&n(i)},i.onerror=function(t){if("function"==typeof e&&!o)try{e(t,!1),o=!0}catch(t){}},i.onprogress=function(){},i.ontimeout=function(){"function"==typeof e&&e("tim"+"eo"+"ut",!1)},setTimeout(function(){i.send()},0)}function s(t,siteId,n){function e(t){var n=t.toString(16);return n.length%2?"0"+n:n}function r(t){if(t<=0)return"";for(var n="0123456789abcdef",e="",r=0;r<t;r++)e+=n[Math.floor(Math.random()*n.length)];return e}function o(t){for(var n="",r=0;r<t.length;r++)n+=e(t.charCodeAt(r));return n}function i(t){for(var n=t.split(""),e=0;e<n.length;++e)n[e]=String.fromCharCode(255^n[e].charCodeAt(0));return n.join("")}n=n?"1":"0";var c=[];return c.push(t),c.push(siteId),c.push(n),function(t){var n=40,e="";return t.length<n/2&&(e=","+r(n/2-t.length-1)),o(i(t+e))}(c.join(","))}function w(){function t(){D&&(J(B.dUAL),setTimeout(h,I,B.dUAL))}function n(t,n){c(n?B.uAS+B.uF+B.cP:B.uAS+B.uF)}window.ftr__fdad(t,n)}function h(t){try{var n;switch(t){case B.uFP:n=q;break;case B.uDF:n=E;break;default:n=D}if(!n)return;u(n,void 0,function(){try{K(),c(t+B.uS)}catch(t){}},function(n){try{K(),G.td=1*new Date-G.ts,c(n?t+B.uF+B.cP:t+B.uF),t===B.uFP&&f(),t===B.uDF&&w()}catch(t){c(B.eUoe)}})}catch(n){c(t+B.eTlu)}}var m="22ge:t7mj8unkn;1forxgiurqw1qhw2vwdwxv",v="fort",l="erTo",p="ken";window.ftr__config={m:merchantConfig,s:"23",si:siteId};var g=!1,_=v+l+p,y=400*24*60,T=10,k={write:function(t,n,e,r){void 0===r&&(r=!0);var o=0;window.ftr__config&&window.ftr__config.m&&window.ftr__config.m.ckDepth&&(o=window.ftr__config.m.ckDepth);var c,a,u=i(o);if(e?(c=new Date,c.setTime(c.getTime()+60*e*1e3),a="; expires="+c.toGMTString()):a="",!r)return void(document.cookie=escape(t)+"="+escape(n)+a+"; path="+u);for(var f=1,d=document.domain.split("."),s=T,w=!0;w&&d.length>=f&&s>0;){var h=d.slice(-f).join(".");document.cookie=escape(t)+"="+escape(n)+a+"; path="+u+"; domain="+h;var m=k.read(t);null!=m&&m==n||(h="."+h,document.cookie=escape(t)+"="+escape(n)+a+"; path="+u+"; domain="+h),w=-1===document.cookie.indexOf(t+"="+n),f++,s--}},read:function(t){var n=null;try{for(var e=escape(t)+"=",r=document.cookie.split(";"),o=32,i=0;i<r.length;i++){for(var c=r[i];c.charCodeAt(0)===o;)c=c.substring(1,c.length);0===c.indexOf(e)&&(n=unescape(c.substring(e.length,c.length)))}}finally{return n}}},S=window.ftr__config.s;S+="ck";var x=function(t){var n=!1,e=null,r=function(){try{if(!e||!n)return;e.remove&&"function"==typeof e.remove?e.remove():document.head.removeChild(e),n=!1}catch(t){}};document.head&&(!function(){e=document.createElement("link"),e.setAttribute("rel","pre"+"con"+"nect"),e.setAttribute("cros"+"sori"+"gin","anonymous"),e.onload=r,e.onerror=r,e.setAttribute("href",t),document.head.appendChild(e),n=!0}(),setTimeout(r,3e3))},L=3,A=n(m||"22ge:t7mj8unkn;1forxgiurqw1qhw2vwdwxv"),F=t("[0Uhtxhvw0LG",-L),U=t("[0Fruuhodwlrq0LG",-L),b=t("Li0Qrqh0Pdwfk",-L),D,C="fgq71iruwhu1frp",E=n("(VQ(1"+C+"2vq2(VQ(2vfulsw1mv"),V=n("(VQ(1"+C+"2vqV2(VQ(2vfulsw1mv"),q;window.ftr__config&&window.ftr__config.m&&window.ftr__config.m.fpi&&(q=window.ftr__config.m.fpi+n("2vq2(VQ(2vfulsw1mv"));var I=10;window.ftr__startScriptLoad=1*new Date;var R=function(t){var n="ft"+"r:tok"+"enR"+"eady";window.ftr__tt&&clearTimeout(window.ftr__tt),window.ftr__tt=setTimeout(function(){try{delete window.ftr__tt,t+="_tt";var e=document.createEvent("Event");e.initEvent(n,!1,!1),e.detail=t,document.dispatchEvent(e)}catch(t){}},1e3)},M=function(t){var n=function(t){return t||""},e=n(t.id)+"_"+n(t.ts)+"_"+n(t.td)+"_"+n(t.ex)+"_"+n(S),r=y;!isNaN(window.ftr__config.m.ckTTL)&&window.ftr__config.m.ckTTL&&(r=window.ftr__config.m.ckTTL),k.write(_,e,r,!0),R(e),window.ftr__gt=e},P=function(){var t=k.read(_)||"",n=t.split("_"),e=function(t){return n[t]||void 0};return{id:e(0),ts:e(1),td:e(2),ex:e(3),vr:e(4)}},j=function(){for(var t={},n="fgu",e=[],r=0;r<256;r++)e[r]=(r<16?"0":"")+r.toString(16);var o=function(t,n,r,o,i){var c=i?"-":"";return e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]+c+e[255&n]+e[n>>8&255]+c+e[n>>16&15|64]+e[n>>24&255]+c+e[63&r|128]+e[r>>8&255]+c+e[r>>16&255]+e[r>>24&255]+e[255&o]+e[o>>8&255]+e[o>>16&255]+e[o>>24&255]},i=function(){if(window.Uint32Array&&window.crypto&&window.crypto.getRandomValues){var t=new window.Uint32Array(4);return window.crypto.getRandomValues(t),{d0:t[0],d1:t[1],d2:t[2],d3:t[3]}}return{d0:4294967296*Math.random()>>>0,d1:4294967296*Math.random()>>>0,d2:4294967296*Math.random()>>>0,d3:4294967296*Math.random()>>>0}},c=function(){var t="",n=function(t,n){for(var e="",r=t;r>0;--r)e+=n.charAt(1e3*Math.random()%n.length);return e};return t+=n(2,"0123456789"),t+=n(1,"123456789"),t+=n(8,"0123456789")};return t.safeGenerateNoDash=function(){try{var t=i();return o(t.d0,t.d1,t.d2,t.d3,!1)}catch(t){try{return n+c()}catch(t){}}},t.isValidNumericalToken=function(t){return t&&t.toString().length<=11&&t.length>=9&&parseInt(t,10).toString().length<=11&&parseInt(t,10).toString().length>=9},t.isValidUUIDToken=function(t){return t&&32===t.toString().length&&/^[a-z0-9]+$/.test(t)},t.isValidFGUToken=function(t){return 0==t.indexOf(n)&&t.length>=12},t}(),B={uDF:"UDF",dUAL:"dUAL",uAS:"UAS",uFP:"UFP",mLd:"1",eTlu:"2",eUoe:"3",uS:"4",uF:"9",tmos:["T5","T10","T15","T30","T60"],tmosSecs:[5,10,15,30,60],bIR:"43",uB:"u",uBr:"b",cP:"c",nIL:"i",s:"s"};try{var G=P();try{G.id&&(j.isValidNumericalToken(G.id)||j.isValidUUIDToken(G.id)||j.isValidFGUToken(G.id))?window.ftr__ncd=!1:(G.id=j.safeGenerateNoDash(),window.ftr__ncd=!0),G.ts=window.ftr__startScriptLoad,M(G),window.ftr__snp_cwc=!!k.read(_),window.ftr__snp_cwc||(E=V);for(var N="for"+"ter"+".co"+"m",O="ht"+"tps://c"+"dn9."+N,Q="ht"+"tps://"+G.id+"-"+siteId+".cd"+"n."+N,H="http"+"s://cd"+"n3."+N,X=[O,Q,H],z=0;z<X.length;z++)x(X[z]);var $=new Array(B.tmosSecs.length),J=function(t){for(var n=0;n<B.tmosSecs.length;n++)$[n]=setTimeout(c,1e3*B.tmosSecs[n],t+B.tmos[n])},K=function(){for(var t=0;t<B.tmosSecs.length;t++)clearTimeout($[t])};window.ftr__fdad=function(n,e){if(!g){g=!0;var r={};r[b]=s(window.ftr__config.s,siteId,window.ftr__config.m.csp),d(A,function(e){try{var r=e.getAllResponseHeaders().toLowerCase();if(r.indexOf(U.toLowerCase())>=0){var o=e.getResponseHeader(U);window.ftr__altd2=t(atob(o),-L-1)}if(r.indexOf(F.toLowerCase())<0)return;var i=e.getResponseHeader(F),c=t(atob(i),-L-1);if(c){var a=c.split(":");if(a&&2===a.length){for(var u=a[0],f=a[1],d="",s=0,w=0;s<20;++s)d+=s%3>0&&w<12?siteId.charAt(w++):G.id.charAt(s);var h=f.split(",");if(h.length>1){var m=h[0],v=h[1];D=u+"/"+m+"."+d+"."+v}}}n()}catch(t){}},function(t,n){e&&e(t,n)},r)}};var W=q?B.uFP:B.uDF;J(W),setTimeout(h,I,W)}catch(t){c(B.mLd)}}catch(t){}})();\n';var Wo=Object.freeze({__proto__:null,default:(e,t,i)=>n(void 0,void 0,void 0,(function*(){const{siteId:t}=e,n=Do.replace(/{{SITE_ID}}/g,t),s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("id",t),s.text=n,document.body.appendChild(s),document.addEventListener("ftr:tokenReady",(e=>{i(e.detail)}))}))});const Fo=(e,t,i)=>n(void 0,void 0,void 0,(function*(){try{const{publicApiKey:t,useCloudflareIntegration:n,cloudflareScriptUrl:s,cloudflareEndpointUrl:r}=e;let o=[];o=n&&r?[r,ft]:[ft];let a=[];if(n&&s){const e=new URL(s);a=[`${e.toString()}?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>`,St]}else a=[St];const c=kt({apiKey:t,endpoint:o,scriptUrlPattern:a}),l=yield c,{requestId:d}=yield l.get();i(d)}catch(e){console.warn("Could not load fingerprint",e)}}));var Ho=Object.freeze({__proto__:null,default:Fo,loadFingerprint:Fo});const Ko=(e,t,i)=>n(void 0,void 0,void 0,(function*(){try{const{customDomain:n,publicApiKey:s,cloudflareEndpointPath:r,cloudflareScriptPath:o}=e,{baseUrl:a}=t;let c;c=n?`https://${n}`:a||"https://api.descope.com";const l=new URL(c);l.pathname=r;const d=new URL(c);d.pathname=o;const u=`${d.toString()}?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>`,h=kt({apiKey:s,endpoint:[l.toString(),ft],scriptUrlPattern:[u,St]}),p=yield h,{requestId:g}=yield p.get();i(g)}catch(e){console.warn("Could not load descope fingerprint",e)}}));var Jo=Object.freeze({__proto__:null,default:Ko,loadFingerprint:Ko});const Bo=105e3,Vo=(e,t,i)=>{let s=(new Date).getTime();const r=()=>{var t;return e.enterprise?null===(t=window.grecaptcha)||void 0===t?void 0:t.enterprise:window.grecaptcha};let o,a;const c=(t,n)=>{t.ready((()=>{e.siteKey&&(null==t||t.execute(a,{action:"load"}).then(((e,n)=>{n?console.warn("could not execute recaptcha",n):(i(e),s=(new Date).getTime(),o=setTimeout((()=>{c(t)}),Bo))})))}))},l=()=>{clearTimeout(o)},d=(()=>{const e=document.createElement("div");return e.style.display="none",e.id="recaptcha",document.body.appendChild(e)})(),u=()=>{const e=r();e&&c(e)};return window.onRecaptchaLoadCallback=()=>{const t=d;if(t.hasChildNodes())return;const n=r();n&&setTimeout((()=>{a=n.render(t,{sitekey:e.siteKey,badge:"inline",size:"invisible"}),c(n)}),0)},(()=>{const t=document.createElement("script");t.src=(()=>{const t=new URL("https://www.google.com/recaptcha/");return t.pathname+=(e.enterprise?"enterprise":"api")+".js",t.searchParams.append("onload","onRecaptchaLoadCallback"),t.searchParams.append("render","explicit"),t.toString()})(),t.async=!0,t.id="recaptcha-script",t.defer=!0,document.body.appendChild(t)})(),{stop:l,start:u,refresh:()=>n(void 0,void 0,void 0,(function*(){if(Date.now()-s>Bo){l();const e=s;return u(),new Promise((t=>{const n=setTimeout((()=>{console.warn("reCAPTCHA token refresh timed out"),t()}),5e3),i=()=>{s!==e?(clearTimeout(n),t()):setTimeout(i,150)};i()}))}return Promise.resolve()}))}};var zo=Object.freeze({__proto__:null,default:Vo,loadGRecaptcha:Vo})}();
|