@descope/react-sdk 2.0.3 → 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/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import e,{useMemo as r,useState as t,useEffect as o,useRef as n,useCallback as s,lazy as i,useImperativeHandle as c,Suspense as a,useContext as u}from"react";import d from"@descope/web-js-sdk";const l=e.createContext(void 0),f=e=>(...r)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...r)},p=e=>(...r)=>{let t;try{t=e(...r)}catch(e){console.error(e)}return t},h={"x-descope-sdk-name":"react","x-descope-sdk-version":"2.0.3"},m="undefined"!=typeof window;let k;const g=e=>{const r=d({...e,persistTokens:m,autoRefresh:m});return k=r,r};k=g({projectId:"temp pid"});const w=()=>m?k?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),y=()=>m?k?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=p(((e=w(),r)=>k?.getJwtPermissions(e,r))),I=p(((e=w(),r)=>k?.getJwtRoles(e,r))),U=(e=y())=>k?.refresh(e);const E=({projectId:i,baseUrl:c="",sessionTokenViaCookie:a=!1,children:u})=>{const[d,p]=t(),[m,k]=t(),[w,y]=t(!1),[b,I]=t(!1),U=(({projectId:e,baseUrl:t,sessionTokenViaCookie:o})=>r((()=>{if(e)return g({projectId:e,baseUrl:t,sessionTokenViaCookie:o,baseHeaders:h,persistToken:!0,autoRefresh:!0})}),[e,t,o]))({projectId:i,baseUrl:c,sessionTokenViaCookie:a});o((()=>{if(U){const e=U.onSessionTokenChange(k),r=U.onUserChange(p);return()=>{e(),r()}}}),[U]);const E=n(!1),S=s((()=>{E.current||(E.current=!0,I(!0),f(U?.refresh)().then((()=>{I(!1)})))}),[U]),j=s((()=>{y(!0),f(U.me)().then((()=>{y(!1)}))}),[U]),v=r((()=>({fetchUser:j,user:d,isUserLoading:w,fetchSession:S,session:m,isSessionLoading:b,isSessionFetched:E.current,projectId:i,baseUrl:c,setUser:p,setSession:k,sdk:U})),[j,d,w,S,m,b,E.current,i,c,p,k,U]);return e.createElement(l.Provider,{value:v},u)},S=i((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:h},{default:({projectId:r,flowId:t,baseUrl:o,innerRef:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,redirectUrl:d,autoFocus:l})=>e.createElement("descope-wc",{"project-id":r,"flow-id":t,"base-url":o,ref:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,"redirect-url":d,"auto-focus":l})}))),j=e.forwardRef((({flowId:r,onSuccess:n,onError:i,logger:u,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g,errorTransformer:w},y)=>{const[b,I]=t(null);c(y,(()=>b));const{projectId:U,baseUrl:E,sdk:j}=e.useContext(l),v=s((async e=>{await j.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);return o((()=>{const e=b;return e?.addEventListener("success",v),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",v)}}),[b,i,v]),o((()=>{b&&(b.errorTransformer=w)}),[b,w]),o((()=>{b&&u&&(b.logger=u)}),[b,u]),e.createElement("form",null,e.createElement(a,{fallback:null},e.createElement(S,{projectId:U,flowId:r,baseUrl:E,innerRef:I,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g})))})),v=r=>e.createElement(j,{...r,flowId:"sign-in"}),T=r=>e.createElement(j,{...r,flowId:"sign-up"}),C=r=>e.createElement(j,{...r,flowId:"sign-up-or-in"});var R=()=>{const e=u(l);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const L=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,x={get(e,r){if("object"==typeof e[r]&&null!==e[r])return new Proxy(e[r],x);if("function"==typeof e[r])return()=>{throw Error(L("function"))};throw Error(L("attribute"))}},P=()=>{const{sdk:e}=R();return r((()=>e||new Proxy(g({projectId:"dummy"}),x)),[e])},F=()=>{const{session:e,isSessionLoading:t,fetchSession:s,isSessionFetched:i}=R(),c=n(t);return r((()=>{c.current=t}),[t]),r((()=>{i||(c.current=!0)}),[i]),o((()=>{e||t||s()}),[s]),{isSessionLoading:c.current,sessionToken:e,isAuthenticated:!!e}},A=()=>{const{user:e,fetchUser:s,isUserLoading:i,session:c}=R(),[a,u]=t(!1),d=n(i),l=r((()=>!e&&!i&&c&&!a),[s,c,a]);return r((()=>{d.current=i}),[i]),r((()=>{l&&(d.current=!0)}),[l]),o((()=>{l&&(u(!0),s())}),[l]),{isUserLoading:d.current,user:e}};export{E as AuthProvider,j as Descope,v as SignInFlow,T as SignUpFlow,C as SignUpOrInFlow,b as getJwtPermissions,I as getJwtRoles,y as getRefreshToken,w as getSessionToken,U as refresh,P as useDescope,F as useSession,A as useUser};
1
+ import e,{useMemo as r,useState as t,useEffect as o,useRef as n,useCallback as s,lazy as i,useImperativeHandle as c,Suspense as a,useContext as u}from"react";import d from"@descope/web-js-sdk";const l=e.createContext(void 0),f=e=>(...r)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...r)},p=e=>(...r)=>{let t;try{t=e(...r)}catch(e){console.error(e)}return t},m={"x-descope-sdk-name":"react","x-descope-sdk-version":"2.0.5"},h="undefined"!=typeof window;let k;const g=e=>{const r=d({...e,persistTokens:h,autoRefresh:h});return k=r,r};k=g({projectId:"temp pid"});const w=()=>h?k?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),y=()=>h?k?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=p(((e=w(),r)=>k?.getJwtPermissions(e,r))),I=p(((e=w(),r)=>k?.getJwtRoles(e,r))),S=(e=y())=>k?.refresh(e);const U=({projectId:i,baseUrl:c="",sessionTokenViaCookie:a=!1,children:u})=>{const[d,p]=t(),[h,k]=t(),[w,y]=t(!1),[b,I]=t(!1),S=(({projectId:e,baseUrl:t,sessionTokenViaCookie:o})=>r((()=>{if(e)return g({projectId:e,baseUrl:t,sessionTokenViaCookie:o,baseHeaders:m,persistToken:!0,autoRefresh:!0})}),[e,t,o]))({projectId:i,baseUrl:c,sessionTokenViaCookie:a});o((()=>{if(S){const e=S.onSessionTokenChange(k),r=S.onUserChange(p);return()=>{e(),r()}}}),[S]);const U=n(!1),E=s((()=>{U.current||(U.current=!0,I(!0),f(S?.refresh)().then((()=>{I(!1)})))}),[S]),j=s((()=>{y(!0),f(S.me)().then((()=>{y(!1)}))}),[S]),v=r((()=>({fetchUser:j,user:d,isUserLoading:w,fetchSession:E,session:h,isSessionLoading:b,isSessionFetched:U.current,projectId:i,baseUrl:c,setUser:p,setSession:k,sdk:S})),[j,d,w,E,h,b,U.current,i,c,p,k,S]);return e.createElement(l.Provider,{value:v},u)},E=i((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:m},{default:({projectId:r,flowId:t,baseUrl:o,innerRef:n,tenant:s,theme:i,locale:c,debug:a,redirectUrl:u,client:d,form:l,autoFocus:f})=>e.createElement("descope-wc",{"project-id":r,"flow-id":t,"base-url":o,ref:n,tenant:s,theme:i,locale:c,debug:a,client:d,form:l,"redirect-url":u,"auto-focus":f})}))),j=e.forwardRef((({flowId:n,onSuccess:i,onError:u,logger:d,tenant:f,theme:p,locale:m,debug:h,client:k,form:g,telemetryKey:w,redirectUrl:y,autoFocus:b,errorTransformer:I},S)=>{const[U,j]=t(null);c(S,(()=>U));const{projectId:v,baseUrl:T,sdk:C}=e.useContext(l),R=s((async e=>{await C.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),i&&i(e)}),[i]);o((()=>{const e=U;return e?.addEventListener("success",R),u&&e?.addEventListener("error",u),()=>{u&&e?.removeEventListener("error",u),e?.removeEventListener("success",R)}}),[U,u,R]),o((()=>{U&&(U.errorTransformer=I)}),[U,I]),o((()=>{U&&d&&(U.logger=d)}),[U,d]);const{form:L,client:x}=r((()=>({form:JSON.stringify(g||{}),client:JSON.stringify(k||{})})),[g,k]);return e.createElement("form",null,e.createElement(a,{fallback:null},e.createElement(E,{projectId:v,flowId:n,baseUrl:T,innerRef:j,tenant:f,theme:p,locale:m,debug:h,form:L,client:x,telemetryKey:w,redirectUrl:y,autoFocus:b})))})),v=r=>e.createElement(j,{...r,flowId:"sign-in"}),T=r=>e.createElement(j,{...r,flowId:"sign-up"}),C=r=>e.createElement(j,{...r,flowId:"sign-up-or-in"});var R=()=>{const e=u(l);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const L=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,x={get(e,r){if("object"==typeof e[r]&&null!==e[r])return new Proxy(e[r],x);if("function"==typeof e[r])return()=>{throw Error(L("function"))};throw Error(L("attribute"))}},P=()=>{const{sdk:e}=R();return r((()=>e||new Proxy(g({projectId:"dummy"}),x)),[e])},F=()=>{const{session:e,isSessionLoading:t,fetchSession:s,isSessionFetched:i}=R(),c=n(t);return r((()=>{c.current=t}),[t]),r((()=>{i||(c.current=!0)}),[i]),o((()=>{e||t||s()}),[s]),{isSessionLoading:c.current,sessionToken:e,isAuthenticated:!!e}},J=()=>{const{user:e,fetchUser:s,isUserLoading:i,session:c}=R(),[a,u]=t(!1),d=n(i),l=r((()=>!e&&!i&&c&&!a),[s,c,a]);return r((()=>{d.current=i}),[i]),r((()=>{l&&(d.current=!0)}),[l]),o((()=>{l&&(u(!0),s())}),[l]),{isUserLoading:d.current,user:e}};export{U as AuthProvider,j as Descope,v as SignInFlow,T as SignUpFlow,C as SignUpOrInFlow,b as getJwtPermissions,I as getJwtRoles,y as getRefreshToken,w as getSessionToken,S as refresh,P as useDescope,F as useSession,J as useUser};
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/hooks/Context.ts","../src/utils.ts","../src/constants.ts","../src/sdk.ts","../src/components/AuthProvider/AuthProvider.tsx","../src/components/AuthProvider/useSdk.ts","../src/components/Descope.tsx","../src/components/DefaultFlows.tsx","../src/hooks/useContext.ts","../src/hooks/useDescope.ts","../src/hooks/useSession.ts","../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, {\n\tFC,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState\n} from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl = '',\n\tsessionTokenViaCookie = false,\n\tchildren = undefined\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst isSessionFetched = useRef(false);\n\n\tconst fetchSession = useCallback(() => {\n\t\t// We want that the session will fetched only once\n\t\tif (isSessionFetched.current) return;\n\t\tisSessionFetched.current = true;\n\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched: isSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tlocale={locale}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\tlogger,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus,\n\t\t\terrorTransformer\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, sdk } = React.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef) {\n\t\t\t\tinnerRef.errorTransformer = errorTransformer;\n\t\t\t}\n\t\t}, [innerRef, errorTransformer]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef && logger) {\n\t\t\t\tinnerRef.logger = logger;\n\t\t\t}\n\t\t}, [innerRef, logger]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tlocale={locale}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nexport default Descope;\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { Sdk } from '../types';\nimport useContext from './useContext';\nimport createSdk from '../sdk';\n\nconst generateErrorMsg = (entryType: string) =>\n\t`You can only use this ${entryType} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`;\n\n// handler which throw an error for every SDK function\nconst proxyThrowHandler = {\n\t// eslint-disable-next-line prefer-arrow/prefer-arrow-functions\n\tget(target: Record<string, any>, key: string) {\n\t\tif (typeof target[key] === 'object' && target[key] !== null) {\n\t\t\treturn new Proxy(target[key], proxyThrowHandler);\n\t\t}\n\n\t\tif (typeof target[key] === 'function') {\n\t\t\treturn () => {\n\t\t\t\tthrow Error(generateErrorMsg('function'));\n\t\t\t};\n\t\t}\n\n\t\tthrow Error(generateErrorMsg('attribute'));\n\t}\n};\n\nconst useDescope = (): Sdk => {\n\tconst { sdk } = useContext();\n\n\treturn useMemo(() => {\n\t\tif (!sdk) {\n\t\t\t// In case the SDK is not initialized, we want to throw an error when the SDK functions are called\n\t\t\treturn new Proxy(\n\t\t\t\tcreateSdk({ projectId: 'dummy' }),\n\t\t\t\tproxyThrowHandler\n\t\t\t) as Sdk;\n\t\t}\n\n\t\treturn sdk;\n\t}, [sdk]);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession, isSessionFetched } =\n\t\tuseContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!isSessionFetched) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [isSessionFetched]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","refresh","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","isSessionFetched","useRef","fetchSession","useCallback","current","then","fetchUser","me","value","createElement","Provider","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","locale","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","logger","errorTransformer","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","httpClient","hooks","afterRequest","Response","JSON","stringify","detail","ele","addEventListener","removeEventListener","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","generateErrorMsg","entryType","proxyThrowHandler","get","target","key","Proxy","useDescope","useSession","isLoading","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"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"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/hooks/Context.ts","../src/utils.ts","../src/constants.ts","../src/sdk.ts","../src/components/AuthProvider/AuthProvider.tsx","../src/components/AuthProvider/useSdk.ts","../src/components/Descope.tsx","../src/components/DefaultFlows.tsx","../src/hooks/useContext.ts","../src/hooks/useDescope.ts","../src/hooks/useSession.ts","../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, {\n\tFC,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState\n} from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl = '',\n\tsessionTokenViaCookie = false,\n\tchildren = undefined\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst isSessionFetched = useRef(false);\n\n\tconst fetchSession = useCallback(() => {\n\t\t// We want that the session will fetched only once\n\t\tif (isSessionFetched.current) return;\n\t\tisSessionFetched.current = true;\n\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched: isSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseMemo,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\tredirectUrl,\n\t\t\tclient,\n\t\t\tform,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tlocale={locale}\n\t\t\t\tdebug={debug}\n\t\t\t\tclient={client}\n\t\t\t\tform={form}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\tlogger,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\tclient,\n\t\t\tform,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus,\n\t\t\terrorTransformer\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, sdk } = React.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef) {\n\t\t\t\tinnerRef.errorTransformer = errorTransformer;\n\t\t\t}\n\t\t}, [innerRef, errorTransformer]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef && logger) {\n\t\t\t\tinnerRef.logger = logger;\n\t\t\t}\n\t\t}, [innerRef, logger]);\n\n\t\tconst { form: stringifiedForm, client: stringifiedClient } = useMemo(\n\t\t\t() => ({\n\t\t\t\tform: JSON.stringify(form || {}),\n\t\t\t\tclient: JSON.stringify(client || {})\n\t\t\t}),\n\t\t\t[form, client]\n\t\t);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tlocale={locale}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\tform={stringifiedForm}\n\t\t\t\t\t\tclient={stringifiedClient}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nexport default Descope;\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { Sdk } from '../types';\nimport useContext from './useContext';\nimport createSdk from '../sdk';\n\nconst generateErrorMsg = (entryType: string) =>\n\t`You can only use this ${entryType} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`;\n\n// handler which throw an error for every SDK function\nconst proxyThrowHandler = {\n\t// eslint-disable-next-line prefer-arrow/prefer-arrow-functions\n\tget(target: Record<string, any>, key: string) {\n\t\tif (typeof target[key] === 'object' && target[key] !== null) {\n\t\t\treturn new Proxy(target[key], proxyThrowHandler);\n\t\t}\n\n\t\tif (typeof target[key] === 'function') {\n\t\t\treturn () => {\n\t\t\t\tthrow Error(generateErrorMsg('function'));\n\t\t\t};\n\t\t}\n\n\t\tthrow Error(generateErrorMsg('attribute'));\n\t}\n};\n\nconst useDescope = (): Sdk => {\n\tconst { sdk } = useContext();\n\n\treturn useMemo(() => {\n\t\tif (!sdk) {\n\t\t\t// In case the SDK is not initialized, we want to throw an error when the SDK functions are called\n\t\t\treturn new Proxy(\n\t\t\t\tcreateSdk({ projectId: 'dummy' }),\n\t\t\t\tproxyThrowHandler\n\t\t\t) as Sdk;\n\t\t}\n\n\t\treturn sdk;\n\t}, [sdk]);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession, isSessionFetched } =\n\t\tuseContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!isSessionFetched) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [isSessionFetched]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","refresh","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","isSessionFetched","useRef","fetchSession","useCallback","current","then","fetchUser","me","value","createElement","Provider","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","locale","debug","redirectUrl","client","form","autoFocus","ref","Descope","forwardRef","onSuccess","onError","logger","telemetryKey","errorTransformer","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","httpClient","hooks","afterRequest","Response","JSON","stringify","detail","ele","addEventListener","removeEventListener","stringifiedForm","stringifiedClient","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","generateErrorMsg","entryType","proxyThrowHandler","get","target","key","Proxy","useDescope","useSession","isLoading","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"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"}
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.3"},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__"],$=(_=/[^.]+$/.exec(M&&M.keys&&M.keys.IE_PROTO||""))?"Symbol(src)_1."+_:"",D=P.toString,W=L.hasOwnProperty,q=L.toString,F=RegExp("^"+D.call(W).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),N=R.Symbol,K=T.splice,J=te(R,"Map"),H=te(Object,"create"),z=N?N.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)?F: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",_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"},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",Fe="/v1/auth/password/replace",Ne="/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.1.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 _t=Object.assign(Object.assign({},Ut),Rt);var Tt;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Tt||(Tt={}));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,_t.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:Mt(((t,n)=>ut(e.post(dt(xe,_t.email),{loginId:t,URI:n})))),signUp:Mt(((t,n,o)=>ut(e.post(dt(ke,_t.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")),Ft=jt(xt("executionId"),xt("stepId"),xt("interactionId")),Nt=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:Ft(((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(_t).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(_t).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(_t).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(_t).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(_t).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(_t).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(_t).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(_e,{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(Fe,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>ut(e.get(Ne))}),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(Te.start,{user:{loginId:t,name:o},origin:n})))),finish:On(((t,n)=>ut(e.post(Te.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,_n=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:Nt(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 Tn=(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(_n,{DeliveryMethods:_t});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(Nn)})).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(Fn)}function Fn(){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 Nn(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 Tn(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.7.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=Tn(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=Tn(n,["flow.start"],uo);return o=Tn(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=Tn(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 _o=()=>l?Uo?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),To=()=>l?Uo?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),Po=s(((e=_o(),t)=>Uo?.getJwtPermissions(e,t))),Lo=s(((e=_o(),t)=>Uo?.getJwtRoles(e,t)));const Mo=t.lazy((async()=>((await Promise.resolve().then((function(){return ji}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:n,innerRef:r,tenant:i,theme:s,locale:a,debug:l,telemetryKey:c,redirectUrl:d,autoFocus:u})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":n,ref:r,tenant:i,theme:s,locale:a,debug:l,telemetryKey:c,"redirect-url":d,"auto-focus":u})}))),$o=o.default.forwardRef((({flowId:e,onSuccess:n,onError:i,logger:s,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p,errorTransformer:f},g)=>{const[v,m]=t.useState(null);t.useImperativeHandle(g,(()=>v));const{projectId:b,baseUrl:w,sdk:y}=o.default.useContext(r),I=t.useCallback((async e=>{await y.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);return t.useEffect((()=>{const e=v;return e?.addEventListener("success",I),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",I)}}),[v,i,I]),t.useEffect((()=>{v&&(v.errorTransformer=f)}),[v,f]),t.useEffect((()=>{v&&s&&(v.logger=s)}),[v,s]),o.default.createElement("form",null,o.default.createElement(t.Suspense,{fallback:null},o.default.createElement(Mo,{projectId:b,flowId:e,baseUrl:w,innerRef:m,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p})))}));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"))}},Fo="undefined"!=typeof localStorage,No=Fo&&localStorage.getItem("base.content.url")||"https://static.descope.com/pages",Ko=Fo&&localStorage.getItem("base.ui.components.url")||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Jo="descope-login-flow",Ho="code",zo="ra-challenge",Vo="ra-callback",Bo="ra-initiator",Go="data-exclude-field",Yo="dls_last_auth",Zo="state_id",Xo="saml_idp_state_id",Qo="saml_idp_username",er="sso_app_id",tr="data-type",nr="poll",or="webauthnCreate",rr="config.json",ir="submit",sr="polling";var ar;function lr(e){return new URLSearchParams(window.location.search).get(e)}function cr(e){if(window.history.replaceState&&lr(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 dr(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 ur(e,t,n="v2-beta"){const o=new URL(No);return o.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(o.pathname,e,n,t),o.toString()}function hr(e,t){if(!Number.isNaN(e)&&!Number.isNaN(t))return e>t?ar.forward:e<t?ar.backward:void 0}!function(e){e.backward="backward",e.forward="forward"}(ar||(ar={}));const pr=()=>{const[e="",t=""]=(lr(Jo)||"").split("_");return{executionId:e,stepId:t}};function fr(){cr(Jo)}const gr=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),vr=()=>{const{executionId:e,stepId:t}=pr();(e||t)&&fr();const n=lr("t")||void 0;n&&cr("t");const o=lr(Ho)||void 0;o&&cr(Ho);const r=lr("err")||void 0;r&&cr("err");const{redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a}={redirectAuthCodeChallenge:lr(zo),redirectAuthCallbackUrl:lr(Vo),redirectAuthInitiator:lr(Bo)};(i||s||a)&&(cr(zo),cr(Vo),cr(Bo));const l=lr(Zo);l&&cr(Zo);const c=lr(Xo);c&&cr(Xo);const d=lr(Qo);c&&cr(Qo);const u=lr(er);return u&&cr(er),{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}},mr=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}},br=(e,t,n,o,r)=>e&&!t&&e&&!n&&!o&&e&&!r,wr=e=>null==e?void 0:e.submit();var yr,Ir,kr,Sr;function jr(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(!jr(i,s))return!1}else if(i!==s)return!1}return!0}class xr{constructor(e={},{updateOnlyOnChange:t=!0}={}){yr.set(this,void 0),Ir.set(this,{}),kr.set(this,0),Sr.set(this,!1),this.update=e=>{const t="function"==typeof e?e(h(this,yr,"f")):e,n=Object.assign(Object.assign({},h(this,yr,"f")),t);if(!h(this,Sr,"f")||!jr(h(this,yr,"f"),n)){const e=h(this,yr,"f");p(this,yr,n,"f"),Object.freeze(h(this,yr,"f")),setTimeout((()=>{Object.values(h(this,Ir,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},p(this,yr,e,"f"),p(this,Sr,t,"f")}get current(){return Object.assign({},h(this,yr,"f"))}subscribe(e){return p(this,kr,h(this,kr,"f")+1,"f"),h(this,Ir,"f")[h(this,kr,"f")]=e,h(this,kr,"f").toString()}unsubscribe(e){const t=!!h(this,Ir,"f")[e];return t&&delete h(this,Ir,"f")[e],t}unsubscribeAll(){return p(this,Ir,{},"f"),!0}}yr=new WeakMap,Ir=new WeakMap,kr=new WeakMap,Sr=new WeakMap;const Cr=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${Go}])`)).forEach((e=>{e.setAttribute("value",n)}))}))},Or=mr((()=>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}})))),Er={"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 Ar(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(Yo)))}catch(e){}return t}const Ur="dls_ab_testing_id",Rr=document.createElement("template");var _r,Tr,Pr,Lr,Mr,$r,Dr,Wr,qr,Fr,Nr,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;Rr.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 ki 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(),_r.add(this),this.logger=console,Tr.set(this,!1),this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),h(this,_r,"m",ri).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)}},Pr.set(this,new xr({deferredRedirect:!1})),Lr.set(this,new xr),Mr.set(this,{}),this.getComponentsContext=()=>h(this,Mr,"f"),this.nextRequestStatus=new xr({isLoading:!1}),$r.set(this,void 0),Dr.set(this,{popstate:h(this,_r,"m",Jr).bind(this),visibilitychange:h(this,_r,"m",Hr).bind(this),componentsContext:h(this,_r,"m",ei).bind(this)}),Wr.set(this,void 0),Yr.set(this,mr((()=>u(this,void 0,void 0,(function*(){const e=ur(this.projectId,rr);try{const{body:t,headers:n}=yield dr(e,"json");return{projectConfig:t,executionContext:{geo:n["x-geo"]}}}catch(e){return{isMissingConfig:!0}}}))))),p(this,Wr,e,"f"),h(this,_r,"m",qr).call(this)}get projectId(){return this.getAttribute("project-id")}get flowId(){return this.getAttribute("flow-id")}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,Yr,"f").call(this);return e}))}getProjectConfig(){return u(this,void 0,void 0,(function*(){const{projectConfig:e}=yield h(this,Yr,"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,Lr,"f").subscribe(h(this,_r,"m",oi).bind(this)),h(this,Lr,"f").update({isDebug:this.debug}),h(this,_r,"m",Fr).call(this))return void h(this,_r,"m",Nr).call(this);if(h(this,_r,"m",Kr).call(this),yield h(this,_r,"m",Br).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,Yr,"f").call(this)).isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");yield h(this,_r,"m",si).call(this),yield h(this,_r,"m",Xr).call(this),h(this,_r,"m",Zr).call(this),h(this,_r,"m",ii).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}=vr();window.addEventListener("popstate",h(this,Dr,"f").popstate),window.addEventListener("components-context",h(this,Dr,"f").componentsContext),window.addEventListener("visibilitychange",h(this,Dr,"f").visibilitychange),h(this,Pr,"f").subscribe(h(this,_r,"m",Vr).bind(this)),h(this,Pr,"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,Tr,!0,"f")}}))}disconnectedCallback(){h(this,Pr,"f").unsubscribeAll(),h(this,Lr,"f").unsubscribeAll(),h(this,_r,"m",ni).call(this),window.removeEventListener("popstate",h(this,Dr,"f").popstate),window.removeEventListener("visibilitychange",h(this,Dr,"f").visibilitychange),window.removeEventListener("components-context",h(this,Dr,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&h(this,Tr,"f")&&t!==n&&ki.observedAttributes.includes(e)){h(this,_r,"m",Kr).call(this);const o=null===t;h(this,Pr,"f").update((({stepId:t,executionId:r})=>{let i=t,s=r;return o||(s=null,i=null,fr()),{[gr(e)]:n,stepId:i,executionId:s}})),h(this,Lr,"f").update({isDebug:this.debug})}}}Tr=new WeakMap,Pr=new WeakMap,Lr=new WeakMap,Mr=new WeakMap,$r=new WeakMap,Dr=new WeakMap,Wr=new WeakMap,Yr=new WeakMap,_r=new WeakSet,qr=function(){this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Rr.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#wc-root")},Fr=function(){return!this.shadowRoot.host.closest("form")&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},Nr=function(){const e=this.shadowRoot.host,t=document.createElement("form");e.parentElement.appendChild(t),t.appendChild(e)},Kr=function(){const e=["base-url","tenant","theme","locale","debug","redirect-url","auto-focus","preview","storage-prefix"];if(ki.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[gr(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')},Jr=function(){const{stepId:e,executionId:t}=pr();h(this,Pr,"f").update({stepId:e,executionId:t})},Hr=function(){document.hidden||setTimeout((()=>{h(this,Pr,"f").update({deferredRedirect:!1})}),300)},zr=function(e,t){this.sdk=Ao(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix},ki.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})}}))}))},Vr=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,_r,"m",zr).call(this,t,o)}h(this,Wr,"f").call(this,e)}))},Br=function(){return u(this,void 0,void 0,(function*(){return(yield h(this,Yr,"f").call(this)).isMissingConfig&&(yield h(this,_r,"m",Gr).call(this))}))},Gr=function(){return u(this,void 0,void 0,(function*(){const e=ur(this.projectId,rr,"v2-alpha");try{return yield dr(e,"json"),!0}catch(e){return!1}}))},Zr=function(){var e,t;return u(this,void 0,void 0,(function*(){const{projectConfig:n}=yield h(this,Yr,"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)))}))},Xr=function(){return u(this,void 0,void 0,(function*(){yield h(this,_r,"m",Qr).call(this),yield h(this,_r,"m",ti).call(this)}))},Qr=function(){var e,t,n,o;return u(this,void 0,void 0,(function*(){const r=document.createElement("style"),i=ur(this.projectId,"theme.json");try{const{body:s}=yield dr(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 this.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)}))},ei=function(e){p(this,Mr,Object.assign(Object.assign({},e.detail),h(this,Mr,"f")),"f")},ti=function(){return u(this,void 0,void 0,(function*(){this.rootElement.setAttribute("data-theme",this.theme);const e=yield this.descopeUI;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)}))},ni=function(){var e;null===(e=h(this,$r,"f"))||void 0===e||e.remove(),p(this,$r,null,"f")},oi=function({isDebug:e}){return u(this,void 0,void 0,(function*(){e?(p(this,$r,document.createElement("descope-debugger"),"f"),Object.assign(h(this,$r,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Di})),document.body.appendChild(h(this,$r,"f"))):h(this,_r,"m",ni).call(this)}))},ri=function(e,t){var n;e&&this.debug&&(null===(n=h(this,$r,"f"))||void 0===n||n.updateData({title:e,description:t}))},ii=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()}},si=function(){var e,t;return u(this,void 0,void 0,(function*(){const n="load-descope-ui";if(globalThis.DescopeUI)return void(this.descopeUI=Promise.resolve(globalThis.DescopeUI));const o=document.getElementById(n),r=o||document.createElement("script");if(o)this.loggerWrapper.info("DescopeUI loading script is already exist, probably multiple flows are running on the same page");else{r.id=n;let o=null===(t=null===(e=yield h(this,Yr,"f").call(this))||void 0===e?void 0:e.projectConfig)||void 0===t?void 0:t.componentsVersion;o||(this.logger.error("Did not get components version, using latest version"),o="latest"),r.src=Ko.replace("<version>",o),document.body.append(r)}this.descopeUI=new Promise((e=>{const t=()=>{this.loggerWrapper.error("Cannot load DescopeUI",`Make sure this URL is valid and return the correct script: "${r.src}"`),e(void 0)};r.addEventListener("load",(()=>{globalThis.DescopeUI||t(),e(globalThis.DescopeUI)})),r.addEventListener("error",t),globalThis.DescopeUI&&e(globalThis.DescopeUI)}))}))},ki.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.1.3"}};class Si extends ki{static set sdkConfigOverrides(e){ki.sdkConfigOverrides=e}constructor(){const e=new xr;super(e.update.bind(e)),ai.add(this),this.stepState=new xr({},{updateOnlyOnChange:!1}),li.set(this,void 0),ci.set(this,null),di.set(this,(()=>{clearInterval(h(this,li,"f")),p(this,li,null,"f")})),ui.set(this,(e=>{var t,n,o,r,i,s,a,l,c;if(!(null==e?void 0:e.ok)){h(this,di,"f").call(this),h(this,ai,"m",Ii).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)&&Fo&&localStorage.setItem(Yo,JSON.stringify(e))}(f),h(this,di,"f").call(this),void h(this,ai,"m",Ii).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!==nr?(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})})),hi.set(this,mr((()=>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,ci,"f"))||void 0===e||e.abort(),p(this,ci,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 dr(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 dr(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:_,ssoAppId:T}=e;let P,L;h(this,li,"f")&&h(this,di,"f").call(this);const M=(()=>{const e=localStorage.getItem(Ur);if(!e){const e=Math.floor(100*Math.random()+1);return localStorage.setItem(Ur,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=Er[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=Er[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,!br(P,C,E,A,T))){const e={};let t=!1;w&&(t=!0,e.exchangeCode=w,e.idpInitiated=!0),b&&(t=!0,e.token=b);const n=yield this.sdk.flow.start(s,Object.assign(Object.assign({tenant:a,redirectAuth:q,oidcIdpStateId:C,samlIdpStateId:E,samlIdpUsername:A,ssoAppId:T},m&&{redirectUrl:m}),{lastAuth:Ar($),abTestingKey:M}),L,"",D.version,W.componentsVersion,t?e:void 0);return h(this,ui,"f").call(this,n),void("completed"!==(null===(o=null==n?void 0:n.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,ir,D.version,W.componentsVersion,{token:b,exchangeCode:w,exchangeError:y});return h(this,ui,"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,_||"",wr)}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===or||"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,ci,"f"))||void 0===r||r.abort(),p(this,ci,null,"f");try{e=d===or?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,ir,D.version,W.componentsVersion,{transactionId:I,response:e,failure:t});h(this,ui,"f").call(this,n)}if(d===nr&&p(this,li,setInterval((()=>u(this,void 0,void 0,(function*(){const e=yield this.sdk.flow.next(c,l,sr,D.version,W.componentsVersion,{});h(this,ui,"f").call(this,e)}))),2e3),"f"),!f&&!P)return void this.loggerWrapper.warn("No screen was found to show");const F=P||f,N=yield this.getHtmlFilenameWithLocale(O,F),K={direction:hr(+l,+t.stepId),screenState:Object.assign(Object.assign({},g),{lastAuth:{loginId:$,name:this.sdk.getLastUserDisplayName()||$}}),htmlUrl:ur(i,`${F}.html`),htmlLocaleUrl:N&&ur(i,N),samlIdpUsername:A},J=Ar($);br(P,C,E,A,T)?K.next=(e,t,n,o)=>this.sdk.flow.start(s,Object.assign({tenant:a,redirectAuth:q,oidcIdpStateId:C,samlIdpStateId:E,samlIdpUsername:A,ssoAppId:T,lastAuth:J,preview:this.preview,abTestingKey:M},m&&{redirectUrl:m}),L,e,t,n,Object.assign(Object.assign(Object.assign({},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 this.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,ai,"m",fi).call(this,d,a):d.querySelectorAll(`descope-button[${tr}="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(`[${tr}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(e,"error-message",i),Cr(e,null==t?void 0:t.inputs),Cr(e,null==t?void 0:t.form),((e,t)=>{e.querySelectorAll(`[${tr}="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=((e,t)=>e.replace(/{{(.+?)}}/g,((e,n)=>{return o=t,n.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),o);var o})))(e.textContent,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);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,ai,"m",wi).call(this,a),h(this,ai,"m",Ii).call(this,"page-updated",{}),this.rootElement.querySelector(`[${tr}="polling"]`)){const e=yield this.getFlowConfig(),t=yield this.getProjectConfig(),n=yield a(sr,e.version,t.componentsVersion,{});h(this,ui,"f").call(this,n)}}));s?h(this,ai,"m",yi).call(this,g,s):g()}))}}li=new WeakMap,ci=new WeakMap,di=new WeakMap,ui=new WeakMap,hi=new WeakMap,ai=new WeakSet,pi=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)}))}},fi=function(e,t){var n;return u(this,void 0,void 0,(function*(){null===(n=h(this,ci,"f"))||void 0===n||n.abort();const o=e.querySelector('*[autocomplete="webauthn"]');if(o&&(yield Or())){const{options:e,transactionId:n}=(yield h(this,hi,"f").call(this))||{};if(e&&n){h(this,ai,"m",pi).call(this,o),p(this,ci,new AbortController,"f");const r=yield this.getFlowConfig(),i=yield this.getProjectConfig();this.sdk.webauthn.helpers.conditional(e,h(this,ci,"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,ui,"f").call(this,s)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)}))}}}))},gi=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)}))},vi=function(){return u(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${Go}])`));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})),{})}))},mi=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},bi=function(e,t){return u(this,void 0,void 0,(function*(){if("true"===e.getAttribute("formnovalidate")||h(this,ai,"m",gi).call(this)){const o=null==e?void 0:e.getAttribute("id");h(this,ai,"m",mi).call(this,e);const r=yield h(this,ai,"m",vi).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,ui,"f").call(this,d)}var n}))},wi=function(e){this.rootElement.querySelectorAll("descope-button:not([data-exclude-next])").forEach((t=>{t.onclick=()=>{h(this,ai,"m",bi).call(this,t,e)}}))},yi=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===ar.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")},Ii=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.define("descope-wc",Si);var ji=Object.freeze({__proto__:null,default:Si});const xi=(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 Ci,Oi,Ei,Ai,Ui,Ri,_i,Ti,Pi,Li;const Mi=document.createElement("template");Mi.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 $i extends HTMLElement{constructor(){super(),Ci.add(this),Oi.set(this,new xr({messages:[]})),Ei.set(this,void 0),Ai.set(this,void 0),Ui.set(this,void 0),Ri.set(this,{resize:h(this,Ci,"m",Li).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Mi.content.cloneNode(!0)),p(this,Ei,this.shadowRoot.querySelector(".debugger"),"f"),p(this,Ai,h(this,Ei,"f").querySelector(".content"),"f"),p(this,Ui,h(this,Ei,"f").querySelector(".header"),"f")}updateData(e){h(this,Oi,"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]=xi(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,Ei,"f"),h(this,Ui,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",h(this,Ri,"f").resize),(e=h(this,Ei,"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,Ei,"f").onresize=h(this,Ci,"m",Pi).bind(this),h(this,Oi,"f").subscribe(h(this,Ci,"m",_i).bind(this))}disconnectedCallback(){h(this,Oi,"f").unsubscribeAll(),window.removeEventListener("resize",h(this,Ri,"f").resize)}}Oi=new WeakMap,Ei=new WeakMap,Ai=new WeakMap,Ui=new WeakMap,Ri=new WeakMap,Ci=new WeakSet,_i=function(e){h(this,Ci,"m",Ti).call(this,e),h(this,Ci,"m",Pi).call(this)},Ti=function(e){h(this,Ai,"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("")},Pi=function(){h(this,Ai,"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)}))},Li=function(){const[e,t]=xi(h(this,Ei,"f"),Number.parseInt(h(this,Ei,"f").style.left,10),Number.parseInt(h(this,Ei,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});h(this,Ei,"f").style.top=`${t}px`,h(this,Ei,"f").style.left=`${e}px`},customElements.define("descope-debugger",$i);var Di=Object.freeze({__proto__:null,default:$i});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=To,e.getSessionToken=_o,e.refresh=(e=To())=>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