@descope/react-sdk 2.0.4 → 2.0.5
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/README.md +3 -1
- package/dist/cjs/index.cjs.js +1 -1
- package/dist/index.d.ts +32 -132
- package/dist/index.esm.js +1 -1
- package/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -2
package/dist/index.umd.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Descope={},e.React)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(t);const r=o.default.createContext(void 0),i=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},s=e=>(...t)=>{let n;try{n=e(...t)}catch(e){console.error(e)}return n},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"2.0.4"},l="undefined"!=typeof window;var c=function(){return c=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},c.apply(this,arguments)};function d(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function u(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}))}function h(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function p(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function f(e){this.message=e}"function"==typeof SuppressedError&&SuppressedError,f.prototype=new Error,f.prototype.name="InvalidCharacterError";var g="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new f("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,r=0,i=0,s="";o=t.charAt(i++);~o&&(n=r%4?64*n+o:o,r++%4)?s+=String.fromCharCode(255&n>>(-2*r&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return s};function v(e){this.message=e}function m(e,t){if("string"!=typeof e)throw new v("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(g(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return g(t)}}(e.split(".")[n]))}catch(e){throw new v("Invalid token specified: "+e.message)}}v.prototype=new Error,v.prototype.name="InvalidTokenError";var b="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y="__lodash_hash_undefined__",I="[object Function]",k="[object GeneratorFunction]",S=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,j=/^\w*$/,x=/^\./,C=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,O=/\\(\\)?/g,E=/^\[object .+?Constructor\]$/,A="object"==typeof b&&b&&b.Object===Object&&b,U="object"==typeof self&&self&&self.Object===Object&&self,R=A||U||Function("return this")();var T,_=Array.prototype,P=Function.prototype,L=Object.prototype,M=R["__core-js_shared__"],$=(T=/[^.]+$/.exec(M&&M.keys&&M.keys.IE_PROTO||""))?"Symbol(src)_1."+T:"",D=P.toString,W=L.hasOwnProperty,q=L.toString,N=RegExp("^"+D.call(W).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),F=R.Symbol,K=_.splice,J=te(R,"Map"),H=te(Object,"create"),z=F?F.prototype:void 0,V=z?z.toString:void 0;function B(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function G(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Y(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Z(e,t){for(var n,o,r=e.length;r--;)if((n=e[r][0])===(o=t)||n!=n&&o!=o)return r;return-1}function X(e,t){var n;t=function(e,t){if(ie(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||ae(e))return!0;return j.test(e)||!S.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:ie(n=t)?n:ne(n);for(var o=0,r=t.length;null!=e&&o<r;)e=e[oe(t[o++])];return o&&o==r?e:void 0}function Q(e){if(!se(e)||(t=e,$&&$ in t))return!1;var t,n=function(e){var t=se(e)?q.call(e):"";return t==I||t==k}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?N:E;return n.test(function(e){if(null!=e){try{return D.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function ee(e,t){var n,o,r=e.__data__;return("string"==(o=typeof(n=t))||"number"==o||"symbol"==o||"boolean"==o?"__proto__"!==n:null===n)?r["string"==typeof t?"string":"hash"]:r.map}function te(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Q(n)?n:void 0}B.prototype.clear=function(){this.__data__=H?H(null):{}},B.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},B.prototype.get=function(e){var t=this.__data__;if(H){var n=t[e];return n===y?void 0:n}return W.call(t,e)?t[e]:void 0},B.prototype.has=function(e){var t=this.__data__;return H?void 0!==t[e]:W.call(t,e)},B.prototype.set=function(e,t){return this.__data__[e]=H&&void 0===t?y:t,this},G.prototype.clear=function(){this.__data__=[]},G.prototype.delete=function(e){var t=this.__data__,n=Z(t,e);return!(n<0)&&(n==t.length-1?t.pop():K.call(t,n,1),!0)},G.prototype.get=function(e){var t=this.__data__,n=Z(t,e);return n<0?void 0:t[n][1]},G.prototype.has=function(e){return Z(this.__data__,e)>-1},G.prototype.set=function(e,t){var n=this.__data__,o=Z(n,e);return o<0?n.push([e,t]):n[o][1]=t,this},Y.prototype.clear=function(){this.__data__={hash:new B,map:new(J||G),string:new B}},Y.prototype.delete=function(e){return ee(this,e).delete(e)},Y.prototype.get=function(e){return ee(this,e).get(e)},Y.prototype.has=function(e){return ee(this,e).has(e)},Y.prototype.set=function(e,t){return ee(this,e).set(e,t),this};var ne=re((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(ae(e))return V?V.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return x.test(e)&&n.push(""),e.replace(C,(function(e,t,o,r){n.push(o?r.replace(O,"$1"):t||e)})),n}));function oe(e){if("string"==typeof e||ae(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function re(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var o=arguments,r=t?t.apply(this,o):o[0],i=n.cache;if(i.has(r))return i.get(r);var s=e.apply(this,o);return n.cache=i.set(r,s),s};return n.cache=new(re.Cache||Y),n}re.Cache=Y;var ie=Array.isArray;function se(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ae(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==q.call(e)}var le=w((function(e,t,n){var o=null==e?void 0:X(e,t);return void 0===o?n:o})),ce="/v1/auth/accesskey/exchange",de="/v1/auth/otp/verify",ue="/v1/auth/otp/signin",he="/v1/auth/otp/signup",pe={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},fe="/v1/auth/otp/signup-in",ge="/v1/auth/magiclink/verify",ve="/v1/auth/magiclink/signin",me="/v1/auth/magiclink/signup",be={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},we="/v1/auth/magiclink/signup-in",ye="/v1/auth/enchantedlink/verify",Ie="/v1/auth/enchantedlink/signin",ke="/v1/auth/enchantedlink/signup",Se="/v1/auth/enchantedlink/pending-session",je={email:"/v1/auth/enchantedlink/update/email"},xe="/v1/auth/enchantedlink/signup-in",Ce="/v1/auth/oauth/authorize",Oe="/v1/auth/oauth/exchange",Ee="/v1/auth/saml/authorize",Ae="/v1/auth/saml/exchange",Ue="/v1/auth/totp/verify",Re="/v1/auth/totp/signup",Te="/v1/auth/totp/update",_e={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},Pe={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},Le={start:"/v1/auth/webauthn/signup-in/start"},Me={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},$e="/v1/auth/password/signup",De="/v1/auth/password/signin",We="/v1/auth/password/reset",qe="/v1/auth/password/update",Ne="/v1/auth/password/replace",Fe="/v1/auth/password/policy",Ke="/v1/auth/refresh",Je="/v1/auth/tenant/select",He="/v1/auth/logout",ze="/v1/auth/logoutall",Ve="/v1/auth/me",Be="/v1/flow/start",Ge="/v1/flow/next";const Ye=6e5,Ze=()=>{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")}};var Xe;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Xe||(Xe={}));const Qe=(...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,o])=>(e[n]=o,e)),e),e}),{})),et=e=>void 0===e?void 0:JSON.stringify(e),tt=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},nt=({baseUrl:e,projectId:t,baseConfig:n,logger:o,hooks:r,cookiePolicy:i,fetch:s})=>{const a=((e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),o=await n.text();return n.text=()=>Promise.resolve(o),n.json=()=>Promise.resolve(JSON.parse(o)),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=>Ze().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const o=await n(...t);return e[o.ok?"log":"error"](await(async e=>{const t=await e.text();return Ze().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(o)),o}:n})(o,s),l=async o=>{const s=(null==r?void 0:r.beforeRequest)?r.beforeRequest(o):o,{path:l,body:c,headers:d,queryParams:u,method:h,token:p}=s,f=await a((({path:e,baseUrl:t,queryParams:n})=>{const o=new URL(e,t);return n&&(o.search=new URLSearchParams(n).toString()),o})({path:l,baseUrl:e,queryParams:u}),{headers:Qe(tt(t,p),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.3.0"},(null==n?void 0:n.baseHeaders)||{},d),method:h,body:et(c),credentials:i||"include"});return(null==r?void 0:r.afterRequest)&&await r.afterRequest(o,null==f?void 0:f.clone()),f};return{get:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Xe.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Xe.post,token:r}),put:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Xe.put,token:r}),delete:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Xe.delete,token:o}),hooks:r}};var ot=429;function rt(e,t,n){var o;let r=it(e);t&&(r=null===(o=null==r?void 0:r.tenants)||void 0===o?void 0:o[t]);const i=null==r?void 0:r[n];return Array.isArray(i)?i:[]}function it(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return m(e)}function st(e){const{exp:t}=it(e);return(new Date).getTime()/1e3>t}function at(e){let t=it(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function lt(e,t){return rt(e,t,"permissions")}function ct(e,t){return rt(e,t,"roles")}const dt=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function ut(e,t){var n;const o=await e,r={code:o.status,ok:o.ok,response:o},i=await o.clone().json();return o.ok?r.data=t?t(i):i:(r.error=i,o.status===ot&&Object.assign(r.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),r}const ht=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),pt=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),ft=e=>t=>e.test(t),gt=ft(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),vt=ft(/^\+[1-9]{1}[0-9]{3,14}$/),mt=ht(gt,'"{val}" is not a valid email'),bt=ht(vt,'"{val}" is not a valid phone number'),wt=ht((1,e=>e.length>=1),"Minimum length is 1");const yt=ht((e=>"string"==typeof e),"Input is not a string"),It=ht((e=>void 0===e),"Input is defined"),kt=(St=[yt(),It()],"Input is not a string or undefined",(e="Input is not a string or undefined")=>t=>{const n=St.filter((e=>e(t)));return!(n.length<St.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var St;const jt=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>pt(...e).validate(n[t]))),t(...n)),xt=e=>[yt(`"${e}" must be a string`),wt(`"${e}" must not be empty`)],Ct=e=>[yt(`"${e}" must be a string`),mt()],Ot=e=>[yt(`"${e}" must be a string`),bt()],Et=jt(xt("accessKey")),At=e=>({exchange:Et((t=>ut(e.post(ce,{},{token:t}))))});var Ut,Rt;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(Ut||(Ut={})),function(e){e.email="email"}(Rt||(Rt={}));const Tt=Object.assign(Object.assign({},Ut),Rt);var _t;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(_t||(_t={}));const Pt=xt("loginId"),Lt=jt(xt("token")),Mt=jt(Pt),$t=jt(xt("pendingRef")),Dt=jt(Pt,Ct("email")),Wt=e=>({verify:Lt((t=>ut(e.post(ye,{token:t})))),signIn:Mt(((t,n,o,r)=>ut(e.post(dt(Ie,Tt.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:Mt(((t,n)=>ut(e.post(dt(xe,Tt.email),{loginId:t,URI:n})))),signUp:Mt(((t,n,o)=>ut(e.post(dt(ke,Tt.email),{loginId:t,URI:n,user:o})))),waitForSession:$t(((t,n)=>new Promise((o=>{const{pollingIntervalMs:r,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||Ye,Ye)}))(n);let s;const a=setInterval((async()=>{const n=await e.post(Se,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(ut(Promise.resolve(n))))}),r);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)})))),update:{email:Dt(((t,n,o,r,i)=>ut(e.post(je.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r}))))}}),qt=jt(xt("flowId")),Nt=jt(xt("executionId"),xt("stepId"),xt("interactionId")),Ft=e=>({start:qt(((t,n,o,r,i,s,a)=>ut(e.post(Be,{flowId:t,options:n,conditionInteractionId:o,interactionId:r,version:i,componentsVersion:s,input:a})))),next:Nt(((t,n,o,r,i,s)=>ut(e.post(Ge,{executionId:t,stepId:n,interactionId:o,version:r,componentsVersion:i,input:s}))))}),Kt=xt("loginId"),Jt=jt(xt("token")),Ht=jt(Kt),zt=jt(Kt,Ot("phone")),Vt=jt(Kt,Ct("email")),Bt=e=>({verify:Jt((t=>ut(e.post(ge,{token:t})))),signIn:Object.keys(Tt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ht(((t,o,r,i)=>ut(e.post(dt(ve,n),{loginId:t,URI:o,loginOptions:r},{token:i}))))})),{}),signUp:Object.keys(Tt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ht(((t,o,r)=>ut(e.post(dt(me,n),{loginId:t,URI:o,user:r}))))})),{}),signUpOrIn:Object.keys(Tt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ht(((t,o)=>ut(e.post(dt(we,n),{loginId:t,URI:o}))))})),{}),update:{email:Vt(((t,n,o,r,i)=>ut(e.post(be.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r})))),phone:Object.keys(Ut).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:zt(((t,o,r,i,s)=>ut(e.post(dt(be.phone,n),Object.assign({loginId:t,phone:o,URI:r},s),{token:i}))))})),{})}});var Gt;!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"}(Gt||(Gt={}));const Yt=jt(xt("code")),Zt=e=>({start:Object.assign(((t,n,o,r)=>ut(e.post(Ce,o||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:r}))),Object.keys(Gt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,r)=>ut(e.post(Ce,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:r}))})),{})),exchange:Yt((t=>ut(e.post(Oe,{code:t}))))}),Xt=xt("loginId"),Qt=jt(Xt,xt("code")),en=jt(Xt),tn=jt(Xt,Ot("phone")),nn=jt(Xt,Ct("email")),on=e=>({verify:Object.keys(Tt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Qt(((t,o)=>ut(e.post(dt(de,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(Tt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:en(((t,o,r)=>ut(e.post(dt(ue,n),{loginId:t,loginOptions:o},{token:r}))))})),{}),signUp:Object.keys(Tt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:en(((t,o)=>ut(e.post(dt(he,n),{loginId:t,user:o}))))})),{}),signUpOrIn:Object.keys(Tt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:en((t=>ut(e.post(dt(fe,n),{loginId:t}))))})),{}),update:{email:nn(((t,n,o,r)=>ut(e.post(pe.email,Object.assign({loginId:t,email:n},r),{token:o})))),phone:Object.keys(Ut).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tn(((t,o,r,i)=>ut(e.post(dt(pe.phone,n),Object.assign({loginId:t,phone:o},i),{token:r}))))})),{})}}),rn=jt(xt("tenant")),sn=jt(xt("code")),an=e=>({start:rn(((t,n,o,r)=>ut(e.post(Ee,o||{},{queryParams:{tenant:t,redirectURL:n},token:r})))),exchange:sn((t=>ut(e.post(Ae,{code:t}))))}),ln=xt("loginId"),cn=jt(ln,xt("code")),dn=jt(ln),un=jt(ln),hn=e=>({signUp:dn(((t,n)=>ut(e.post(Re,{loginId:t,user:n})))),verify:cn(((t,n,o,r)=>ut(e.post(Ue,{loginId:t,code:n,loginOptions:o},{token:r})))),update:un(((t,n)=>ut(e.post(Te,{loginId:t},{token:n}))))}),pn=xt("loginId"),fn=xt("newPassword"),gn=jt(pn,xt("password")),vn=jt(pn),mn=jt(pn,fn),bn=jt(pn,xt("oldPassword"),fn),wn=e=>({signUp:gn(((t,n,o)=>ut(e.post($e,{loginId:t,password:n,user:o})))),signIn:gn(((t,n)=>ut(e.post(De,{loginId:t,password:n})))),sendReset:vn(((t,n)=>ut(e.post(We,{loginId:t,redirectUrl:n})))),update:mn(((t,n,o)=>ut(e.post(qe,{loginId:t,newPassword:n},{token:o})))),replace:bn(((t,n,o)=>ut(e.post(Ne,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>ut(e.get(Fe))}),yn=[yt('"loginId" must be a string')],In=xt("loginId"),kn=xt("origin"),Sn=jt(In,kn,xt("name")),jn=jt(In,kn),xn=jt(yn,kn),Cn=jt(In,kn,xt("token")),On=jt(xt("transactionId"),xt("response")),En=e=>({signUp:{start:Sn(((t,n,o)=>ut(e.post(_e.start,{user:{loginId:t,name:o},origin:n})))),finish:On(((t,n)=>ut(e.post(_e.finish,{transactionId:t,response:n}))))},signIn:{start:xn(((t,n,o,r)=>ut(e.post(Pe.start,{loginId:t,origin:n,loginOptions:o},{token:r})))),finish:On(((t,n)=>ut(e.post(Pe.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:jn(((t,n)=>ut(e.post(Le.start,{loginId:t,origin:n}))))},update:{start:Cn(((t,n,o)=>ut(e.post(Me.start,{loginId:t,origin:n},{token:o})))),finish:On(((t,n)=>ut(e.post(Me.finish,{transactionId:t,response:n}))))}}),An=jt(xt("token")),Un=jt([kt('"token" must be string or undefined')]);var Rn,Tn=jt([("projectId",Rn=xt("projectId"),ht(((e,t)=>n=>pt(...t).validate(le(n,e)))("projectId",Rn))())])((e=>{var t,n;const o=[].concat((null===(t=e.hooks)||void 0===t?void 0:t.beforeRequest)||[]),r=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.afterRequest)||[]);return(({projectId:e,logger:t,baseUrl:n,hooks:o,cookiePolicy:r,baseHeaders:i={},fetch:s})=>{return a=nt({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:o,cookiePolicy:r,baseConfig:{baseHeaders:i},fetch:s}),{accessKey:At(a),otp:on(a),magicLink:Bt(a),enchantedLink:Wt(a),oauth:Zt(a),saml:an(a),totp:hn(a),webauthn:En(a),password:wn(a),flow:Ft(a),refresh:Un((e=>ut(a.post(Ke,{},{token:e})))),selectTenant:jt([yt("tenantId")],[kt('"token" must be string or undefined')])(((e,t)=>ut(a.post(Je,{tenant:e},{token:t})))),logout:Un((e=>ut(a.post(He,{},{token:e})))),logoutAll:Un((e=>ut(a.post(ze,{},{token:e})))),me:Un((e=>ut(a.get(Ve,{token:e})))),isJwtExpired:An(st),getTenants:An(at),getJwtPermissions:An(lt),getJwtRoles:An(ct),httpClient:a};var a})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:e=>null==o?void 0:o.reduce(((e,t)=>t(e)),e),afterRequest:async(t,n)=>{(await Promise.allSettled(null==r?void 0:r.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))}))}}}))}));const _n=(e,t,n)=>(t.forEach((t=>{const o=t.split(".");let r=o.shift(),i=e;for(;o.length>0;){if(i=i[r],!r||!i)throw Error(`Invalid path "${t}", "${r}" is missing or has no value`);r=o.shift()}if("function"!=typeof i[r])throw Error(`"${t}" is not a function`);const s=i[r];i[r]=n(s)})),e);var Pn=Object.assign(Tn,{DeliveryMethods:Tt});var Ln="Blocked by CSP",Mn="9319";function $n(e,t){var n=[];return function(e,t){var n,o,r=(o=function(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0),{current:function(){return o[0]},postpone:function(){var e=o.shift();void 0!==e&&o.push(e)},exclude:function(){o.shift()}}),i=(100,3e3,n=0,function(){return Math.random()*Math.min(3e3,100*Math.pow(2,n++))}),s=r.current();if(void 0===s)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var a=function(e,n){return t(e).catch((function(e){if(n+1>=5)throw e;!function(e){if(!(e instanceof Error))return!1;var t=e.message;return t===Ln||t===Mn}(e)?r.postpone():r.exclude();var t,o=r.current();if(void 0===o)throw e;return(t=i(),new Promise((function(e){return setTimeout(e,t)}))).then((function(){return a(o,n+1)}))}))};return a(s,0)}(e,(function(e){var o=new Date,r=function(t){return n.push({url:e,startedAt:o,finishedAt:new Date,error:t})},i=t(e);return i.then((function(){return r()}),r),i})).then((function(e){return[e,{attempts:n}]}))}var Dn="Failed to load the JS script of the agent";function Wn(e){var t;e.scriptUrlPattern;var n=e.token,o=e.apiKey,r=void 0===o?n:o,i=d(e,["scriptUrlPattern","token","apiKey"]),s=null!==(t=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(e,"scriptUrlPattern"))&&void 0!==t?t:"https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js";return Promise.resolve().then((function(){if(!r||"string"!=typeof r)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.8.5"):e}))}(String(e),t)}))}(s,r);return $n(e,qn).catch(Fn)})).then((function(e){var t=e[0],n=e[1];return t.load(c(c({},i),{ldi:n}))}))}function qn(e){return function(e,t,n,o){var r,i=document,s="securitypolicyviolation",a=function(t){var n=new URL(e,location.href),o=t.blockedURI;o!==n.href&&o!==n.protocol.slice(0,-1)&&o!==n.origin||(r=t,l())};i.addEventListener(s,a);var l=function(){return i.removeEventListener(s,a)};return Promise.resolve().then(t).then((function(e){return l(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(l(),r)return function(){throw new Error(Ln)}();throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){var o=document.createElement("script"),r=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},i=document.head||document.getElementsByTagName("head")[0];o.onload=function(){r(),t()},o.onerror=function(){r(),n(new Error(Dn))},o.async=!0,o.src=e,i.appendChild(o)}))}(e)})).then(Nn)}function Nn(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,o=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==o?void 0:o.configurable)?delete e[t]:o&&!o.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(Mn);return n}function Fn(e){throw e instanceof Error&&e.message===Mn?new Error(Dn):e}var Kn={exports:{}};
|
|
2
|
-
/*! js-cookie v3.0.5 | MIT */!function(e,t){e.exports=function(){function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}function t(n,o){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=e({},o,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in i)i[a]&&(s+="; "+a,!0!==i[a]&&(s+="="+i[a].split(";")[0]));return document.cookie=t+"="+n.write(r,t)+s}}function i(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},r=0;r<t.length;r++){var i=t[r].split("="),s=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(o[a]=n.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}}return Object.create({set:r,get:i,remove:function(t,n){r(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}return 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:"/"})}()}(Kn);var Jn=w(Kn.exports);const Hn=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var r;return n[o]=[].concat((null===(r=e.hooks)||void 0===r?void 0:r[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},zn=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||{}},Vn=async e=>{const t=await zn(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},Bn="undefined"!=typeof localStorage,Gn=(e,t)=>Bn&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),Yn=e=>Bn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Zn=e=>Bn&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),Xn=(...e)=>{console.debug(...e)},Qn="undefined"!=typeof window,eo=Math.pow(2,31)-1,to=Qn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",no="fp",oo=(e=!1)=>{const t=localStorage.getItem(no);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},ro=async e=>{try{if(oo())return;const t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),n=Wn({apiKey:e,endpoint:to}),o=await n,{requestId:r}=await o.get({linkedId:t}),i=((e,t)=>({vsid:e,vrid:t}))(t,r);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem(no,JSON.stringify(t))})(i)}catch(e){global.FB_DEBUG&&console.error(e)}},io=e=>{const t=oo(!0);return t&&e.body&&(e.body.fpData=t),e},so="dls_last_user_login_id",ao="dls_last_user_display_name",lo=()=>Yn(so),co=()=>Yn(ao),uo=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,r=lo(),i=co();return r&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=r,o.lastAuth.name=i),await e(...t)},ho=e=>async(...t)=>{const n=await e(...t);return Zn(so),Zn(ao),n};function po(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const fo="DS",go="DSR";function vo(e=""){return Yn(`${e}${go}`)||""}function mo(e=""){Zn(`${e}${go}`),Zn(`${e}${fo}`),Jn.remove(fo)}async function bo(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=jo(n.publicKey.challenge),n.publicKey.user.id=jo(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=jo(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:xo(n.rawId),type:n.type,response:{attestationObject:xo(n.response.attestationObject),clientDataJSON:xo(n.response.clientDataJSON)}});var n}async function wo(e){const t=ko(e);return So(await navigator.credentials.get(t))}async function yo(e,t){const n=ko(e);return n.signal=t.signal,n.mediation="conditional",So(await navigator.credentials.get(n))}async function Io(e=!1){if(!Qn)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 ko(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=jo(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=jo(e.id)})),n}function So(e){return JSON.stringify({id:e.id,rawId:xo(e.rawId),type:e.type,response:{authenticatorData:xo(e.response.authenticatorData),clientDataJSON:xo(e.response.clientDataJSON),signature:xo(e.response.signature),userHandle:e.response.userHandle?xo(e.response.userHandle):void 0}})}function jo(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function xo(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Co,Oo=(Co=e=>({async signUp(t,n){const o=await e.webauthn.signUp.start(t,window.location.origin,n);if(!o.ok)return o;const r=await bo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,r)},async signIn(t){const n=await e.webauthn.signIn.start(t,window.location.origin);if(!n.ok)return n;const o=await wo(n.data.options);return await e.webauthn.signIn.finish(n.data.transactionId,o)},async signUpOrIn(t){var n;const o=await e.webauthn.signUpOrIn.start(t,window.location.origin);if(!o.ok)return o;if(null===(n=o.data)||void 0===n?void 0:n.create){const t=await bo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await wo(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,t)}},async update(t,n){const o=await e.webauthn.update.start(t,window.location.origin,n);if(!o.ok)return o;const r=await bo(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,r)},helpers:{create:bo,get:wo,isSupported:Io,conditional:yo}}),(...e)=>{const t=Co(...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}),Eo=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await Io(),o=Object.assign(Object.assign({redirectUrl:window.location.href,location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n}});return t[1]=o,e.flow.start(...t)}});const Ao=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var{fpKey:n,fpLoad:o}=t,r=d(t,["fpKey","fpLoad"]);return Qn?(n&&o&&ro(n).catch((()=>null)),e(Hn(r,{beforeRequest:io}))):(console.warn("Fingerprint is a client side only capability and will not work when running in the server"),e(r))}),(e=>t=>{var{autoRefresh:n}=t,o=d(t,["autoRefresh"]);if(!n)return e(o);const{clearAllTimers:r,setTimer:i}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let s,a;document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&new Date>s&&(Xn("Expiration time passed, refreshing session"),l.refresh(a))}));const l=e(Hn(o,{afterRequest:async(e,t)=>{const{refreshJwt:n,sessionJwt:o}=await zn(t);if(401===(null==t?void 0:t.status))Xn("Received 401, canceling all timers"),r();else if(o){s=(e=>{const t=e.split(".");try{if(3===t.length){const e=JSON.parse(window.atob(t[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(e){}return null})(o),a=n;let e=((c=s)?c.getTime()-(new Date).getTime():0)-2e4;e>eo&&(Xn(`Timeout is too large (${e}ms), setting it to ${eo}ms`),e=eo),r();const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});Xn(`Setting refresh timer for ${t}. (${e}ms)`),i((()=>{Xn("Refreshing session due to timer"),l.refresh(n)}),e)}var c}}));return _n(l,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return Xn("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.8.0"},t.baseHeaders)}))),(e=>t=>{const n=po(),o=po(),r=e(Hn(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))n.pub(null),o.pub(null);else{const e=await Vn(t);e&&o.pub(e);const{sessionJwt:r}=await zn(t);r&&n.pub(r)}}})),i=_n(r,["logout","logoutAll"],(e=>async(...t)=>{const r=await e(...t);return n.pub(null),o.pub(null),r}));return Object.assign(i,{onSessionTokenChange:n.sub,onUserChange:o.sub})}),(e=>t=>{const n=e(Hn(t,{afterRequest:async(e,t)=>{var n;const o=await Vn(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],i=null==o?void 0:o.name;r&&((e=>{Gn(so,e)})(r),(e=>{Gn(ao,e)})(i))}}));let o=_n(n,["flow.start"],uo);return o=_n(o,["logout","logoutAll"],ho),Object.assign(o,{getLastUserLoginId:lo,getLastUserDisplayName:co})}),(e=>t=>{var{persistTokens:n,sessionTokenViaCookie:o,storagePrefix:r}=t,i=d(t,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!n||!Qn)return n&&console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),e(i);const s=e(Hn(i,{beforeRequest:(a=r,e=>Object.assign(e,{token:e.token||vo(a)})),afterRequest:async(e,t)=>{401===(null==t?void 0:t.status)?mo(r):((e={},t,n)=>{var{refreshJwt:o,sessionJwt:r}=e,i=d(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),void 0===n&&(n=""),o&&Gn(`${n}${go}`,o),r&&(t?function(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:r}){if(t){const i=new Date(1e3*r);Jn.set(e,t,{path:n,domain:o,expires:i,sameSite:"Strict",secure:!0})}}(fo,r,i):Gn(`${n}${fo}`,r))})(await zn(t),o,r)}}));var a;const l=_n(s,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return mo(e),o})(r));return Object.assign(l,{getRefreshToken:()=>vo(r),getSessionToken:()=>function(e=""){return Jn.get(fo)||Yn(`${e}${fo}`)||""}(r)})}))(((...e)=>{const t=Pn(...e);return Object.assign(Object.assign({},t),{flow:Eo(t),webauthn:Oo(t)})}));let Uo;const Ro=e=>{const t=Ao({...e,persistTokens:l,autoRefresh:l});return Uo=t,t};Uo=Ro({projectId:"temp pid"});const To=()=>l?Uo?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),_o=()=>l?Uo?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),Po=s(((e=To(),t)=>Uo?.getJwtPermissions(e,t))),Lo=s(((e=To(),t)=>Uo?.getJwtRoles(e,t)));const Mo=t.lazy((async()=>((await Promise.resolve().then((function(){return Ai}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:n,innerRef:r,tenant:i,theme:s,locale:a,debug:l,redirectUrl:c,client:d,form:u,autoFocus:h})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":n,ref:r,tenant:i,theme:s,locale:a,debug:l,client:d,form:u,"redirect-url":c,"auto-focus":h})}))),$o=o.default.forwardRef((({flowId:e,onSuccess:n,onError:i,logger:s,tenant:a,theme:l,locale:c,debug:d,client:u,form:h,telemetryKey:p,redirectUrl:f,autoFocus:g,errorTransformer:v},m)=>{const[b,w]=t.useState(null);t.useImperativeHandle(m,(()=>b));const{projectId:y,baseUrl:I,sdk:k}=o.default.useContext(r),S=t.useCallback((async e=>{await k.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);t.useEffect((()=>{const e=b;return e?.addEventListener("success",S),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",S)}}),[b,i,S]),t.useEffect((()=>{b&&(b.errorTransformer=v)}),[b,v]),t.useEffect((()=>{b&&s&&(b.logger=s)}),[b,s]);const{form:j,client:x}=t.useMemo((()=>({form:JSON.stringify(h||{}),client:JSON.stringify(u||{})})),[h,u]);return o.default.createElement("form",null,o.default.createElement(t.Suspense,{fallback:null},o.default.createElement(Mo,{projectId:y,flowId:e,baseUrl:I,innerRef:w,tenant:a,theme:l,locale:c,debug:d,form:j,client:x,telemetryKey:p,redirectUrl:f,autoFocus:g})))}));var Do=()=>{const e=t.useContext(r);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const Wo=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,qo={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],qo);if("function"==typeof e[t])return()=>{throw Error(Wo("function"))};throw Error(Wo("attribute"))}},No="undefined"!=typeof localStorage,Fo=No&&localStorage.getItem("base.content.url")||"https://static.descope.com/pages",Ko="config.json",Jo="base.ui.components.url",Ho=No&&localStorage.getItem(Jo)||"https://static.descope.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",zo=No&&localStorage.getItem(Jo)||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Vo="descope-login-flow",Bo="code",Go="ra-challenge",Yo="ra-callback",Zo="ra-initiator",Xo="data-exclude-field",Qo="dls_last_auth",er="state_id",tr="saml_idp_state_id",nr="saml_idp_username",or="sso_app_id",rr="data-type",ir="poll",sr="webauthnCreate",ar="submit",lr="polling";var cr;function dr(e){return new URLSearchParams(window.location.search).get(e)}function ur(e){if(window.history.replaceState&&dr(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 hr(e,t){return u(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||"text"](),headers:Object.fromEntries(n.headers.entries())}}))}function pr(e,t,n="v2-beta"){const o=new URL(Fo);return o.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(o.pathname,e,n,t),o.toString()}function fr(e,t){if(!Number.isNaN(e)&&!Number.isNaN(t))return e>t?cr.forward:e<t?cr.backward:void 0}!function(e){e.backward="backward",e.forward="forward"}(cr||(cr={}));const gr=()=>{const[e="",t=""]=(dr(Vo)||"").split("_");return{executionId:e,stepId:t}};function vr(){ur(Vo)}const mr=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),br=e=>{let t,n;return(...o)=>{return t&&(i=o,(r=t).length===i.length&&r.every(((e,t)=>e===i[t])))||(t=o,n=e(...o)),n;var r,i}},wr=(e,t,n,o,r)=>e&&!t&&e&&!n&&!o&&e&&!r,yr=e=>null==e?void 0:e.submit(),Ir=(e,t)=>{const n=t.find((t=>e[t]));return n?e[n]:null};var kr,Sr,jr,xr;function Cr(e,t){const n=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(n.length!==o.length)return!1;for(let o=0;o<n.length;o+=1){const r=n[o],i=e[r],s=t[r];if(null===i||null===s){if(i!==s)return!1}else if("object"==typeof i&&"object"==typeof s){if(!Cr(i,s))return!1}else if(i!==s)return!1}return!0}class Or{constructor(e={},{updateOnlyOnChange:t=!0}={}){kr.set(this,void 0),Sr.set(this,{}),jr.set(this,0),xr.set(this,!1),this.update=e=>{const t="function"==typeof e?e(h(this,kr,"f")):e,n=Object.assign(Object.assign({},h(this,kr,"f")),t);if(!h(this,xr,"f")||!Cr(h(this,kr,"f"),n)){const e=h(this,kr,"f");p(this,kr,n,"f"),Object.freeze(h(this,kr,"f")),setTimeout((()=>{Object.values(h(this,Sr,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},p(this,kr,e,"f"),p(this,xr,t,"f")}get current(){return Object.assign({},h(this,kr,"f"))}subscribe(e){return p(this,jr,h(this,jr,"f")+1,"f"),h(this,Sr,"f")[h(this,jr,"f")]=e,h(this,jr,"f").toString()}unsubscribe(e){const t=!!h(this,Sr,"f")[e];return t&&delete h(this,Sr,"f")[e],t}unsubscribeAll(){return p(this,Sr,{},"f"),!0}}kr=new WeakMap,Sr=new WeakMap,jr=new WeakMap,xr=new WeakMap;const Er=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${Xo}])`)).forEach((e=>{e.value=n}))}))},Ar=(e,t)=>e.replace(/{{(.+?)}}/g,((e,n)=>{return o=t,n.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),o);var o})),Ur=br((()=>u(void 0,void 0,void 0,(function*(){var e,t,n,o;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return!1;try{const r=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(100,n=r,o=i,new Promise(((e,t)=>{let r=!1;const i=setTimeout((()=>{r=!0,void 0!==o?e(o):t(new Error("Promise timed out after 100 ms"))}),100);n.then((t=>{r||(clearTimeout(i),e(t))})).catch((e=>{r||(clearTimeout(i),t(e))}))})))}catch(e){return console.error("Conditional login check failed",e),!1}})))),Rr={"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 Tr(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(Qo)))}catch(e){}return t}const _r="dls_ab_testing_id",Pr=document.createElement("template");var Lr,Mr,$r,Dr,Wr,qr,Nr,Fr,Kr,Jr,Hr,zr,Vr,Br,Gr,Yr,Zr,Xr,Qr,ei,ti,ni,oi,ri,ii,si,ai,li,ci,di,ui,hi,pi,fi,gi,vi,mi,bi,wi,yi,Ii,ki,Si,ji,xi,Ci;Pr.innerHTML='\n\t<style>\n\t\t:host {\n all: initial;\n\t\t\twidth: 100%;\n\t\t\theight: 100%;\n\t\t}\n\n\t\t#wc-root {\n\t\t\theight: 100%;\n\t\t\ttransition: opacity 300ms ease-in-out;\n\t\t}\n\n\t\t#wc-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\t</style>\n\t<div id="wc-root"></div>\n\t';class Oi extends HTMLElement{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","theme","locale","debug","storage-prefix","preview","redirect-url","auto-focus"]}constructor(e){super(),Lr.add(this),this.logger=console,Mr.set(this,!1),this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),h(this,Lr,"m",ai).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)}},$r.set(this,new Or({deferredRedirect:!1})),Dr.set(this,new Or),Wr.set(this,{}),this.getComponentsContext=()=>h(this,Wr,"f"),this.nextRequestStatus=new Or({isLoading:!1}),qr.set(this,void 0),Nr.set(this,{popstate:h(this,Lr,"m",Vr).bind(this),visibilitychange:h(this,Lr,"m",Br).bind(this),componentsContext:h(this,Lr,"m",oi).bind(this)}),Fr.set(this,void 0),Qr.set(this,br((()=>u(this,void 0,void 0,(function*(){const e=pr(this.projectId,Ko);try{const{body:t,headers:n}=yield hr(e,"json");return{projectConfig:t,executionContext:{geo:n["x-geo"]}}}catch(e){return{isMissingConfig:!0}}}))))),p(this,Fr,e,"f"),h(this,Lr,"m",Kr).call(this)}get projectId(){return this.getAttribute("project-id")}get flowId(){return this.getAttribute("flow-id")}get form(){try{const e=JSON.parse(this.getAttribute("form"))||{};return Object.entries(e).reduce(((e,[t,n])=>Object.assign(Object.assign({},e),{[`form.${t}`]:n})),e)}catch(e){return{}}}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(e){return{}}}get baseUrl(){return this.getAttribute("base-url")||void 0}get tenant(){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 theme(){var e,t;const n=this.getAttribute("theme");return"os"===n?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":n||"light"}get autoFocus(){var e;const t=null!==(e=this.getAttribute("auto-focus"))&&void 0!==e?e:"true";return"skipFirstScreen"===t?t:"true"===t}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}getExecutionContext(){return u(this,void 0,void 0,(function*(){const{executionContext:e}=yield h(this,Qr,"f").call(this);return e}))}getProjectConfig(){return u(this,void 0,void 0,(function*(){const{projectConfig:e}=yield h(this,Qr,"f").call(this);return e}))}getFlowConfig(){var e,t;return u(this,void 0,void 0,(function*(){const n=yield this.getProjectConfig(),o=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=o.version)&&void 0!==t||(o.version=0),o}))}getTargetLocales(){return u(this,void 0,void 0,(function*(){const e=yield this.getFlowConfig();return((null==e?void 0:e.targetLocales)||[]).map((e=>e.toLowerCase()))}))}connectedCallback(){return u(this,void 0,void 0,(function*(){if(this.shadowRoot.isConnected){if(h(this,Dr,"f").subscribe(h(this,Lr,"m",si).bind(this)),h(this,Dr,"f").update({isDebug:this.debug}),h(this,Lr,"m",Jr).call(this))return void h(this,Lr,"m",Hr).call(this);if(h(this,Lr,"m",zr).call(this),yield h(this,Lr,"m",Zr).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");if((yield h(this,Qr,"f").call(this)).isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");yield h(this,Lr,"m",di).call(this),yield h(this,Lr,"m",ti).call(this),h(this,Lr,"m",ei).call(this),h(this,Lr,"m",li).call(this);const{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCallbackUrl:i,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}=(()=>{const{executionId:e,stepId:t}=gr();(e||t)&&vr();const n=dr("t")||void 0;n&&ur("t");const o=dr(Bo)||void 0;o&&ur(Bo);const r=dr("err")||void 0;r&&ur("err");const{redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a}={redirectAuthCodeChallenge:dr(Go),redirectAuthCallbackUrl:dr(Yo),redirectAuthInitiator:dr(Zo)};(i||s||a)&&(ur(Go),ur(Yo),ur(Zo));const l=dr(er);l&&ur(er);const c=dr(tr);c&&ur(tr);const d=dr(nr);c&&ur(nr);const u=dr(or);return u&&ur(or),{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}})();window.addEventListener("popstate",h(this,Nr,"f").popstate),window.addEventListener("components-context",h(this,Nr,"f").componentsContext),window.addEventListener("visibilitychange",h(this,Nr,"f").visibilitychange),h(this,$r,"f").subscribe(h(this,Lr,"m",Yr).bind(this)),h(this,$r,"f").update({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenant,redirectUrl:this.redirectUrl,locale:this.locale,stepId:t,executionId:e,token:n,code:o,exchangeError:r,redirectAuthCallbackUrl:i,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}),p(this,Mr,!0,"f")}}))}disconnectedCallback(){h(this,$r,"f").unsubscribeAll(),h(this,Dr,"f").unsubscribeAll(),h(this,Lr,"m",ii).call(this),window.removeEventListener("popstate",h(this,Nr,"f").popstate),window.removeEventListener("visibilitychange",h(this,Nr,"f").visibilitychange),window.removeEventListener("components-context",h(this,Nr,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&h(this,Mr,"f")&&t!==n&&Oi.observedAttributes.includes(e)){h(this,Lr,"m",zr).call(this);const o=null===t;h(this,$r,"f").update((({stepId:t,executionId:r})=>{let i=t,s=r;return o||(s=null,i=null,vr()),{[mr(e)]:n,stepId:i,executionId:s}})),h(this,Dr,"f").update({isDebug:this.debug})}}}Mr=new WeakMap,$r=new WeakMap,Dr=new WeakMap,Wr=new WeakMap,qr=new WeakMap,Nr=new WeakMap,Fr=new WeakMap,Qr=new WeakMap,Lr=new WeakSet,Kr=function(){this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Pr.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#wc-root")},Jr=function(){return!this.shadowRoot.host.closest("form")&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},Hr=function(){const e=this.shadowRoot.host,t=document.createElement("form");e.parentElement.appendChild(t),t.appendChild(e)},zr=function(){const e=["base-url","tenant","theme","locale","debug","redirect-url","auto-focus","preview","storage-prefix","form","client"];if(Oi.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[mr(t)])throw Error(`${t} cannot be empty`)})),this.theme&&"light"!==this.theme&&"dark"!==this.theme)throw Error('Supported theme values are "light", "dark", or leave empty for using the OS theme')},Vr=function(){const{stepId:e,executionId:t}=gr();h(this,$r,"f").update({stepId:e,executionId:t})},Br=function(){document.hidden||setTimeout((()=>{h(this,$r,"f").update({deferredRedirect:!1})}),300)},Gr=function(e,t){this.sdk=Ao(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix},Oi.sdkConfigOverrides),{projectId:e,baseUrl:t})),["start","next"].forEach((e=>{const t=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>u(this,void 0,void 0,(function*(){this.nextRequestStatus.update({isLoading:!0});try{return yield t(...e)}finally{this.nextRequestStatus.update({isLoading:!1})}}))}))},Yr=function(e,t,n){return u(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:o}=e;if(n("projectId")||n("baseUrl")){if(!t)return;h(this,Lr,"m",Gr).call(this,t,o)}h(this,Fr,"f").call(this,e)}))},Zr=function(){return u(this,void 0,void 0,(function*(){return(yield h(this,Qr,"f").call(this)).isMissingConfig&&(yield h(this,Lr,"m",Xr).call(this))}))},Xr=function(){return u(this,void 0,void 0,(function*(){const e=pr(this.projectId,Ko,"v2-alpha");try{return yield hr(e,"json"),!0}catch(e){return!1}}))},ei=function(){var e,t;return u(this,void 0,void 0,(function*(){const{projectConfig:n}=yield h(this,Qr,"f").call(this),o=null===(t=null===(e=null==n?void 0:n.cssTemplate)||void 0===e?void 0:e[this.theme])||void 0===t?void 0:t.fonts;o&&Object.values(o).forEach((e=>(e=>{if(!e)return;const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url)))}))},ti=function(){return u(this,void 0,void 0,(function*(){yield h(this,Lr,"m",ni).call(this),yield h(this,Lr,"m",ri).call(this)}))},ni=function(){var e,t,n,o;return u(this,void 0,void 0,(function*(){const r=document.createElement("style"),i=pr(this.projectId,"theme.json");try{const{body:s}=yield hr(i,"json");r.innerText=((null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.globals)||"")+((null===(t=null==s?void 0:s.dark)||void 0===t?void 0:t.globals)||"");const a=yield Oi.descopeUI;(null==a?void 0:a.componentsThemeManager)&&(a.componentsThemeManager.themes={light:null===(n=null==s?void 0:s.light)||void 0===n?void 0:n.components,dark:null===(o=null==s?void 0:s.dark)||void 0===o?void 0:o.components})}catch(r){this.loggerWrapper.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}this.shadowRoot.appendChild(r)}))},oi=function(e){p(this,Wr,Object.assign(Object.assign({},e.detail),h(this,Wr,"f")),"f")},ri=function(){return u(this,void 0,void 0,(function*(){this.rootElement.setAttribute("data-theme",this.theme);const e=yield Oi.descopeUI;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)}))},ii=function(){var e;null===(e=h(this,qr,"f"))||void 0===e||e.remove(),p(this,qr,null,"f")},si=function({isDebug:e}){return u(this,void 0,void 0,(function*(){e?(p(this,qr,document.createElement("descope-debugger"),"f"),Object.assign(h(this,qr,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Ki})),document.body.appendChild(h(this,qr,"f"))):h(this,Lr,"m",ii).call(this)}))},ai=function(e,t){var n;e&&this.debug&&(null===(n=h(this,qr,"f"))||void 0===n||n.updateData({title:e,description:t}))},li=function(){this.rootElement.onkeydown=e=>{if("Enter"!==e.key)return;e.preventDefault();const t=this.rootElement.querySelectorAll("descope-button");if(1===t.length)return void t[0].click();const n=Array.from(t).filter((e=>"button"===e.getAttribute("data-type")));1===n.length&&n[0].click()}},ci=function(){var e,t;return u(this,void 0,void 0,(function*(){return(null===(t=null===(e=yield h(this,Qr,"f").call(this))||void 0===e?void 0:e.projectConfig)||void 0===t?void 0:t.componentsVersion)||(this.logger.error("Did not get components version, using latest version"),"latest")}))},di=function(){return u(this,void 0,void 0,(function*(){Oi.descopeUI?this.loggerWrapper.info("DescopeUI is already loading, probably multiple flows are running on the same page"):Oi.descopeUI=new Promise((e=>{if(globalThis.DescopeUI)return void e(globalThis.DescopeUI);const t=e=>{const t=document.createElement("script");return t.id="load-descope-ui",t.src=e,t},n=(e,t)=>e.replace("<version>",t),o=(t,n)=>{const o=()=>{this.loggerWrapper.error("Cannot load DescopeUI",`Make sure this URL is valid and return the correct script: "${t.src}"`),n()};t.addEventListener("load",(()=>{globalThis.DescopeUI||o(),e(globalThis.DescopeUI)})),t.addEventListener("error",o)};(()=>{u(this,void 0,void 0,(function*(){const r=yield h(this,Lr,"m",ci).call(this),i=t(n(Ho,r));o(i,(()=>{i.remove(),this.loggerWrapper.info("Trying to load DescopeUI from a fallback URL");const s=t(n(zo,r));o(s,(()=>{e(void 0)})),document.body.append(s)})),document.body.append(i)}))})()}))}))},Oi.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.4.0"}};class Ei extends Oi{static set sdkConfigOverrides(e){Oi.sdkConfigOverrides=e}constructor(){const e=new Or;super(e.update.bind(e)),ui.add(this),this.stepState=new Or({},{updateOnlyOnChange:!1}),hi.set(this,void 0),pi.set(this,null),fi.set(this,(()=>{clearInterval(h(this,hi,"f")),p(this,hi,null,"f")})),gi.set(this,(e=>{var t,n,o,r,i,s,a,l,c;if(!(null==e?void 0:e.ok)){h(this,fi,"f").call(this),h(this,ui,"m",Ci).call(this,"error",null==e?void 0:e.error);const s=null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url,a=`${null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status} - ${null===(o=null==e?void 0:e.response)||void 0===o?void 0:o.statusText}`;return void this.loggerWrapper.error((null===(r=null==e?void 0:e.error)||void 0===r?void 0:r.errorDescription)||s,(null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.errorMessage)||a)}const d=null===(l=null===(a=null===(s=e.data)||void 0===s?void 0:s.screen)||void 0===a?void 0:a.state)||void 0===l?void 0:l.errorText;(null===(c=e.data)||void 0===c?void 0:c.error)?this.loggerWrapper.error(`[${e.data.error.code}]: ${e.data.error.description}`,`${d?`${d} - `:""}${e.data.error.message}`):d&&this.loggerWrapper.error(d);const{status:u,authInfo:p,lastAuth:f}=e.data;if("completed"===u)return function(e){(null==e?void 0:e.authMethod)&&No&&localStorage.setItem(Qo,JSON.stringify(e))}(f),h(this,fi,"f").call(this),void h(this,ui,"m",Ci).call(this,"success",p);const{executionId:g,stepId:v,stepName:m,action:b,screen:w,redirect:y,webauthn:I,error:k,samlIdpResponse:S}=e.data;b!==ir?(this.loggerWrapper.info(`Step "${m||`#${v}`}" is ${u}`,"",{screen:w,status:u,stepId:v,stepName:m,action:b,error:k}),this.flowState.update({stepId:v,executionId:g,action:b,redirectTo:null==y?void 0:y.url,screenId:null==w?void 0:w.id,screenState:null==w?void 0:w.state,webauthnTransactionId:null==I?void 0:I.transactionId,webauthnOptions:null==I?void 0:I.options,samlIdpResponseUrl:null==S?void 0:S.url,samlIdpResponseSamlResponse:null==S?void 0:S.samlResponse,samlIdpResponseRelayState:null==S?void 0:S.relayState})):this.flowState.update({action:b})})),vi.set(this,br((()=>u(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.error("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.error("Webauthn start failed",e.message)}}))))),this.flowState=e}connectedCallback(){const e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});var t,n;return u(this,void 0,void 0,(function*(){this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(n=this.stepState)||void 0===n||n.subscribe(this.onStepChange.bind(this))),yield e.connectedCallback.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=h(this,pi,"f"))||void 0===e||e.abort(),p(this,pi,null,"f")}getHtmlFilenameWithLocale(e,t){return u(this,void 0,void 0,(function*(){let n,o=navigator.language;o&&"zh-TW"!==o&&(o=o.split("-")[0]);const r=(e||o||"").toLowerCase();return(yield this.getTargetLocales()).includes(r)&&(n=`${t}-${r}.html`),n}))}getPageContent(e,t){return u(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield hr(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 hr(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(e,t,n){var o,r;return u(this,void 0,void 0,(function*(){const{projectId:i,flowId:s,tenant:a,stepId:l,executionId:c,action:d,screenId:f,screenState:g,redirectTo:v,redirectUrl:m,token:b,code:w,exchangeError:y,webauthnTransactionId:I,webauthnOptions:k,redirectAuthCodeChallenge:S,redirectAuthCallbackUrl:j,redirectAuthInitiator:x,oidcIdpStateId:C,locale:O,samlIdpStateId:E,samlIdpUsername:A,samlIdpResponseUrl:U,samlIdpResponseSamlResponse:R,samlIdpResponseRelayState:T,ssoAppId:_}=e;let P,L;h(this,hi,"f")&&h(this,fi,"f").call(this);const M=(()=>{const e=localStorage.getItem(_r);if(!e){const e=Math.floor(100*Math.random()+1);return localStorage.setItem(_r,e.toString()),e}return Number(e)})(),$=this.sdk.getLastUserLoginId(),D=yield this.getFlowConfig(),W=yield this.getProjectConfig(),q=j&&S?{callbackUrl:j,codeChallenge:S}:void 0;if(!c&&(D.fingerprintEnabled&&D.fingerprintKey?ro(D.fingerprintKey):localStorage.removeItem(no),D.conditions?({startScreenId:P,conditionInteractionId:L}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n,predicate:o})=>{var r;if("ELSE"===t)return!0;const i=null===(r=Rr[t])||void 0===r?void 0:r[n];return!!(null==i?void 0:i(e,o))}));return n?{startScreenId:n.met.screenId,conditionInteractionId:n.met.interactionId}:{}})({loginId:$,code:w,token:b,abTestingKey:M},D.conditions)):D.condition?({startScreenId:P,conditionInteractionId:L}=((e,t)=>{var n;const o=null===(n=Rr[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const r=o(t,e.predicate)?e.met:e.unmet;return{startScreenId:null==r?void 0:r.screenId,conditionInteractionId:null==r?void 0:r.interactionId}})(D.condition,{loginId:$,code:w,token:b,abTestingKey:M})):P=D.startScreenId,!wr(P,C,E,A,_))){const e=yield this.sdk.flow.start(s,Object.assign(Object.assign({tenant:a,redirectAuth:q,oidcIdpStateId:C,samlIdpStateId:E,samlIdpUsername:A,ssoAppId:_,client:this.client},m&&{redirectUrl:m}),{lastAuth:Tr($),abTestingKey:M}),L,"",D.version,W.componentsVersion,Object.assign(Object.assign(Object.assign({},this.form),w?{exchangeCode:w,idpInitiated:!0}:{}),b?{token:b}:{}));return h(this,gi,"f").call(this,e),void("completed"!==(null===(o=null==e?void 0:e.data)||void 0===o?void 0:o.status)&&this.flowState.update({code:void 0,token:void 0}))}if(c&&(n("token")&&b||n("code")&&w||n("exchangeError")&&y)){const e=yield this.sdk.flow.next(c,l,ar,D.version,W.componentsVersion,{token:b,exchangeCode:w,exchangeError:y});return h(this,gi,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if("loadForm"===d&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>n(e)))){if(!U||!R)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,o)=>{const r=document.createElement("form");r.method="POST",r.action=e,r.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(r),o(r)})(U,R,T||"",yr)}if("redirect"===d&&(n("redirectTo")||n("deferredRedirect")))return v?"android"===x&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(v):void this.loggerWrapper.error("Did not get redirect url");if(d===sr||"webauthnGet"===d){if(!I||!k)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(r=h(this,pi,"f"))||void 0===r||r.abort(),p(this,pi,null,"f");try{e=d===sr?yield this.sdk.webauthn.helpers.create(k):yield this.sdk.webauthn.helpers.get(k)}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(c,l,ar,D.version,W.componentsVersion,{transactionId:I,response:e,failure:t});h(this,gi,"f").call(this,n)}if(d===ir&&p(this,hi,setInterval((()=>u(this,void 0,void 0,(function*(){const e=yield this.sdk.flow.next(c,l,lr,D.version,W.componentsVersion,{});h(this,gi,"f").call(this,e)}))),2e3),"f"),!f&&!P)return void this.loggerWrapper.warn("No screen was found to show");const N=P||f,F=yield this.getHtmlFilenameWithLocale(O,N),K={direction:fr(+l,+t.stepId),screenState:Object.assign(Object.assign({},g),{form:Object.assign(Object.assign({},this.form),null==g?void 0:g.form),lastAuth:{loginId:$,name:this.sdk.getLastUserDisplayName()||$}}),htmlUrl:pr(i,`${N}.html`),htmlLocaleUrl:F&&pr(i,F),samlIdpUsername:A},J=Tr($);wr(P,C,E,A,_)?K.next=(e,t,n,o)=>this.sdk.flow.start(s,Object.assign({tenant:a,redirectAuth:q,oidcIdpStateId:C,samlIdpStateId:E,samlIdpUsername:A,ssoAppId:_,lastAuth:J,preview:this.preview,abTestingKey:M,client:this.client},m&&{redirectUrl:m}),L,e,t,n,Object.assign(Object.assign(Object.assign(Object.assign({},this.form),o),w&&{exchangeCode:w,idpInitiated:!0}),b&&{token:b})):(n("projectId")||n("baseUrl")||n("executionId")||n("stepId"))&&(K.next=(...e)=>this.sdk.flow.next(c,l,...e)),this.stepState.update(K)}))}loadDescopeUiComponents(e){return u(this,void 0,void 0,(function*(){const t=yield Oi.descopeUI;if(!t)return;const n=(e=>[...Array.from(e.querySelectorAll("*")).reduce(((e,t)=>t.tagName.startsWith("DESCOPE-")?e.add(t.tagName.toLocaleLowerCase()):e),new Set)])(e);yield Promise.all(n.map((e=>u(this,void 0,void 0,(function*(){if(!customElements.get(e))if(t[e])try{return yield t[e]()}catch(t){if("NotSupportedError"!==t.name)throw t;console.debug(`${e} is already registered`)}else this.loggerWrapper.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)})))))}))}onStepChange(e,t){var n,o;return u(this,void 0,void 0,(function*(){const{htmlUrl:r,htmlLocaleUrl:i,direction:s,next:a,screenState:l}=e,c=document.createElement("template");c.innerHTML=yield this.getPageContent(r,i);const d=c.content.cloneNode(!0),p=this.loadDescopeUiComponents(c.content);this.sdk.webauthn.helpers.isSupported()?yield h(this,ui,"m",bi).call(this,d,a):d.querySelectorAll(`descope-button[${rr}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(n=l.form)||void 0===n?void 0:n.loginId)||(null===(o=l.form)||void 0===o?void 0:o.email)||(l.form||(l.form={}),l.form.loginId=e.samlIdpUsername,l.form.email=e.samlIdpUsername),((e,t,n,o)=>{var r;let i=null==t?void 0:t.errorText;try{i=(null==n?void 0:n({text:null==t?void 0:t.errorText,type:null==t?void 0:t.errorType}))||(null==t?void 0:t.errorText)}catch(e){o.error("Error transforming error message",e.message)}((e,t,n="")=>{e.querySelectorAll(`[${rr}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(e,"error-message",i),((e,t)=>{e.querySelectorAll(`[${rr}="totp-link"]`).forEach((e=>{e.setAttribute("href",t)}))})(e,null===(r=null==t?void 0:t.totp)||void 0===r?void 0:r.provisionUrl),((e,t)=>{e.querySelectorAll("descope-text,descope-link").forEach((e=>{e.textContent=Ar(e.textContent,t)}))})(e,t),((e,t)=>{e.querySelectorAll("[data-has-dynamic-attr-values]").forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=Ar(e.value,t)}))}))})(e,t)})(d,l,this.errorTransformer,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('descope-phone-field[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(d,f);const g=()=>u(this,void 0,void 0,(function*(){var e;yield p,((e,t)=>{var n,o;const r=null===(n=customElements.get("descope-totp-image"))||void 0===n?void 0:n.cssVarList.url;t&&r&&(null===(o=null==e?void 0:e.style)||void 0===o||o.setProperty(r,`url(data:image/jpg;base64,${t})`))})(this.shadowRoot.querySelector("div"),null===(e=null==l?void 0:l.totp)||void 0===e?void 0:e.image),this.rootElement.replaceChildren(d),setTimeout((()=>((e,t)=>{Er(e,null==t?void 0:t.inputs),Er(e,null==t?void 0:t.form)})(this.rootElement,l)));const n=!t.htmlUrl;if(((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}})(this.rootElement,this.autoFocus,n),h(this,ui,"m",ji).call(this,a),h(this,ui,"m",Ci).call(this,"page-updated",{}),this.rootElement.querySelector(`[${rr}="polling"]`)){const e=yield this.getFlowConfig(),t=yield this.getProjectConfig(),n=yield a(lr,e.version,t.componentsVersion,{});h(this,gi,"f").call(this,n)}}));s?h(this,ui,"m",xi).call(this,g,s):g()}))}}hi=new WeakMap,pi=new WeakMap,fi=new WeakMap,gi=new WeakMap,vi=new WeakMap,ui=new WeakSet,mi=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)}))}},bi=function(e,t){var n;return u(this,void 0,void 0,(function*(){null===(n=h(this,pi,"f"))||void 0===n||n.abort();const o=e.querySelector('*[autocomplete="webauthn"]');if(o&&(yield Ur())){const{options:e,transactionId:n}=(yield h(this,vi,"f").call(this))||{};if(e&&n){h(this,ui,"m",mi).call(this,o),p(this,pi,new AbortController,"f");const r=yield this.getFlowConfig(),i=yield this.getProjectConfig();this.sdk.webauthn.helpers.conditional(e,h(this,pi,"f")).then((e=>u(this,void 0,void 0,(function*(){const s=yield t(o.id,r.version,i.componentsVersion,{transactionId:n,response:e});h(this,gi,"f").call(this,s)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)}))}}}))},wi=function(){return Array.from(this.shadowRoot.querySelectorAll("*[name]")).every((e=>{var t,n;return null===(t=e.reportValidity)||void 0===t||t.call(e),null===(n=e.checkValidity)||void 0===n?void 0:n.call(e)}))},yi=function(){return u(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${Xo}])`));return(yield Promise.all(e.map((e=>u(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})),{})}))},Ii=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},ki=function(e={}){var t,n;const o=Ir(e,["externalId","email","phone"]),r=Ir(e,["newPassword","password"]);if(o&&r)try{const e=new globalThis.PasswordCredential({id:o,password:r});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)}},Si=function(e,t){return u(this,void 0,void 0,(function*(){if("true"===e.getAttribute("formnovalidate")||h(this,ui,"m",wi).call(this)){const o=null==e?void 0:e.getAttribute("id");h(this,ui,"m",Ii).call(this,e);const r=yield h(this,ui,"m",yi).call(this),i=(n=e,Array.from((null==n?void 0:n.attributes)||[]).reduce(((e,t)=>{var n;const o=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return o?Object.assign(e,{[o]:t.value}):e}),{})),s=this.getComponentsContext(),a=Object.assign(Object.assign(Object.assign(Object.assign({},s),i),r),{origin:window.location.origin}),l=yield this.getFlowConfig(),c=yield this.getProjectConfig(),d=yield t(o,l.version,c.componentsVersion,a);h(this,gi,"f").call(this,d),h(this,ui,"m",ki).call(this,r)}var n}))},ji=function(e){this.rootElement.querySelectorAll("descope-button:not([data-exclude-next])").forEach((t=>{t.onclick=()=>{h(this,ui,"m",Si).call(this,t,e)}}))},xi=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===cr.forward?"slide-forward":"slide-backward";Array.from(this.rootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(n)})),this.rootElement.classList.add("fade-out")},Ci=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.define("descope-wc",Ei);var Ai=Object.freeze({__proto__:null,default:Ei});const Ui=(e,t,n,o={})=>{var r,i,s,a;return[Math.min(Math.max(t,("all"===o.left?e.offsetWidth:null!==(r=o.left)&&void 0!==r?r:0)-e.offsetWidth),window.innerWidth-("all"===o.right?e.offsetWidth:null!==(i=o.right)&&void 0!==i?i:0)),Math.min(Math.max(n,("all"===o.top?e.offsetHeight:null!==(s=o.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===o.bottom?e.offsetHeight:null!==(a=o.bottom)&&void 0!==a?a:0))]};var Ri,Ti,_i,Pi,Li,Mi,$i,Di,Wi,qi;const Ni=document.createElement("template");Ni.innerHTML=`\n<style>\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</style>\n\n<div style="top:32px; left:${window.innerWidth-300-32}px;" 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 Fi extends HTMLElement{constructor(){super(),Ri.add(this),Ti.set(this,new Or({messages:[]})),_i.set(this,void 0),Pi.set(this,void 0),Li.set(this,void 0),Mi.set(this,{resize:h(this,Ri,"m",qi).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Ni.content.cloneNode(!0)),p(this,_i,this.shadowRoot.querySelector(".debugger"),"f"),p(this,Pi,h(this,_i,"f").querySelector(".content"),"f"),p(this,Li,h(this,_i,"f").querySelector(".header"),"f")}updateData(e){h(this,Ti,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let o=0,r=0,i=0,s=0;function a(t){t.preventDefault(),o=i-t.clientX,r=s-t.clientY,i=t.clientX,s=t.clientY;const[a,l]=Ui(e,e.offsetLeft-o,e.offsetTop-r,n);e.style.top=`${l}px`,e.style.left=`${a}px`}function l(){document.onmouseup=null,document.onmousemove=null}function c(e){e.preventDefault(),i=e.clientX,s=e.clientY,document.onmouseup=l,document.onmousemove=a}t?t.onmousedown=c:e.onmousedown=c})(h(this,_i,"f"),h(this,Li,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",h(this,Mi,"f").resize),(e=h(this,_i,"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},h(this,_i,"f").onresize=h(this,Ri,"m",Wi).bind(this),h(this,Ti,"f").subscribe(h(this,Ri,"m",$i).bind(this))}disconnectedCallback(){h(this,Ti,"f").unsubscribeAll(),window.removeEventListener("resize",h(this,Mi,"f").resize)}}Ti=new WeakMap,_i=new WeakMap,Pi=new WeakMap,Li=new WeakMap,Mi=new WeakMap,Ri=new WeakSet,$i=function(e){h(this,Ri,"m",Di).call(this,e),h(this,Ri,"m",Wi).call(this)},Di=function(e){h(this,Pi,"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("")},Wi=function(){h(this,Pi,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,o=t.clientHeight>20;n||o?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},qi=function(){const[e,t]=Ui(h(this,_i,"f"),Number.parseInt(h(this,_i,"f").style.left,10),Number.parseInt(h(this,_i,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});h(this,_i,"f").style.top=`${t}px`,h(this,_i,"f").style.left=`${e}px`},customElements.define("descope-debugger",Fi);var Ki=Object.freeze({__proto__:null,default:Fi});e.AuthProvider=({projectId:e,baseUrl:n="",sessionTokenViaCookie:s=!1,children:l})=>{const[c,d]=t.useState(),[u,h]=t.useState(),[p,f]=t.useState(!1),[g,v]=t.useState(!1),m=(({projectId:e,baseUrl:n,sessionTokenViaCookie:o})=>t.useMemo((()=>{if(e)return Ro({projectId:e,baseUrl:n,sessionTokenViaCookie:o,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[e,n,o]))({projectId:e,baseUrl:n,sessionTokenViaCookie:s});t.useEffect((()=>{if(m){const e=m.onSessionTokenChange(h),t=m.onUserChange(d);return()=>{e(),t()}}}),[m]);const b=t.useRef(!1),w=t.useCallback((()=>{b.current||(b.current=!0,v(!0),i(m?.refresh)().then((()=>{v(!1)})))}),[m]),y=t.useCallback((()=>{f(!0),i(m.me)().then((()=>{f(!1)}))}),[m]),I=t.useMemo((()=>({fetchUser:y,user:c,isUserLoading:p,fetchSession:w,session:u,isSessionLoading:g,isSessionFetched:b.current,projectId:e,baseUrl:n,setUser:d,setSession:h,sdk:m})),[y,c,p,w,u,g,b.current,e,n,d,h,m]);return o.default.createElement(r.Provider,{value:I},l)},e.Descope=$o,e.SignInFlow=e=>o.default.createElement($o,{...e,flowId:"sign-in"}),e.SignUpFlow=e=>o.default.createElement($o,{...e,flowId:"sign-up"}),e.SignUpOrInFlow=e=>o.default.createElement($o,{...e,flowId:"sign-up-or-in"}),e.getJwtPermissions=Po,e.getJwtRoles=Lo,e.getRefreshToken=_o,e.getSessionToken=To,e.refresh=(e=_o())=>Uo?.refresh(e),e.useDescope=()=>{const{sdk:e}=Do();return t.useMemo((()=>e||new Proxy(Ro({projectId:"dummy"}),qo)),[e])},e.useSession=()=>{const{session:e,isSessionLoading:n,fetchSession:o,isSessionFetched:r}=Do(),i=t.useRef(n);return t.useMemo((()=>{i.current=n}),[n]),t.useMemo((()=>{r||(i.current=!0)}),[r]),t.useEffect((()=>{e||n||o()}),[o]),{isSessionLoading:i.current,sessionToken:e,isAuthenticated:!!e}},e.useUser=()=>{const{user:e,fetchUser:n,isUserLoading:o,session:r}=Do(),[i,s]=t.useState(!1),a=t.useRef(o),l=t.useMemo((()=>!e&&!o&&r&&!i),[n,r,i]);return t.useMemo((()=>{a.current=o}),[o]),t.useMemo((()=>{l&&(a.current=!0)}),[l]),t.useEffect((()=>{l&&(s(!0),n())}),[l]),{isUserLoading:a.current,user:e}},Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Descope={},e.React)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(t);const r=o.default.createContext(void 0),i=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},s=e=>(...t)=>{let n;try{n=e(...t)}catch(e){console.error(e)}return n},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"2.0.5"},l="undefined"!=typeof window;var c=function(){return c=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},c.apply(this,arguments)};function d(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function u(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}))}function h(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function p(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function f(e){this.message=e}"function"==typeof SuppressedError&&SuppressedError,f.prototype=new Error,f.prototype.name="InvalidCharacterError";var g="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new f("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,r=0,i=0,s="";o=t.charAt(i++);~o&&(n=r%4?64*n+o:o,r++%4)?s+=String.fromCharCode(255&n>>(-2*r&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return s};function v(e){this.message=e}function m(e,t){if("string"!=typeof e)throw new v("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(g(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return g(t)}}(e.split(".")[n]))}catch(e){throw new v("Invalid token specified: "+e.message)}}v.prototype=new Error,v.prototype.name="InvalidTokenError";var b="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y="__lodash_hash_undefined__",I="[object Function]",k="[object GeneratorFunction]",j=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,S=/^\w*$/,C=/^\./,x=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,O=/\\(\\)?/g,E=/^\[object .+?Constructor\]$/,A="object"==typeof b&&b&&b.Object===Object&&b,U="object"==typeof self&&self&&self.Object===Object&&self,R=A||U||Function("return this")();var _,T=Array.prototype,P=Function.prototype,L=Object.prototype,$=R["__core-js_shared__"],M=(_=/[^.]+$/.exec($&&$.keys&&$.keys.IE_PROTO||""))?"Symbol(src)_1."+_:"",q=P.toString,D=L.hasOwnProperty,W=L.toString,N=RegExp("^"+q.call(D).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),F=R.Symbol,H=T.splice,J=te(R,"Map"),K=te(Object,"create"),V=F?F.prototype:void 0,z=V?V.toString:void 0;function B(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function G(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Y(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Z(e,t){for(var n,o,r=e.length;r--;)if((n=e[r][0])===(o=t)||n!=n&&o!=o)return r;return-1}function X(e,t){var n;t=function(e,t){if(ie(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||ae(e))return!0;return S.test(e)||!j.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:ie(n=t)?n:ne(n);for(var o=0,r=t.length;null!=e&&o<r;)e=e[oe(t[o++])];return o&&o==r?e:void 0}function Q(e){if(!se(e)||(t=e,M&&M in t))return!1;var t,n=function(e){var t=se(e)?W.call(e):"";return t==I||t==k}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?N:E;return n.test(function(e){if(null!=e){try{return q.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function ee(e,t){var n,o,r=e.__data__;return("string"==(o=typeof(n=t))||"number"==o||"symbol"==o||"boolean"==o?"__proto__"!==n:null===n)?r["string"==typeof t?"string":"hash"]:r.map}function te(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Q(n)?n:void 0}B.prototype.clear=function(){this.__data__=K?K(null):{}},B.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},B.prototype.get=function(e){var t=this.__data__;if(K){var n=t[e];return n===y?void 0:n}return D.call(t,e)?t[e]:void 0},B.prototype.has=function(e){var t=this.__data__;return K?void 0!==t[e]:D.call(t,e)},B.prototype.set=function(e,t){return this.__data__[e]=K&&void 0===t?y:t,this},G.prototype.clear=function(){this.__data__=[]},G.prototype.delete=function(e){var t=this.__data__,n=Z(t,e);return!(n<0)&&(n==t.length-1?t.pop():H.call(t,n,1),!0)},G.prototype.get=function(e){var t=this.__data__,n=Z(t,e);return n<0?void 0:t[n][1]},G.prototype.has=function(e){return Z(this.__data__,e)>-1},G.prototype.set=function(e,t){var n=this.__data__,o=Z(n,e);return o<0?n.push([e,t]):n[o][1]=t,this},Y.prototype.clear=function(){this.__data__={hash:new B,map:new(J||G),string:new B}},Y.prototype.delete=function(e){return ee(this,e).delete(e)},Y.prototype.get=function(e){return ee(this,e).get(e)},Y.prototype.has=function(e){return ee(this,e).has(e)},Y.prototype.set=function(e,t){return ee(this,e).set(e,t),this};var ne=re((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(ae(e))return z?z.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return C.test(e)&&n.push(""),e.replace(x,(function(e,t,o,r){n.push(o?r.replace(O,"$1"):t||e)})),n}));function oe(e){if("string"==typeof e||ae(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function re(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var o=arguments,r=t?t.apply(this,o):o[0],i=n.cache;if(i.has(r))return i.get(r);var s=e.apply(this,o);return n.cache=i.set(r,s),s};return n.cache=new(re.Cache||Y),n}re.Cache=Y;var ie=Array.isArray;function se(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ae(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==W.call(e)}var le=w((function(e,t,n){var o=null==e?void 0:X(e,t);return void 0===o?n:o})),ce="/v1/auth/accesskey/exchange",de="/v1/auth/otp/verify",ue="/v1/auth/otp/signin",he="/v1/auth/otp/signup",pe={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},fe="/v1/auth/otp/signup-in",ge="/v1/auth/magiclink/verify",ve="/v1/auth/magiclink/signin",me="/v1/auth/magiclink/signup",be={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},we="/v1/auth/magiclink/signup-in",ye="/v1/auth/enchantedlink/verify",Ie="/v1/auth/enchantedlink/signin",ke="/v1/auth/enchantedlink/signup",je="/v1/auth/enchantedlink/pending-session",Se={email:"/v1/auth/enchantedlink/update/email"},Ce="/v1/auth/enchantedlink/signup-in",xe="/v1/auth/oauth/authorize",Oe="/v1/auth/oauth/exchange",Ee="/v1/auth/saml/authorize",Ae="/v1/auth/saml/exchange",Ue="/v1/auth/totp/verify",Re="/v1/auth/totp/signup",_e="/v1/auth/totp/update",Te={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},Pe={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},Le={start:"/v1/auth/webauthn/signup-in/start"},$e={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},Me="/v1/auth/password/signup",qe="/v1/auth/password/signin",De="/v1/auth/password/reset",We="/v1/auth/password/update",Ne="/v1/auth/password/replace",Fe="/v1/auth/password/policy",He="/v1/auth/refresh",Je="/v1/auth/tenant/select",Ke="/v1/auth/logout",Ve="/v1/auth/logoutall",ze="/v1/auth/me",Be="/v1/flow/start",Ge="/v1/flow/next";const Ye="<region>",Ze=`https://api.${Ye}descope.com`,Xe=6e5,Qe=()=>{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")}};var et;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(et||(et={}));const tt=(...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,o])=>(e[n]=o,e)),e),e}),{})),nt=e=>void 0===e?void 0:JSON.stringify(e),ot=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},rt=({baseUrl:e,projectId:t,baseConfig:n,logger:o,hooks:r,cookiePolicy:i,fetch:s})=>{const a=((e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),o=await n.text();return n.text=()=>Promise.resolve(o),n.json=()=>Promise.resolve(JSON.parse(o)),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=>Qe().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const o=await n(...t);return e[o.ok?"log":"error"](await(async e=>{const t=await e.text();return Qe().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(o)),o}:n})(o,s),l=async o=>{const s=(null==r?void 0:r.beforeRequest)?r.beforeRequest(o):o,{path:l,body:c,headers:d,queryParams:u,method:h,token:p}=s,f={headers:tt(ot(t,p),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.8.0"},(null==n?void 0:n.baseHeaders)||{},d),method:h,body:nt(c)};null!==i&&(f.credentials=i||"include");const g=await a((({path:e,baseUrl:t,queryParams:n,projectId:o})=>{const r=o.slice(1,-27);t=t.replace(Ye,r?r+".":"");const i=new URL(e,t);return n&&(i.search=new URLSearchParams(n).toString()),i})({path:l,baseUrl:e,queryParams:u,projectId:t}),f);return(null==r?void 0:r.afterRequest)&&await r.afterRequest(o,null==g?void 0:g.clone()),g};return{get:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:et.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:et.post,token:r}),put:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:et.put,token:r}),delete:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:et.delete,token:o}),hooks:r}};var it=429;function st(e,t,n){var o;let r=at(e);t&&(r=null===(o=null==r?void 0:r.tenants)||void 0===o?void 0:o[t]);const i=null==r?void 0:r[n];return Array.isArray(i)?i:[]}function at(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return m(e)}function lt(e){const{exp:t}=at(e);return(new Date).getTime()/1e3>t}function ct(e){let t=at(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function dt(e,t){return st(e,t,"permissions")}function ut(e,t){return st(e,t,"roles")}const ht=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function pt(e,t){var n;const o=await e,r={code:o.status,ok:o.ok,response:o},i=await o.clone().json();return o.ok?r.data=t?t(i):i:(r.error=i,o.status===it&&Object.assign(r.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),r}const ft=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),gt=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),vt=e=>t=>e.test(t),mt=vt(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),bt=vt(/^\+[1-9]{1}[0-9]{3,14}$/),wt=ft(mt,'"{val}" is not a valid email'),yt=ft(bt,'"{val}" is not a valid phone number'),It=ft((1,e=>e.length>=1),"Minimum length is 1");const kt=ft((e=>"string"==typeof e),"Input is not a string"),jt=ft((e=>void 0===e),"Input is defined"),St=(Ct=[kt(),jt()],"Input is not a string or undefined",(e="Input is not a string or undefined")=>t=>{const n=Ct.filter((e=>e(t)));return!(n.length<Ct.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var Ct;const xt=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>gt(...e).validate(n[t]))),t(...n)),Ot=e=>[kt(`"${e}" must be a string`),It(`"${e}" must not be empty`)],Et=e=>[kt(`"${e}" must be a string`),wt()],At=e=>[kt(`"${e}" must be a string`),yt()],Ut=xt(Ot("accessKey")),Rt=e=>({exchange:Ut((t=>pt(e.post(ce,{},{token:t}))))});var _t,Tt;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(_t||(_t={})),function(e){e.email="email"}(Tt||(Tt={}));const Pt=Object.assign(Object.assign({},_t),Tt);var Lt;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Lt||(Lt={}));const $t=Ot("loginId"),Mt=xt(Ot("token")),qt=xt($t),Dt=xt(Ot("pendingRef")),Wt=xt($t,Et("email")),Nt=e=>({verify:Mt((t=>pt(e.post(ye,{token:t})))),signIn:qt(((t,n,o,r)=>pt(e.post(ht(Ie,Pt.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:qt(((t,n)=>pt(e.post(ht(Ce,Pt.email),{loginId:t,URI:n})))),signUp:qt(((t,n,o)=>pt(e.post(ht(ke,Pt.email),{loginId:t,URI:n,user:o})))),waitForSession:Dt(((t,n)=>new Promise((o=>{const{pollingIntervalMs:r,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||Xe,Xe)}))(n);let s;const a=setInterval((async()=>{const n=await e.post(je,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(pt(Promise.resolve(n))))}),r);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)})))),update:{email:Wt(((t,n,o,r,i)=>pt(e.post(Se.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r}))))}}),Ft=xt(Ot("flowId")),Ht=xt(Ot("executionId"),Ot("stepId"),Ot("interactionId")),Jt=e=>({start:Ft(((t,n,o,r,i,s,a)=>pt(e.post(Be,{flowId:t,options:n,conditionInteractionId:o,interactionId:r,version:i,componentsVersion:s,input:a})))),next:Ht(((t,n,o,r,i,s)=>pt(e.post(Ge,{executionId:t,stepId:n,interactionId:o,version:r,componentsVersion:i,input:s}))))}),Kt=Ot("loginId"),Vt=xt(Ot("token")),zt=xt(Kt),Bt=xt(Kt,At("phone")),Gt=xt(Kt,Et("email")),Yt=e=>({verify:Vt((t=>pt(e.post(ge,{token:t})))),signIn:Object.keys(Pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:zt(((t,o,r,i)=>pt(e.post(ht(ve,n),{loginId:t,URI:o,loginOptions:r},{token:i}))))})),{}),signUp:Object.keys(Pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:zt(((t,o,r)=>pt(e.post(ht(me,n),{loginId:t,URI:o,user:r}))))})),{}),signUpOrIn:Object.keys(Pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:zt(((t,o)=>pt(e.post(ht(we,n),{loginId:t,URI:o}))))})),{}),update:{email:Gt(((t,n,o,r,i)=>pt(e.post(be.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r})))),phone:Object.keys(_t).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Bt(((t,o,r,i,s)=>pt(e.post(ht(be.phone,n),Object.assign({loginId:t,phone:o,URI:r},s),{token:i}))))})),{})}});var Zt;!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"}(Zt||(Zt={}));const Xt=xt(Ot("code")),Qt=e=>({start:Object.assign(((t,n,o,r)=>pt(e.post(xe,o||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:r}))),Object.keys(Zt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,r)=>pt(e.post(xe,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:r}))})),{})),exchange:Xt((t=>pt(e.post(Oe,{code:t}))))}),en=Ot("loginId"),tn=xt(en,Ot("code")),nn=xt(en),on=xt(en,At("phone")),rn=xt(en,Et("email")),sn=e=>({verify:Object.keys(Pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tn(((t,o)=>pt(e.post(ht(de,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(Pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:nn(((t,o,r)=>pt(e.post(ht(ue,n),{loginId:t,loginOptions:o},{token:r}))))})),{}),signUp:Object.keys(Pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:nn(((t,o)=>pt(e.post(ht(he,n),{loginId:t,user:o}))))})),{}),signUpOrIn:Object.keys(Pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:nn((t=>pt(e.post(ht(fe,n),{loginId:t}))))})),{}),update:{email:rn(((t,n,o,r)=>pt(e.post(pe.email,Object.assign({loginId:t,email:n},r),{token:o})))),phone:Object.keys(_t).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:on(((t,o,r,i)=>pt(e.post(ht(pe.phone,n),Object.assign({loginId:t,phone:o},i),{token:r}))))})),{})}}),an=xt(Ot("tenant")),ln=xt(Ot("code")),cn=e=>({start:an(((t,n,o,r)=>pt(e.post(Ee,o||{},{queryParams:{tenant:t,redirectURL:n},token:r})))),exchange:ln((t=>pt(e.post(Ae,{code:t}))))}),dn=Ot("loginId"),un=xt(dn,Ot("code")),hn=xt(dn),pn=xt(dn),fn=e=>({signUp:hn(((t,n)=>pt(e.post(Re,{loginId:t,user:n})))),verify:un(((t,n,o,r)=>pt(e.post(Ue,{loginId:t,code:n,loginOptions:o},{token:r})))),update:pn(((t,n)=>pt(e.post(_e,{loginId:t},{token:n}))))}),gn=Ot("loginId"),vn=Ot("newPassword"),mn=xt(gn,Ot("password")),bn=xt(gn),wn=xt(gn,vn),yn=xt(gn,Ot("oldPassword"),vn),In=e=>({signUp:mn(((t,n,o)=>pt(e.post(Me,{loginId:t,password:n,user:o})))),signIn:mn(((t,n)=>pt(e.post(qe,{loginId:t,password:n})))),sendReset:bn(((t,n)=>pt(e.post(De,{loginId:t,redirectUrl:n})))),update:wn(((t,n,o)=>pt(e.post(We,{loginId:t,newPassword:n},{token:o})))),replace:yn(((t,n,o)=>pt(e.post(Ne,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>pt(e.get(Fe))}),kn=[kt('"loginId" must be a string')],jn=Ot("loginId"),Sn=Ot("origin"),Cn=xt(jn,Sn,Ot("name")),xn=xt(jn,Sn),On=xt(kn,Sn),En=xt(jn,Sn,Ot("token")),An=xt(Ot("transactionId"),Ot("response")),Un=e=>({signUp:{start:Cn(((t,n,o)=>pt(e.post(Te.start,{user:{loginId:t,name:o},origin:n})))),finish:An(((t,n)=>pt(e.post(Te.finish,{transactionId:t,response:n}))))},signIn:{start:On(((t,n,o,r)=>pt(e.post(Pe.start,{loginId:t,origin:n,loginOptions:o},{token:r})))),finish:An(((t,n)=>pt(e.post(Pe.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:xn(((t,n)=>pt(e.post(Le.start,{loginId:t,origin:n}))))},update:{start:En(((t,n,o)=>pt(e.post($e.start,{loginId:t,origin:n},{token:o})))),finish:An(((t,n)=>pt(e.post($e.finish,{transactionId:t,response:n}))))}}),Rn=xt(Ot("token")),_n=xt([St('"token" must be string or undefined')]);var Tn,Pn=xt([("projectId",Tn=Ot("projectId"),ft(((e,t)=>n=>gt(...t).validate(le(n,e)))("projectId",Tn))())])((e=>{var t,n;const o=[].concat((null===(t=e.hooks)||void 0===t?void 0:t.beforeRequest)||[]),r=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.afterRequest)||[]);return(({projectId:e,logger:t,baseUrl:n,hooks:o,cookiePolicy:r,baseHeaders:i={},fetch:s})=>{return a=rt({baseUrl:n||Ze,projectId:e,logger:t,hooks:o,cookiePolicy:r,baseConfig:{baseHeaders:i},fetch:s}),{accessKey:Rt(a),otp:sn(a),magicLink:Yt(a),enchantedLink:Nt(a),oauth:Qt(a),saml:cn(a),totp:fn(a),webauthn:Un(a),password:In(a),flow:Jt(a),refresh:_n((e=>pt(a.post(He,{},{token:e})))),selectTenant:xt([kt("tenantId")],[St('"token" must be string or undefined')])(((e,t)=>pt(a.post(Je,{tenant:e},{token:t})))),logout:_n((e=>pt(a.post(Ke,{},{token:e})))),logoutAll:_n((e=>pt(a.post(Ve,{},{token:e})))),me:_n((e=>pt(a.get(ze,{token:e})))),isJwtExpired:Rn(lt),getTenants:Rn(ct),getJwtPermissions:Rn(dt),getJwtRoles:Rn(ut),httpClient:a};var a})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:e=>null==o?void 0:o.reduce(((e,t)=>t(e)),e),afterRequest:async(t,n)=>{(await Promise.allSettled(null==r?void 0:r.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))}))}}}))}));const Ln=(e,t,n)=>(t.forEach((t=>{const o=t.split(".");let r=o.shift(),i=e;for(;o.length>0;){if(i=i[r],!r||!i)throw Error(`Invalid path "${t}", "${r}" is missing or has no value`);r=o.shift()}if("function"!=typeof i[r])throw Error(`"${t}" is not a function`);const s=i[r];i[r]=n(s)})),e);var $n=Object.assign(Pn,{DeliveryMethods:Pt});var Mn="Blocked by CSP",qn="9319";function Dn(e,t){var n=[];return function(e,t){var n,o,r=(o=function(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0),{current:function(){return o[0]},postpone:function(){var e=o.shift();void 0!==e&&o.push(e)},exclude:function(){o.shift()}}),i=(100,3e3,n=0,function(){return Math.random()*Math.min(3e3,100*Math.pow(2,n++))}),s=r.current();if(void 0===s)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var a=function(e,n){return t(e).catch((function(e){if(n+1>=5)throw e;!function(e){if(!(e instanceof Error))return!1;var t=e.message;return t===Mn||t===qn}(e)?r.postpone():r.exclude();var t,o=r.current();if(void 0===o)throw e;return(t=i(),new Promise((function(e){return setTimeout(e,t)}))).then((function(){return a(o,n+1)}))}))};return a(s,0)}(e,(function(e){var o=new Date,r=function(t){return n.push({url:e,startedAt:o,finishedAt:new Date,error:t})},i=t(e);return i.then((function(){return r()}),r),i})).then((function(e){return[e,{attempts:n}]}))}var Wn="Failed to load the JS script of the agent";function Nn(e){var t;e.scriptUrlPattern;var n=e.token,o=e.apiKey,r=void 0===o?n:o,i=d(e,["scriptUrlPattern","token","apiKey"]),s=null!==(t=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(e,"scriptUrlPattern"))&&void 0!==t?t:"https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js";return Promise.resolve().then((function(){if(!r||"string"!=typeof r)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.8.5"):e}))}(String(e),t)}))}(s,r);return Dn(e,Fn).catch(Jn)})).then((function(e){var t=e[0],n=e[1];return t.load(c(c({},i),{ldi:n}))}))}function Fn(e){return function(e,t,n,o){var r,i=document,s="securitypolicyviolation",a=function(t){var n=new URL(e,location.href),o=t.blockedURI;o!==n.href&&o!==n.protocol.slice(0,-1)&&o!==n.origin||(r=t,l())};i.addEventListener(s,a);var l=function(){return i.removeEventListener(s,a)};return Promise.resolve().then(t).then((function(e){return l(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(l(),r)return function(){throw new Error(Mn)}();throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){var o=document.createElement("script"),r=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},i=document.head||document.getElementsByTagName("head")[0];o.onload=function(){r(),t()},o.onerror=function(){r(),n(new Error(Wn))},o.async=!0,o.src=e,i.appendChild(o)}))}(e)})).then(Hn)}function Hn(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,o=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==o?void 0:o.configurable)?delete e[t]:o&&!o.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(qn);return n}function Jn(e){throw e instanceof Error&&e.message===qn?new Error(Wn):e}var Kn={exports:{}};
|
|
2
|
+
/*! js-cookie v3.0.5 | MIT */!function(e,t){e.exports=function(){function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}function t(n,o){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=e({},o,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in i)i[a]&&(s+="; "+a,!0!==i[a]&&(s+="="+i[a].split(";")[0]));return document.cookie=t+"="+n.write(r,t)+s}}function i(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},r=0;r<t.length;r++){var i=t[r].split("="),s=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(o[a]=n.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}}return Object.create({set:r,get:i,remove:function(t,n){r(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}return 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:"/"})}()}(Kn);var Vn=w(Kn.exports);const zn=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var r;return n[o]=[].concat((null===(r=e.hooks)||void 0===r?void 0:r[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},Bn=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||{}},Gn=async e=>{const t=await Bn(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},Yn="undefined"!=typeof localStorage,Zn=(e,t)=>Yn&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),Xn=e=>Yn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Qn=e=>Yn&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),eo=(...e)=>{console.debug(...e)},to="undefined"!=typeof window,no=Math.pow(2,31)-1,oo=to&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",ro="fp",io=(e=!1)=>{const t=localStorage.getItem(ro);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},so=async e=>{try{if(io())return;const t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),n=Nn({apiKey:e,endpoint:oo}),o=await n,{requestId:r}=await o.get({linkedId:t}),i=((e,t)=>({vsid:e,vrid:t}))(t,r);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem(ro,JSON.stringify(t))})(i)}catch(e){global.FB_DEBUG&&console.error(e)}},ao=e=>{const t=io(!0);return t&&e.body&&(e.body.fpData=t),e},lo="dls_last_user_login_id",co="dls_last_user_display_name",uo=()=>Xn(lo),ho=()=>Xn(co),po=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,r=uo(),i=ho();return r&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=r,o.lastAuth.name=i),await e(...t)},fo=e=>async(...t)=>{const n=await e(...t);return Qn(lo),Qn(co),n};function go(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const vo="DS",mo="DSR";function bo(e=""){return Xn(`${e}${mo}`)||""}function wo(e=""){Qn(`${e}${mo}`),Qn(`${e}${vo}`),Vn.remove(vo)}async function yo(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=xo(n.publicKey.challenge),n.publicKey.user.id=xo(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=xo(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:Oo(n.rawId),type:n.type,response:{attestationObject:Oo(n.response.attestationObject),clientDataJSON:Oo(n.response.clientDataJSON)}});var n}async function Io(e){const t=So(e);return Co(await navigator.credentials.get(t))}async function ko(e,t){const n=So(e);return n.signal=t.signal,n.mediation="conditional",Co(await navigator.credentials.get(n))}async function jo(e=!1){if(!to)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 So(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=xo(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=xo(e.id)})),n}function Co(e){return JSON.stringify({id:e.id,rawId:Oo(e.rawId),type:e.type,response:{authenticatorData:Oo(e.response.authenticatorData),clientDataJSON:Oo(e.response.clientDataJSON),signature:Oo(e.response.signature),userHandle:e.response.userHandle?Oo(e.response.userHandle):void 0}})}function xo(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function Oo(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Eo,Ao=(Eo=e=>({async signUp(t,n){const o=await e.webauthn.signUp.start(t,window.location.origin,n);if(!o.ok)return o;const r=await yo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,r)},async signIn(t){const n=await e.webauthn.signIn.start(t,window.location.origin);if(!n.ok)return n;const o=await Io(n.data.options);return await e.webauthn.signIn.finish(n.data.transactionId,o)},async signUpOrIn(t){var n;const o=await e.webauthn.signUpOrIn.start(t,window.location.origin);if(!o.ok)return o;if(null===(n=o.data)||void 0===n?void 0:n.create){const t=await yo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await Io(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,t)}},async update(t,n){const o=await e.webauthn.update.start(t,window.location.origin,n);if(!o.ok)return o;const r=await yo(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,r)},helpers:{create:yo,get:Io,isSupported:jo,conditional:ko}}),(...e)=>{const t=Eo(...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}),Uo=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await jo(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});const Ro=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var{fpKey:n,fpLoad:o}=t,r=d(t,["fpKey","fpLoad"]);return to?(n&&o&&so(n).catch((()=>null)),e(zn(r,{beforeRequest:ao}))):(console.warn("Fingerprint is a client side only capability and will not work when running in the server"),e(r))}),(e=>t=>{var{autoRefresh:n}=t,o=d(t,["autoRefresh"]);if(!n)return e(o);const{clearAllTimers:r,setTimer:i}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let s,a;document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&new Date>s&&(eo("Expiration time passed, refreshing session"),l.refresh(a))}));const l=e(zn(o,{afterRequest:async(e,t)=>{const{refreshJwt:n,sessionJwt:o}=await Bn(t);if(401===(null==t?void 0:t.status))eo("Received 401, canceling all timers"),r();else if(o){s=(e=>{const t=e.split(".");try{if(3===t.length){const e=JSON.parse(window.atob(t[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(e){}return null})(o),a=n;let e=((c=s)?c.getTime()-(new Date).getTime():0)-2e4;e>no&&(eo(`Timeout is too large (${e}ms), setting it to ${no}ms`),e=no),r();const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});eo(`Setting refresh timer for ${t}. (${e}ms)`),i((()=>{eo("Refreshing session due to timer"),l.refresh(n)}),e)}var c}}));return Ln(l,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return eo("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.9.0"},t.baseHeaders)}))),(e=>t=>{const n=go(),o=go(),r=e(zn(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))n.pub(null),o.pub(null);else{const e=await Gn(t);e&&o.pub(e);const{sessionJwt:r}=await Bn(t);r&&n.pub(r)}}})),i=Ln(r,["logout","logoutAll"],(e=>async(...t)=>{const r=await e(...t);return n.pub(null),o.pub(null),r}));return Object.assign(i,{onSessionTokenChange:n.sub,onUserChange:o.sub})}),(e=>t=>{const n=e(zn(t,{afterRequest:async(e,t)=>{var n;const o=await Gn(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],i=null==o?void 0:o.name;r&&((e=>{Zn(lo,e)})(r),(e=>{Zn(co,e)})(i))}}));let o=Ln(n,["flow.start"],po);return o=Ln(o,["logout","logoutAll"],fo),Object.assign(o,{getLastUserLoginId:uo,getLastUserDisplayName:ho})}),(e=>t=>{var{persistTokens:n,sessionTokenViaCookie:o,storagePrefix:r}=t,i=d(t,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!n||!to)return n&&console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),e(i);const s=e(zn(i,{beforeRequest:(a=r,e=>Object.assign(e,{token:e.token||bo(a)})),afterRequest:async(e,t)=>{401===(null==t?void 0:t.status)?wo(r):((e={},t,n)=>{var{refreshJwt:o,sessionJwt:r}=e,i=d(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),void 0===n&&(n=""),o&&Zn(`${n}${mo}`,o),r&&(t?function(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:r}){if(t){const i=new Date(1e3*r);Vn.set(e,t,{path:n,domain:o,expires:i,sameSite:"Strict",secure:!0})}}(vo,r,i):Zn(`${n}${vo}`,r))})(await Bn(t),o,r)}}));var a;const l=Ln(s,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return wo(e),o})(r));return Object.assign(l,{getRefreshToken:()=>bo(r),getSessionToken:()=>function(e=""){return Vn.get(vo)||Xn(`${e}${vo}`)||""}(r)})}))(((...e)=>{const t=$n(...e);return Object.assign(Object.assign({},t),{flow:Uo(t),webauthn:Ao(t)})}));let _o;const To=e=>{const t=Ro({...e,persistTokens:l,autoRefresh:l});return _o=t,t};_o=To({projectId:"temp pid"});const Po=()=>l?_o?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),Lo=()=>l?_o?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),$o=s(((e=Po(),t)=>_o?.getJwtPermissions(e,t))),Mo=s(((e=Po(),t)=>_o?.getJwtRoles(e,t)));const qo=t.lazy((async()=>((await Promise.resolve().then((function(){return Pi}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:n,innerRef:r,tenant:i,theme:s,locale:a,debug:l,redirectUrl:c,client:d,form:u,autoFocus:h})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":n,ref:r,tenant:i,theme:s,locale:a,debug:l,client:d,form:u,"redirect-url":c,"auto-focus":h})}))),Do=o.default.forwardRef((({flowId:e,onSuccess:n,onError:i,logger:s,tenant:a,theme:l,locale:c,debug:d,client:u,form:h,telemetryKey:p,redirectUrl:f,autoFocus:g,errorTransformer:v},m)=>{const[b,w]=t.useState(null);t.useImperativeHandle(m,(()=>b));const{projectId:y,baseUrl:I,sdk:k}=o.default.useContext(r),j=t.useCallback((async e=>{await k.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);t.useEffect((()=>{const e=b;return e?.addEventListener("success",j),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",j)}}),[b,i,j]),t.useEffect((()=>{b&&(b.errorTransformer=v)}),[b,v]),t.useEffect((()=>{b&&s&&(b.logger=s)}),[b,s]);const{form:S,client:C}=t.useMemo((()=>({form:JSON.stringify(h||{}),client:JSON.stringify(u||{})})),[h,u]);return o.default.createElement("form",null,o.default.createElement(t.Suspense,{fallback:null},o.default.createElement(qo,{projectId:y,flowId:e,baseUrl:I,innerRef:w,tenant:a,theme:l,locale:c,debug:d,form:S,client:C,telemetryKey:p,redirectUrl:f,autoFocus:g})))}));var Wo=()=>{const e=t.useContext(r);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const No=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,Fo={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],Fo);if("function"==typeof e[t])return()=>{throw Error(No("function"))};throw Error(No("attribute"))}},Ho="undefined"!=typeof localStorage,Jo=Ho&&localStorage.getItem("base.content.url")||"https://static.descope.com/pages",Ko="config.json",Vo="base.ui.components.url",zo=Ho&&localStorage.getItem(Vo)||"https://static.descope.com/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Bo=Ho&&localStorage.getItem(Vo)||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Go="descope-login-flow",Yo="code",Zo="ra-challenge",Xo="ra-callback",Qo="ra-backup-callback",er="ra-initiator",tr="data-exclude-field",nr="dls_last_auth",or="state_id",rr="saml_idp_state_id",ir="saml_idp_username",sr="sso_app_id",ar="oidc_login_hint",lr="data-type",cr="poll",dr="webauthnCreate",ur="submit",hr="polling";var pr;function fr(e){return new URLSearchParams(window.location.search).get(e)}function gr(e){if(window.history.replaceState&&fr(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 vr(e,t){return u(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||"text"](),headers:Object.fromEntries(n.headers.entries())}}))}function mr(e,t,n="v2-beta"){const o=new URL(Jo);return o.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(o.pathname,e,n,t),o.toString()}function br(e,t){if(!Number.isNaN(e)&&!Number.isNaN(t))return e>t?pr.forward:e<t?pr.backward:void 0}!function(e){e.backward="backward",e.forward="forward"}(pr||(pr={}));const wr=()=>{const[e="",t=""]=(fr(Go)||"").split("_");return{executionId:e,stepId:t}};function yr(){gr(Go)}const Ir=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),kr=e=>{let t,n;return(...o)=>{return t&&(i=o,(r=t).length===i.length&&r.every(((e,t)=>e===i[t])))||(t=o,n=e(...o)),n;var r,i}},jr=(e,t,n,o,r,i)=>e&&!t&&e&&!n&&!o&&e&&!r&&e&&!i,Sr=e=>null==e?void 0:e.submit(),Cr=(e,t)=>{const n=t.find((t=>e[t]));return n?e[n]:null};var xr,Or,Er,Ar;function Ur(e,t){const n=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(n.length!==o.length)return!1;for(let o=0;o<n.length;o+=1){const r=n[o],i=e[r],s=t[r];if(null===i||null===s){if(i!==s)return!1}else if("object"==typeof i&&"object"==typeof s){if(!Ur(i,s))return!1}else if(i!==s)return!1}return!0}class Rr{constructor(e={},{updateOnlyOnChange:t=!0}={}){xr.set(this,void 0),Or.set(this,{}),Er.set(this,0),Ar.set(this,!1),this.update=e=>{const t="function"==typeof e?e(h(this,xr,"f")):e,n=Object.assign(Object.assign({},h(this,xr,"f")),t);if(!h(this,Ar,"f")||!Ur(h(this,xr,"f"),n)){const e=h(this,xr,"f");p(this,xr,n,"f"),Object.freeze(h(this,xr,"f")),setTimeout((()=>{Object.values(h(this,Or,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},p(this,xr,e,"f"),p(this,Ar,t,"f")}get current(){return Object.assign({},h(this,xr,"f"))}subscribe(e){return p(this,Er,h(this,Er,"f")+1,"f"),h(this,Or,"f")[h(this,Er,"f")]=e,h(this,Er,"f").toString()}unsubscribe(e){const t=!!h(this,Or,"f")[e];return t&&delete h(this,Or,"f")[e],t}unsubscribeAll(){return p(this,Or,{},"f"),!0}}xr=new WeakMap,Or=new WeakMap,Er=new WeakMap,Ar=new WeakMap;const _r=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${tr}])`)).forEach((e=>{e.value=n}))}))},Tr=(e,t)=>e.replace(/{{(.+?)}}/g,((e,n)=>{return o=t,n.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),o);var o})),Pr=kr((()=>u(void 0,void 0,void 0,(function*(){var e,t,n,o;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return!1;try{const r=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(100,n=r,o=i,new Promise(((e,t)=>{let r=!1;const i=setTimeout((()=>{r=!0,void 0!==o?e(o):t(new Error("Promise timed out after 100 ms"))}),100);n.then((t=>{r||(clearTimeout(i),e(t))})).catch((e=>{r||(clearTimeout(i),t(e))}))})))}catch(e){return console.error("Conditional login check failed",e),!1}})))),Lr={"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 $r(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(nr)))}catch(e){}return t}const Mr="dls_ab_testing_id",qr=document.createElement("template");var Dr,Wr,Nr,Fr,Hr,Jr,Kr,Vr,zr,Br,Gr,Yr,Zr,Xr,Qr,ei,ti,ni,oi,ri,ii,si,ai,li,ci,di,ui,hi,pi,fi,gi,vi,mi,bi,wi,yi,Ii,ki,ji,Si,Ci,xi,Oi,Ei,Ai,Ui,Ri;qr.innerHTML='\n\t<style>\n\t\t:host {\n all: initial;\n\t\t\twidth: 100%;\n\t\t\theight: 100%;\n\t\t}\n\n\t\t#wc-root {\n\t\t\theight: 100%;\n\t\t\ttransition: opacity 300ms ease-in-out;\n\t\t}\n\n\t\t#wc-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\t</style>\n\t<div id="wc-root"></div>\n\t';class _i extends HTMLElement{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","theme","locale","debug","storage-prefix","preview","redirect-url","auto-focus"]}constructor(e){super(),Dr.add(this),this.logger=console,Wr.set(this,!1),this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),h(this,Dr,"m",ui).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)}},Nr.set(this,new Rr({deferredRedirect:!1})),Fr.set(this,new Rr),Hr.set(this,{}),this.getComponentsContext=()=>h(this,Hr,"f"),this.nextRequestStatus=new Rr({isLoading:!1}),Jr.set(this,void 0),Kr.set(this,{popstate:h(this,Dr,"m",Zr).bind(this),visibilitychange:h(this,Dr,"m",Xr).bind(this),componentsContext:h(this,Dr,"m",ai).bind(this)}),Vr.set(this,void 0),oi.set(this,kr((()=>u(this,void 0,void 0,(function*(){const e=mr(this.projectId,Ko);try{const{body:t,headers:n}=yield vr(e,"json");return{projectConfig:t,executionContext:{geo:n["x-geo"]}}}catch(e){return{isMissingConfig:!0}}}))))),p(this,Vr,e,"f"),h(this,Dr,"m",zr).call(this)}get projectId(){return this.getAttribute("project-id")}get flowId(){return this.getAttribute("flow-id")}get form(){try{const e=JSON.parse(this.getAttribute("form"))||{};return Object.entries(e).reduce(((e,[t,n])=>Object.assign(Object.assign({},e),{[`form.${t}`]:n})),e)}catch(e){return{}}}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(e){return{}}}get baseUrl(){return this.getAttribute("base-url")||void 0}get tenant(){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 theme(){var e,t;const n=this.getAttribute("theme");return"os"===n?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":n||"light"}get autoFocus(){var e;const t=null!==(e=this.getAttribute("auto-focus"))&&void 0!==e?e:"true";return"skipFirstScreen"===t?t:"true"===t}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}getExecutionContext(){return u(this,void 0,void 0,(function*(){const{executionContext:e}=yield h(this,oi,"f").call(this);return e}))}getProjectConfig(){return u(this,void 0,void 0,(function*(){const{projectConfig:e}=yield h(this,oi,"f").call(this);return e}))}getFlowConfig(){var e,t;return u(this,void 0,void 0,(function*(){const n=yield this.getProjectConfig(),o=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=o.version)&&void 0!==t||(o.version=0),o}))}getTargetLocales(){return u(this,void 0,void 0,(function*(){const e=yield this.getFlowConfig();return((null==e?void 0:e.targetLocales)||[]).map((e=>e.toLowerCase()))}))}connectedCallback(){return u(this,void 0,void 0,(function*(){if(this.shadowRoot.isConnected){if(h(this,Fr,"f").subscribe(h(this,Dr,"m",di).bind(this)),h(this,Fr,"f").update({isDebug:this.debug}),h(this,Dr,"m",Br).call(this))return void h(this,Dr,"m",Gr).call(this);if(h(this,Dr,"m",Yr).call(this),yield h(this,Dr,"m",ti).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");if((yield h(this,oi,"f").call(this)).isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");yield h(this,Dr,"m",fi).call(this),yield h(this,Dr,"m",ii).call(this),h(this,Dr,"m",ri).call(this),h(this,Dr,"m",hi).call(this);const{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCallbackUrl:i,redirectAuthBackupCallbackUri:s,redirectAuthCodeChallenge:a,redirectAuthInitiator:l,oidcIdpStateId:c,samlIdpStateId:d,samlIdpUsername:u,ssoAppId:f,oidcLoginHint:g}=(()=>{const{executionId:e,stepId:t}=wr();(e||t)&&yr();const n=fr("t")||void 0;n&&gr("t");const o=fr(Yo)||void 0;o&&gr(Yo);const r=fr("err")||void 0;r&&gr("err");const{redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthBackupCallbackUri:a,redirectAuthInitiator:l}={redirectAuthCodeChallenge:fr(Zo),redirectAuthCallbackUrl:fr(Xo),redirectAuthBackupCallbackUri:fr(Qo),redirectAuthInitiator:fr(er)};(i||s||a||l)&&(gr(Zo),gr(Xo),gr(Qo),gr(er));const c=fr(or);c&&gr(or);const d=fr(rr);d&&gr(rr);const u=fr(ir);d&&gr(ir);const h=fr(sr);h&&gr(sr);const p=fr(ar);return p&&gr(ar),{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthBackupCallbackUri:a,redirectAuthInitiator:l,oidcIdpStateId:c,samlIdpStateId:d,samlIdpUsername:u,ssoAppId:h,oidcLoginHint:p}})();window.addEventListener("popstate",h(this,Kr,"f").popstate),window.addEventListener("components-context",h(this,Kr,"f").componentsContext),window.addEventListener("visibilitychange",h(this,Kr,"f").visibilitychange),h(this,Nr,"f").subscribe(h(this,Dr,"m",ei).bind(this)),h(this,Nr,"f").update({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenant,redirectUrl:this.redirectUrl,locale:this.locale,stepId:t,executionId:e,token:n,code:o,exchangeError:r,redirectAuthCallbackUrl:i,redirectAuthBackupCallbackUri:s,redirectAuthCodeChallenge:a,redirectAuthInitiator:l,oidcIdpStateId:c,samlIdpStateId:d,samlIdpUsername:u,ssoAppId:f,oidcLoginHint:g}),p(this,Wr,!0,"f")}}))}disconnectedCallback(){h(this,Nr,"f").unsubscribeAll(),h(this,Fr,"f").unsubscribeAll(),h(this,Dr,"m",ci).call(this),window.removeEventListener("popstate",h(this,Kr,"f").popstate),window.removeEventListener("visibilitychange",h(this,Kr,"f").visibilitychange),window.removeEventListener("components-context",h(this,Kr,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&h(this,Wr,"f")&&t!==n&&_i.observedAttributes.includes(e)){h(this,Dr,"m",Yr).call(this);const o=null===t;h(this,Nr,"f").update((({stepId:t,executionId:r})=>{let i=t,s=r;return o||(s=null,i=null,yr()),{[Ir(e)]:n,stepId:i,executionId:s}})),h(this,Fr,"f").update({isDebug:this.debug})}}}Wr=new WeakMap,Nr=new WeakMap,Fr=new WeakMap,Hr=new WeakMap,Jr=new WeakMap,Kr=new WeakMap,Vr=new WeakMap,oi=new WeakMap,Dr=new WeakSet,zr=function(){this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(qr.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#wc-root")},Br=function(){return!this.shadowRoot.host.closest("form")&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},Gr=function(){const e=this.shadowRoot.host,t=document.createElement("form");e.parentElement.appendChild(t),t.appendChild(e)},Yr=function(){const e=["base-url","tenant","theme","locale","debug","redirect-url","auto-focus","preview","storage-prefix","form","client"];if(_i.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[Ir(t)])throw Error(`${t} cannot be empty`)})),this.theme&&"light"!==this.theme&&"dark"!==this.theme)throw Error('Supported theme values are "light", "dark", or leave empty for using the OS theme')},Zr=function(){const{stepId:e,executionId:t}=wr();h(this,Nr,"f").update({stepId:e,executionId:t})},Xr=function(){document.hidden||setTimeout((()=>{h(this,Nr,"f").update({deferredRedirect:!1})}),300)},Qr=function(e,t){this.sdk=Ro(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix},_i.sdkConfigOverrides),{projectId:e,baseUrl:t})),["start","next"].forEach((e=>{const t=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>u(this,void 0,void 0,(function*(){this.nextRequestStatus.update({isLoading:!0});try{return yield t(...e)}finally{this.nextRequestStatus.update({isLoading:!1})}}))}))},ei=function(e,t,n){return u(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:o}=e;if(n("projectId")||n("baseUrl")){if(!t)return;h(this,Dr,"m",Qr).call(this,t,o)}h(this,Vr,"f").call(this,e)}))},ti=function(){return u(this,void 0,void 0,(function*(){return(yield h(this,oi,"f").call(this)).isMissingConfig&&(yield h(this,Dr,"m",ni).call(this))}))},ni=function(){return u(this,void 0,void 0,(function*(){const e=mr(this.projectId,Ko,"v2-alpha");try{return yield vr(e,"json"),!0}catch(e){return!1}}))},ri=function(){var e,t;return u(this,void 0,void 0,(function*(){const{projectConfig:n}=yield h(this,oi,"f").call(this),o=null===(t=null===(e=null==n?void 0:n.cssTemplate)||void 0===e?void 0:e[this.theme])||void 0===t?void 0:t.fonts;o&&Object.values(o).forEach((e=>(e=>{if(!e)return;const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url)))}))},ii=function(){return u(this,void 0,void 0,(function*(){yield h(this,Dr,"m",si).call(this),yield h(this,Dr,"m",li).call(this)}))},si=function(){var e,t,n,o;return u(this,void 0,void 0,(function*(){const r=document.createElement("style"),i=mr(this.projectId,"theme.json");try{const{body:s}=yield vr(i,"json");r.innerText=((null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.globals)||"")+((null===(t=null==s?void 0:s.dark)||void 0===t?void 0:t.globals)||"");const a=yield _i.descopeUI;(null==a?void 0:a.componentsThemeManager)&&(a.componentsThemeManager.themes={light:null===(n=null==s?void 0:s.light)||void 0===n?void 0:n.components,dark:null===(o=null==s?void 0:s.dark)||void 0===o?void 0:o.components})}catch(r){this.loggerWrapper.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}this.shadowRoot.appendChild(r)}))},ai=function(e){p(this,Hr,Object.assign(Object.assign({},e.detail),h(this,Hr,"f")),"f")},li=function(){return u(this,void 0,void 0,(function*(){this.rootElement.setAttribute("data-theme",this.theme);const e=yield _i.descopeUI;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)}))},ci=function(){var e;null===(e=h(this,Jr,"f"))||void 0===e||e.remove(),p(this,Jr,null,"f")},di=function({isDebug:e}){return u(this,void 0,void 0,(function*(){e?(p(this,Jr,document.createElement("descope-debugger"),"f"),Object.assign(h(this,Jr,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Bi})),document.body.appendChild(h(this,Jr,"f"))):h(this,Dr,"m",ci).call(this)}))},ui=function(e,t){var n;e&&this.debug&&(null===(n=h(this,Jr,"f"))||void 0===n||n.updateData({title:e,description:t}))},hi=function(){this.rootElement.onkeydown=e=>{if("Enter"!==e.key)return;e.preventDefault();const t=this.rootElement.querySelectorAll("descope-button");if(1===t.length)return void t[0].click();const n=Array.from(t).filter((e=>"button"===e.getAttribute("data-type")));1===n.length&&n[0].click()}},pi=function(){var e,t;return u(this,void 0,void 0,(function*(){return(null===(t=null===(e=yield h(this,oi,"f").call(this))||void 0===e?void 0:e.projectConfig)||void 0===t?void 0:t.componentsVersion)||(this.logger.error("Did not get components version, using latest version"),"latest")}))},fi=function(){return u(this,void 0,void 0,(function*(){_i.descopeUI?this.loggerWrapper.info("DescopeUI is already loading, probably multiple flows are running on the same page"):_i.descopeUI=new Promise((e=>{if(globalThis.DescopeUI)return void e(globalThis.DescopeUI);const t=e=>{const t=document.createElement("script");return t.id="load-descope-ui",t.src=e,t},n=(e,t)=>e.replace("<version>",t),o=(t,n)=>{const o=()=>{this.loggerWrapper.error("Cannot load DescopeUI",`Make sure this URL is valid and return the correct script: "${t.src}"`),n()};t.addEventListener("load",(()=>{globalThis.DescopeUI||o(),e(globalThis.DescopeUI)})),t.addEventListener("error",o)};(()=>{u(this,void 0,void 0,(function*(){const r=yield h(this,Dr,"m",pi).call(this),i=t(n(zo,r));o(i,(()=>{i.remove(),this.loggerWrapper.info("Trying to load DescopeUI from a fallback URL");const s=t(n(Bo,r));o(s,(()=>{e(void 0)})),document.body.append(s)})),document.body.append(i)}))})()}))}))},_i.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.7.0"}};class Ti extends _i{static set sdkConfigOverrides(e){_i.sdkConfigOverrides=e}constructor(){const e=new Rr;super(e.update.bind(e)),gi.add(this),this.stepState=new Rr({},{updateOnlyOnChange:!1}),vi.set(this,void 0),mi.set(this,null),bi.set(this,(()=>{clearInterval(h(this,vi,"f")),p(this,vi,null,"f")})),wi.set(this,(e=>{var t,n,o,r,i,s,a,l,c;if(!(null==e?void 0:e.ok)){h(this,bi,"f").call(this),h(this,gi,"m",Ri).call(this,"error",null==e?void 0:e.error);const s=null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url,a=`${null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status} - ${null===(o=null==e?void 0:e.response)||void 0===o?void 0:o.statusText}`;return void this.loggerWrapper.error((null===(r=null==e?void 0:e.error)||void 0===r?void 0:r.errorDescription)||s,(null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.errorMessage)||a)}const d=null===(l=null===(a=null===(s=e.data)||void 0===s?void 0:s.screen)||void 0===a?void 0:a.state)||void 0===l?void 0:l.errorText;(null===(c=e.data)||void 0===c?void 0:c.error)?this.loggerWrapper.error(`[${e.data.error.code}]: ${e.data.error.description}`,`${d?`${d} - `:""}${e.data.error.message}`):d&&this.loggerWrapper.error(d);const{status:u,authInfo:p,lastAuth:f}=e.data;if("completed"===u)return function(e){(null==e?void 0:e.authMethod)&&Ho&&localStorage.setItem(nr,JSON.stringify(e))}(f),h(this,bi,"f").call(this),void h(this,gi,"m",Ri).call(this,"success",p);const{executionId:g,stepId:v,stepName:m,action:b,screen:w,redirect:y,webauthn:I,error:k,samlIdpResponse:j}=e.data;b!==cr?(this.loggerWrapper.info(`Step "${m||`#${v}`}" is ${u}`,"",{screen:w,status:u,stepId:v,stepName:m,action:b,error:k}),this.flowState.update({stepId:v,executionId:g,action:b,redirectTo:null==y?void 0:y.url,screenId:null==w?void 0:w.id,screenState:null==w?void 0:w.state,webauthnTransactionId:null==I?void 0:I.transactionId,webauthnOptions:null==I?void 0:I.options,samlIdpResponseUrl:null==j?void 0:j.url,samlIdpResponseSamlResponse:null==j?void 0:j.samlResponse,samlIdpResponseRelayState:null==j?void 0:j.relayState})):this.flowState.update({action:b})})),yi.set(this,kr((()=>u(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.error("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.error("Webauthn start failed",e.message)}}))))),this.flowState=e}connectedCallback(){const e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});var t,n;return u(this,void 0,void 0,(function*(){this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(n=this.stepState)||void 0===n||n.subscribe(this.onStepChange.bind(this))),yield e.connectedCallback.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=h(this,mi,"f"))||void 0===e||e.abort(),p(this,mi,null,"f")}getHtmlFilenameWithLocale(e,t){return u(this,void 0,void 0,(function*(){let n,o=navigator.language;o&&"zh-TW"!==o&&(o=o.split("-")[0]);const r=(e||o||"").toLowerCase();return(yield this.getTargetLocales()).includes(r)&&(n=`${t}-${r}.html`),n}))}getPageContent(e,t){return u(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield vr(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 vr(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(e,t,n){var o,r;return u(this,void 0,void 0,(function*(){const{projectId:i,flowId:s,tenant:a,stepId:l,executionId:c,action:d,screenId:f,screenState:g,redirectTo:v,redirectUrl:m,token:b,code:w,exchangeError:y,webauthnTransactionId:I,webauthnOptions:k,redirectAuthCodeChallenge:j,redirectAuthCallbackUrl:S,redirectAuthBackupCallbackUri:C,redirectAuthInitiator:x,oidcIdpStateId:O,locale:E,samlIdpStateId:A,samlIdpUsername:U,samlIdpResponseUrl:R,samlIdpResponseSamlResponse:_,samlIdpResponseRelayState:T,ssoAppId:P,oidcLoginHint:L}=e;let $,M;h(this,vi,"f")&&h(this,bi,"f").call(this);const q=(()=>{const e=localStorage.getItem(Mr);if(!e){const e=Math.floor(100*Math.random()+1);return localStorage.setItem(Mr,e.toString()),e}return Number(e)})(),D=this.sdk.getLastUserLoginId(),W=yield this.getFlowConfig(),N=yield this.getProjectConfig(),F=S&&j?{callbackUrl:S,codeChallenge:j,backupCallbackUri:C}:void 0;if(!c&&(W.fingerprintEnabled&&W.fingerprintKey?so(W.fingerprintKey):localStorage.removeItem(ro),W.conditions?({startScreenId:$,conditionInteractionId:M}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n,predicate:o})=>{var r;if("ELSE"===t)return!0;const i=null===(r=Lr[t])||void 0===r?void 0:r[n];return!!(null==i?void 0:i(e,o))}));return n?{startScreenId:n.met.screenId,conditionInteractionId:n.met.interactionId}:{}})({loginId:D,code:w,token:b,abTestingKey:q},W.conditions)):W.condition?({startScreenId:$,conditionInteractionId:M}=((e,t)=>{var n;const o=null===(n=Lr[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const r=o(t,e.predicate)?e.met:e.unmet;return{startScreenId:null==r?void 0:r.screenId,conditionInteractionId:null==r?void 0:r.interactionId}})(W.condition,{loginId:D,code:w,token:b,abTestingKey:q})):$=W.startScreenId,!jr($,O,A,U,P,L))){const e=yield this.sdk.flow.start(s,Object.assign(Object.assign({tenant:a,redirectAuth:F,oidcIdpStateId:O,samlIdpStateId:A,samlIdpUsername:U,ssoAppId:P,oidcLoginHint:L,client:this.client},m&&{redirectUrl:m}),{lastAuth:$r(D),abTestingKey:q}),M,"",W.version,N.componentsVersion,Object.assign(Object.assign(Object.assign(Object.assign({},this.form),w?{exchangeCode:w,idpInitiated:!0}:{}),b?{token:b}:{}),L?{externalId:L}:{}));return h(this,wi,"f").call(this,e),void("completed"!==(null===(o=null==e?void 0:e.data)||void 0===o?void 0:o.status)&&this.flowState.update({code:void 0,token:void 0}))}if(c&&(n("token")&&b||n("code")&&w||n("exchangeError")&&y)){const e=yield this.sdk.flow.next(c,l,ur,W.version,N.componentsVersion,{token:b,exchangeCode:w,exchangeError:y});return h(this,wi,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if("loadForm"===d&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>n(e)))){if(!R||!_)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,o)=>{const r=document.createElement("form");r.method="POST",r.action=e,r.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(r),o(r)})(R,_,T||"",Sr)}if("redirect"===d&&(n("redirectTo")||n("deferredRedirect")))return v?"android"===x&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(v):void this.loggerWrapper.error("Did not get redirect url");if(d===dr||"webauthnGet"===d){if(!I||!k)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(r=h(this,mi,"f"))||void 0===r||r.abort(),p(this,mi,null,"f");try{e=d===dr?yield this.sdk.webauthn.helpers.create(k):yield this.sdk.webauthn.helpers.get(k)}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(c,l,ur,W.version,N.componentsVersion,{transactionId:I,response:e,failure:t});h(this,wi,"f").call(this,n)}if(d===cr&&p(this,vi,setInterval((()=>u(this,void 0,void 0,(function*(){const e=yield this.sdk.flow.next(c,l,hr,W.version,N.componentsVersion,{});h(this,wi,"f").call(this,e)}))),2e3),"f"),!f&&!$)return void this.loggerWrapper.warn("No screen was found to show");const H=$||f,J=yield this.getHtmlFilenameWithLocale(E,H),K={direction:br(+l,+t.stepId),screenState:Object.assign(Object.assign({},g),{form:Object.assign(Object.assign({},this.form),null==g?void 0:g.form),lastAuth:{loginId:D,name:this.sdk.getLastUserDisplayName()||D}}),htmlUrl:mr(i,`${H}.html`),htmlLocaleUrl:J&&mr(i,J),samlIdpUsername:U,oidcLoginHint:L},V=$r(D);jr($,O,A,U,P,L)?K.next=(e,t,n,o)=>this.sdk.flow.start(s,Object.assign({tenant:a,redirectAuth:F,oidcIdpStateId:O,samlIdpStateId:A,samlIdpUsername:U,ssoAppId:P,oidcLoginHint:L,lastAuth:V,preview:this.preview,abTestingKey:q,client:this.client},m&&{redirectUrl:m}),M,e,t,n,Object.assign(Object.assign(Object.assign(Object.assign({},this.form),o),w&&{exchangeCode:w,idpInitiated:!0}),b&&{token:b})):(n("projectId")||n("baseUrl")||n("executionId")||n("stepId"))&&(K.next=(...e)=>this.sdk.flow.next(c,l,...e)),this.stepState.update(K)}))}loadDescopeUiComponents(e){return u(this,void 0,void 0,(function*(){const t=yield _i.descopeUI;if(!t)return;const n=(e=>[...Array.from(e.querySelectorAll("*")).reduce(((e,t)=>t.tagName.startsWith("DESCOPE-")?e.add(t.tagName.toLocaleLowerCase()):e),new Set)])(e);yield Promise.all(n.map((e=>u(this,void 0,void 0,(function*(){if(!customElements.get(e))if(t[e])try{return yield t[e]()}catch(t){if("NotSupportedError"!==t.name)throw t;console.debug(`${e} is already registered`)}else this.loggerWrapper.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)})))))}))}onStepChange(e,t){var n,o;return u(this,void 0,void 0,(function*(){const{htmlUrl:r,htmlLocaleUrl:i,direction:s,next:a,screenState:l}=e,c=document.createElement("template");c.innerHTML=yield this.getPageContent(r,i);const d=c.content.cloneNode(!0),p=this.loadDescopeUiComponents(c.content);this.sdk.webauthn.helpers.isSupported()?yield h(this,gi,"m",ki).call(this,d,a):d.querySelectorAll(`descope-button[${lr}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(n=l.form)||void 0===n?void 0:n.loginId)||(null===(o=l.form)||void 0===o?void 0:o.email)||(l.form||(l.form={}),l.form.loginId=e.samlIdpUsername,l.form.email=e.samlIdpUsername),((e,t,n,o,r)=>{var i;let s=null==t?void 0:t.errorText;try{s=(null==o?void 0:o({text:null==t?void 0:t.errorText,type:null==t?void 0:t.errorType}))||(null==t?void 0:t.errorText)}catch(e){r.error("Error transforming error message",e.message)}((e,t,n="")=>{e.querySelectorAll(`[${lr}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(e,"error-message",s),((e,t)=>{e.querySelectorAll(`[${lr}="totp-link"]`).forEach((e=>{e.setAttribute("href",t)}))})(e,null===(i=null==t?void 0:t.totp)||void 0===i?void 0:i.provisionUrl),((e,t)=>{e.querySelectorAll("descope-text,descope-link").forEach((e=>{e.textContent=Tr(e.textContent,t)}))})(e,t),((e,t,n)=>{t&&Object.keys(t).forEach((o=>{e.querySelectorAll(`[name=${o}]`).forEach((e=>{const r=t[o];Object.keys(r).forEach((t=>{let o=r[t];if("string"!=typeof o)try{o=JSON.stringify(o)}catch(e){n.error(`Could not stringify value "${o}" for "${t}"`,e.message),o=""}e.setAttribute(t,o)}))}))}))})(e,n,r),((e,t)=>{e.querySelectorAll("[data-has-dynamic-attr-values]").forEach((e=>{Array.from(e.attributes).forEach((e=>{e.value=Tr(e.value,t)}))}))})(e,t)})(d,l,l.componentsConfig,this.errorTransformer,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('descope-phone-field[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(d,f);const g=()=>u(this,void 0,void 0,(function*(){var e;yield p,((e,t)=>{var n,o;const r=null===(n=customElements.get("descope-totp-image"))||void 0===n?void 0:n.cssVarList.url;t&&r&&(null===(o=null==e?void 0:e.style)||void 0===o||o.setProperty(r,`url(data:image/jpg;base64,${t})`))})(this.shadowRoot.querySelector("div"),null===(e=null==l?void 0:l.totp)||void 0===e?void 0:e.image),this.rootElement.replaceChildren(d),setTimeout((()=>((e,t)=>{_r(e,null==t?void 0:t.inputs),_r(e,null==t?void 0:t.form)})(this.rootElement,l)));const n=!t.htmlUrl;if(((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}})(this.rootElement,this.autoFocus,n),h(this,gi,"m",Ai).call(this,a),h(this,gi,"m",Ri).call(this,"page-updated",{}),this.rootElement.querySelector(`[${lr}="polling"]`)){const e=yield this.getFlowConfig(),t=yield this.getProjectConfig(),n=yield a(hr,e.version,t.componentsVersion,{});h(this,wi,"f").call(this,n)}}));s?h(this,gi,"m",Ui).call(this,g,s):g()}))}}vi=new WeakMap,mi=new WeakMap,bi=new WeakMap,wi=new WeakMap,yi=new WeakMap,gi=new WeakSet,Ii=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)}))}},ki=function(e,t){var n;return u(this,void 0,void 0,(function*(){null===(n=h(this,mi,"f"))||void 0===n||n.abort();const o=e.querySelector('*[autocomplete="webauthn"]');if(o&&(yield Pr())){const{options:e,transactionId:n}=(yield h(this,yi,"f").call(this))||{};if(e&&n){h(this,gi,"m",Ii).call(this,o),p(this,mi,new AbortController,"f");const r=yield this.getFlowConfig(),i=yield this.getProjectConfig();this.sdk.webauthn.helpers.conditional(e,h(this,mi,"f")).then((e=>u(this,void 0,void 0,(function*(){const s=yield t(o.id,r.version,i.componentsVersion,{transactionId:n,response:e});h(this,wi,"f").call(this,s)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)}))}}}))},ji=function(){return Array.from(this.shadowRoot.querySelectorAll("*[name]")).every((e=>{var t,n;return null===(t=e.reportValidity)||void 0===t||t.call(e),null===(n=e.checkValidity)||void 0===n?void 0:n.call(e)}))},Si=function(){return u(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${tr}])`));return(yield Promise.all(e.map((e=>u(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})),{})}))},Ci=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},xi=function(e={}){var t,n;const o=Cr(e,["externalId","email","phone"]),r=Cr(e,["newPassword","password"]);if(o&&r)try{const e=new globalThis.PasswordCredential({id:o,password:r});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)}},Oi=function(e,t){return u(this,void 0,void 0,(function*(){if("true"===e.getAttribute("formnovalidate")||h(this,gi,"m",ji).call(this)){const o=null==e?void 0:e.getAttribute("id");h(this,gi,"m",Ci).call(this,e);const r=yield h(this,gi,"m",Si).call(this),i=(n=e,Array.from((null==n?void 0:n.attributes)||[]).reduce(((e,t)=>{var n;const o=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return o?Object.assign(e,{[o]:t.value}):e}),{})),s=this.getComponentsContext(),a=Object.assign(Object.assign(Object.assign(Object.assign({},s),i),r),{origin:window.location.origin}),l=yield this.getFlowConfig(),c=yield this.getProjectConfig(),d=yield t(o,l.version,c.componentsVersion,a);h(this,wi,"f").call(this,d),h(this,gi,"m",xi).call(this,r)}var n}))},Ei=function(e){this.rootElement.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))&&h(this,gi,"m",Oi).call(this,t,e)}))}))},Ai=function(e){this.rootElement.querySelectorAll("descope-button:not([data-exclude-next])").forEach((t=>{t.onclick=()=>{h(this,gi,"m",Oi).call(this,t,e)}})),h(this,gi,"m",Ei).call(this,e)},Ui=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===pr.forward?"slide-forward":"slide-backward";Array.from(this.rootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(n)})),this.rootElement.classList.add("fade-out")},Ri=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.define("descope-wc",Ti);var Pi=Object.freeze({__proto__:null,default:Ti});const Li=(e,t,n,o={})=>{var r,i,s,a;return[Math.min(Math.max(t,("all"===o.left?e.offsetWidth:null!==(r=o.left)&&void 0!==r?r:0)-e.offsetWidth),window.innerWidth-("all"===o.right?e.offsetWidth:null!==(i=o.right)&&void 0!==i?i:0)),Math.min(Math.max(n,("all"===o.top?e.offsetHeight:null!==(s=o.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===o.bottom?e.offsetHeight:null!==(a=o.bottom)&&void 0!==a?a:0))]};var $i,Mi,qi,Di,Wi,Ni,Fi,Hi,Ji,Ki;const Vi=document.createElement("template");Vi.innerHTML=`\n<style>\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</style>\n\n<div style="top:32px; left:${window.innerWidth-300-32}px;" 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 zi extends HTMLElement{constructor(){super(),$i.add(this),Mi.set(this,new Rr({messages:[]})),qi.set(this,void 0),Di.set(this,void 0),Wi.set(this,void 0),Ni.set(this,{resize:h(this,$i,"m",Ki).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Vi.content.cloneNode(!0)),p(this,qi,this.shadowRoot.querySelector(".debugger"),"f"),p(this,Di,h(this,qi,"f").querySelector(".content"),"f"),p(this,Wi,h(this,qi,"f").querySelector(".header"),"f")}updateData(e){h(this,Mi,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let o=0,r=0,i=0,s=0;function a(t){t.preventDefault(),o=i-t.clientX,r=s-t.clientY,i=t.clientX,s=t.clientY;const[a,l]=Li(e,e.offsetLeft-o,e.offsetTop-r,n);e.style.top=`${l}px`,e.style.left=`${a}px`}function l(){document.onmouseup=null,document.onmousemove=null}function c(e){e.preventDefault(),i=e.clientX,s=e.clientY,document.onmouseup=l,document.onmousemove=a}t?t.onmousedown=c:e.onmousedown=c})(h(this,qi,"f"),h(this,Wi,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",h(this,Ni,"f").resize),(e=h(this,qi,"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},h(this,qi,"f").onresize=h(this,$i,"m",Ji).bind(this),h(this,Mi,"f").subscribe(h(this,$i,"m",Fi).bind(this))}disconnectedCallback(){h(this,Mi,"f").unsubscribeAll(),window.removeEventListener("resize",h(this,Ni,"f").resize)}}Mi=new WeakMap,qi=new WeakMap,Di=new WeakMap,Wi=new WeakMap,Ni=new WeakMap,$i=new WeakSet,Fi=function(e){h(this,$i,"m",Hi).call(this,e),h(this,$i,"m",Ji).call(this)},Hi=function(e){h(this,Di,"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("")},Ji=function(){h(this,Di,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,o=t.clientHeight>20;n||o?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},Ki=function(){const[e,t]=Li(h(this,qi,"f"),Number.parseInt(h(this,qi,"f").style.left,10),Number.parseInt(h(this,qi,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});h(this,qi,"f").style.top=`${t}px`,h(this,qi,"f").style.left=`${e}px`},customElements.define("descope-debugger",zi);var Bi=Object.freeze({__proto__:null,default:zi});e.AuthProvider=({projectId:e,baseUrl:n="",sessionTokenViaCookie:s=!1,children:l})=>{const[c,d]=t.useState(),[u,h]=t.useState(),[p,f]=t.useState(!1),[g,v]=t.useState(!1),m=(({projectId:e,baseUrl:n,sessionTokenViaCookie:o})=>t.useMemo((()=>{if(e)return To({projectId:e,baseUrl:n,sessionTokenViaCookie:o,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[e,n,o]))({projectId:e,baseUrl:n,sessionTokenViaCookie:s});t.useEffect((()=>{if(m){const e=m.onSessionTokenChange(h),t=m.onUserChange(d);return()=>{e(),t()}}}),[m]);const b=t.useRef(!1),w=t.useCallback((()=>{b.current||(b.current=!0,v(!0),i(m?.refresh)().then((()=>{v(!1)})))}),[m]),y=t.useCallback((()=>{f(!0),i(m.me)().then((()=>{f(!1)}))}),[m]),I=t.useMemo((()=>({fetchUser:y,user:c,isUserLoading:p,fetchSession:w,session:u,isSessionLoading:g,isSessionFetched:b.current,projectId:e,baseUrl:n,setUser:d,setSession:h,sdk:m})),[y,c,p,w,u,g,b.current,e,n,d,h,m]);return o.default.createElement(r.Provider,{value:I},l)},e.Descope=Do,e.SignInFlow=e=>o.default.createElement(Do,{...e,flowId:"sign-in"}),e.SignUpFlow=e=>o.default.createElement(Do,{...e,flowId:"sign-up"}),e.SignUpOrInFlow=e=>o.default.createElement(Do,{...e,flowId:"sign-up-or-in"}),e.getJwtPermissions=$o,e.getJwtRoles=Mo,e.getRefreshToken=Lo,e.getSessionToken=Po,e.refresh=(e=Lo())=>_o?.refresh(e),e.useDescope=()=>{const{sdk:e}=Wo();return t.useMemo((()=>e||new Proxy(To({projectId:"dummy"}),Fo)),[e])},e.useSession=()=>{const{session:e,isSessionLoading:n,fetchSession:o,isSessionFetched:r}=Wo(),i=t.useRef(n);return t.useMemo((()=>{i.current=n}),[n]),t.useMemo((()=>{r||(i.current=!0)}),[r]),t.useEffect((()=>{e||n||o()}),[o]),{isSessionLoading:i.current,sessionToken:e,isAuthenticated:!!e}},e.useUser=()=>{const{user:e,fetchUser:n,isUserLoading:o,session:r}=Wo(),[i,s]=t.useState(!1),a=t.useRef(o),l=t.useMemo((()=>!e&&!o&&r&&!i),[n,r,i]);return t.useMemo((()=>{a.current=o}),[o]),t.useMemo((()=>{l&&(a.current=!0)}),[l]),t.useEffect((()=>{l&&(s(!0),n())}),[l]),{isUserLoading:a.current,user:e}},Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
3
3
|
//# sourceMappingURL=index.umd.js.map
|