"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9762],{5461:function(e,t,s){var i=s(7814),r=s(3642),a=s(5815),n=s(574),o=s(719),l=s(5267),u=s(9731),h=s(2028),c=s(9670),d=s(9696),_=s(4615),f=s(7172);(0,h.Y)();let g={url:r.G1,storageKey:r.Uf,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:r.QN,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function w(e,t,s){return await s()}let y={};class v{get jwks(){var e,t;return null!==(t=null===(e=y[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){y[this.storageKey]=Object.assign(Object.assign({},y[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=y[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){y[this.storageKey]=Object.assign(Object.assign({},y[this.storageKey]),{cachedAt:e})}constructor(e){var t,s,r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let a=Object.assign(Object.assign({},g),e);if(this.storageKey=a.storageKey,this.instanceID=null!==(t=v.nextInstanceID[this.storageKey])&&void 0!==t?t:0,v.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,"function"==typeof a.debug&&(this.logger=a.debug),this.instanceID>0&&(0,o.jU)()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.admin=new i.Z({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=(0,o.eM)(a.fetch),this.lock=a.lock||w,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&(0,o.jU)()&&(null===(s=null==globalThis?void 0:globalThis.navigator)||void 0===s?void 0:s.locks)?this.lock=u.aC:this.lock=w,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new f.pw(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(a.storage?this.storage=a.storage:(0,o.y1)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,l._)(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=(0,l._)(this.memoryStorage)),(0,o.jU)()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(r=this.broadcastChannel)||void 0===r||r.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}})}a.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${c.i}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},s="none";if((0,o.jU)()&&(t=(0,o.o9)(window.location.href),this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce")),(0,o.jU)()&&this.detectSessionInUrl&&"none"!==s){let{data:i,error:r}=await this._getSessionFromURL(t,s);if(r)return this._debug("#_initialize()","error detecting session from URL",r),(0,a.wo)(r)&&(null===(e=r.details)||void 0===e||e.code),{error:r};let{session:n,redirectType:o}=i;return this._debug("#_initialize()","detected session in URL",n,"redirect type",o),await this._saveSession(n),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if((0,a.f1)(e))return this._returnResult({error:e});return this._returnResult({error:new a.Iu("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let{data:r,error:a}=await (0,n.cY)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(s=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==s?s:{},gotrue_meta_security:{captcha_token:null===(i=null==e?void 0:e.options)||void 0===i?void 0:i.captchaToken}},xform:n.vI});if(a||!r)return this._returnResult({data:{user:null,session:null},error:a});let o=r.session,l=r.user;return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,s,i;try{let r;if("email"in e){let{email:s,password:i,options:a}=e,l=null,u=null;"pkce"===this.flowType&&([l,u]=await (0,o.__)(this.storage,this.storageKey)),r=await (0,n.cY)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==a?void 0:a.emailRedirectTo,body:{email:s,password:i,data:null!==(t=null==a?void 0:a.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken},code_challenge:l,code_challenge_method:u},xform:n.vI})}else if("phone"in e){let{phone:t,password:a,options:o}=e;r=await (0,n.cY)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:a,data:null!==(s=null==o?void 0:o.data)&&void 0!==s?s:{},channel:null!==(i=null==o?void 0:o.channel)&&void 0!==i?i:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:n.vI})}else throw new a.e_("You must provide either an email or phone number and a password");let{data:l,error:u}=r;if(u||!l)return await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:u});let h=l.session,c=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",h)),this._returnResult({data:{user:c,session:h},error:null})}catch(e){if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),(0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:s,password:i,options:r}=e;t=await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken}},xform:n.jv})}else if("phone"in e){let{phone:s,password:i,options:r}=e;t=await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken}},xform:n.jv})}else throw new a.e_("You must provide either an email or phone number and a password");let{data:s,error:i}=t;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!s||!s.session||!s.user){let e=new a.eV;return this._returnResult({data:{user:null,session:null},error:e})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,s,i,r;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:null===(r=e.options)||void 0===r?void 0:r.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,s,i,r,l,u,h,c,d,f,g;let w,y;if("message"in e)w=e.message,y=e.signature;else{let a;let{chain:n,wallet:f,statement:g,options:v}=e;if((0,o.jU)()){if("object"==typeof f)a=f;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)a=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}}else{if("object"!=typeof f||!(null==v?void 0:v.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");a=f}let p=new URL(null!==(t=null==v?void 0:v.url)&&void 0!==t?t:window.location.href),b=await a.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!b||0===b.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let k=(0,_.Kn)(b[0]),m=null===(s=null==v?void 0:v.signInWithEthereum)||void 0===s?void 0:s.chainId;if(!m){let e=await a.request({method:"eth_chainId"});m=(0,_.H_)(e)}let S={domain:p.host,address:k,statement:g,uri:p.href,version:"1",chainId:m,nonce:null===(i=null==v?void 0:v.signInWithEthereum)||void 0===i?void 0:i.nonce,issuedAt:null!==(l=null===(r=null==v?void 0:v.signInWithEthereum)||void 0===r?void 0:r.issuedAt)&&void 0!==l?l:new Date,expirationTime:null===(u=null==v?void 0:v.signInWithEthereum)||void 0===u?void 0:u.expirationTime,notBefore:null===(h=null==v?void 0:v.signInWithEthereum)||void 0===h?void 0:h.notBefore,requestId:null===(c=null==v?void 0:v.signInWithEthereum)||void 0===c?void 0:c.requestId,resources:null===(d=null==v?void 0:v.signInWithEthereum)||void 0===d?void 0:d.resources};w=(0,_.eJ)(S),y=await a.request({method:"personal_sign",params:[(0,_.NC)(w),k]})}try{let{data:t,error:s}=await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:w,signature:y},(null===(f=e.options)||void 0===f?void 0:f.captchaToken)?{gotrue_meta_security:{captcha_token:null===(g=e.options)||void 0===g?void 0:g.captchaToken}}:null),xform:n.vI});if(s)throw s;if(!t||!t.session||!t.user){let e=new a.eV;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:s})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,s,i,r,l,u,h,c,_,f,g,w;let y,v;if("message"in e)y=e.message,v=e.signature;else{let a;let{chain:n,wallet:d,statement:g,options:w}=e;if((0,o.jU)()){if("object"==typeof d)a=d;else{let e=window;if("solana"in e&&"object"==typeof e.solana&&("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))a=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}}else{if("object"!=typeof d||!(null==w?void 0:w.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");a=d}let p=new URL(null!==(t=null==w?void 0:w.url)&&void 0!==t?t:window.location.href);if("signIn"in a&&a.signIn){let e;let t=await a.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==w?void 0:w.signInWithSolana),{version:"1",domain:p.host,uri:p.href}),g?{statement:g}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)y="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),v=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in a)||"function"!=typeof a.signMessage||!("publicKey"in a)||"object"!=typeof a||!a.publicKey||!("toBase58"in a.publicKey)||"function"!=typeof a.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${p.host} wants you to sign in with your Solana account:`,a.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${p.href}`,`Issued At: ${null!==(i=null===(s=null==w?void 0:w.signInWithSolana)||void 0===s?void 0:s.issuedAt)&&void 0!==i?i:new Date().toISOString()}`,...(null===(r=null==w?void 0:w.signInWithSolana)||void 0===r?void 0:r.notBefore)?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...(null===(l=null==w?void 0:w.signInWithSolana)||void 0===l?void 0:l.expirationTime)?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...(null===(u=null==w?void 0:w.signInWithSolana)||void 0===u?void 0:u.chainId)?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...(null===(h=null==w?void 0:w.signInWithSolana)||void 0===h?void 0:h.nonce)?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...(null===(c=null==w?void 0:w.signInWithSolana)||void 0===c?void 0:c.requestId)?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...(null===(f=null===(_=null==w?void 0:w.signInWithSolana)||void 0===_?void 0:_.resources)||void 0===f?void 0:f.length)?["Resources",...w.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");let e=await a.signMessage(new TextEncoder().encode(y),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=e}}try{let{data:t,error:s}=await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:(0,d.rB)(v)},(null===(g=e.options)||void 0===g?void 0:g.captchaToken)?{gotrue_meta_security:{captcha_token:null===(w=e.options)||void 0===w?void 0:w.captchaToken}}:null),xform:n.vI});if(s)throw s;if(!t||!t.session||!t.user){let e=new a.eV;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:s})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await (0,o.Dc)(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(null!=t?t:"").split("/");try{if(!s&&"pkce"===this.flowType)throw new a.Uw;let{data:t,error:r}=await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:n.vI});if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),r)throw r;if(!t||!t.session||!t.user){let e=new a.eV;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=i?i:null}),error:r})}catch(e){if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),(0,a.f1)(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:s,token:i,access_token:r,nonce:o}=e,{data:l,error:u}=await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:r,nonce:o,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:n.vI});if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let e=new a.eV;return this._returnResult({data:{user:null,session:null},error:e})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,s,i,r,l;try{if("email"in e){let{email:i,options:r}=e,a=null,l=null;"pkce"===this.flowType&&([a,l]=await (0,o.__)(this.storage,this.storageKey));let{error:u}=await (0,n.cY)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:i,data:null!==(t=null==r?void 0:r.data)&&void 0!==t?t:{},create_user:null===(s=null==r?void 0:r.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},code_challenge:a,code_challenge_method:l},redirectTo:null==r?void 0:r.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:u})}if("phone"in e){let{phone:t,options:s}=e,{data:a,error:o}=await (0,n.cY)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(i=null==s?void 0:s.data)&&void 0!==i?i:{},create_user:null===(r=null==s?void 0:s.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},channel:null!==(l=null==s?void 0:s.channel)&&void 0!==l?l:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new a.e_("You must provide either an email or phone number.")}catch(e){if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),(0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,s;try{let i,r;"options"in e&&(i=null===(t=e.options)||void 0===t?void 0:t.redirectTo,r=null===(s=e.options)||void 0===s?void 0:s.captchaToken);let{data:a,error:o}=await (0,n.cY)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:r}}),redirectTo:i,xform:n.vI});if(o)throw o;if(!a)throw Error("An error occurred on token verification.");let l=a.session,u=a.user;return(null==l?void 0:l.access_token)&&(await this._saveSession(l),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,s,i,r,l;try{let a=null,u=null;"pkce"===this.flowType&&([a,u]=await (0,o.__)(this.storage,this.storageKey));let h=await (0,n.cY)(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==s?s:void 0}),(null===(i=null==e?void 0:e.options)||void 0===i?void 0:i.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:u}),headers:this.headers,xform:n.E_});return(null===(r=h.data)||void 0===r?void 0:r.url)&&(0,o.jU)()&&!(null===(l=e.options)||void 0===l?void 0:l.skipBrowserRedirect)&&window.location.assign(h.data.url),this._returnResult(h)}catch(e){if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),(0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new a.GF;let{error:i}=await (0,n.cY)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:r}=e,{error:a}=await (0,n.cY)(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken}},redirectTo:null==r?void 0:r.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){let{phone:s,type:i,options:r}=e,{data:a,error:o}=await (0,n.cY)(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new a.e_("You must provide either an email or phone number and a type")}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch(e){}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,t=await (0,o.Dc)(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=!!e.expires_at&&1e3*e.expires_at-Date.now()await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{if(e)return await (0,n.cY)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:n.Br});return await this._useSession(async e=>{var t,s,i;let{data:r,error:o}=e;if(o)throw o;return(null===(t=r.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await (0,n.cY)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(i=null===(s=r.session)||void 0===s?void 0:s.access_token)&&void 0!==i?i:void 0,xform:n.Br}):{data:{user:null},error:new a.GF}})}catch(e){if((0,a.f1)(e))return(0,a.t)(e)&&(await this._removeSession(),await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:r}=s;if(r)throw r;if(!i.session)throw new a.GF;let l=i.session,u=null,h=null;"pkce"===this.flowType&&null!=e.email&&([u,h]=await (0,o.__)(this.storage,this.storageKey));let{data:c,error:d}=await (0,n.cY)(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:h}),jwt:l.access_token,xform:n.Br});if(d)throw d;return l.user=c.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(e){if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),(0,a.f1)(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new a.GF;let t=Date.now()/1e3,s=t,i=!0,r=null,{payload:n}=(0,o.xp)(e.access_token);if(n.exp&&(i=(s=n.exp)<=t),i){let{data:t,error:s}=await this._callRefreshToken(e.refresh_token);if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!t)return{data:{user:null,session:null},error:null};r=t}else{let{data:i,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});r={access_token:e.access_token,refresh_token:e.refresh_token,user:i.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(r),await this._notifyAllSubscribers("SIGNED_IN",r)}return this._returnResult({data:{user:r.user,session:r},error:null})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:i,error:r}=t;if(r)throw r;e=null!==(s=i.session)&&void 0!==s?s:void 0}if(!(null==e?void 0:e.refresh_token))throw new a.GF;let{data:i,error:r}=await this._callRefreshToken(e.refresh_token);return r?this._returnResult({data:{user:null,session:null},error:r}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!(0,o.jU)())throw new a.LI("No browser detected.");if(e.error||e.error_description||e.error_code)throw new a.LI(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new a.Po("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new a.LI("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new a.Po("No code detected.");let{data:t,error:s}=await this._exchangeCodeForSession(e.code);if(s)throw s;let i=new URL(window.location.href);return i.searchParams.delete("code"),window.history.replaceState(window.history.state,"",i.toString()),{data:{session:t.session,redirectType:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:l,expires_in:u,expires_at:h,token_type:c}=e;if(!n||!u||!l||!c)throw new a.LI("No session defined in URL");let d=Math.round(Date.now()/1e3),_=parseInt(u),f=d+_;h&&(f=parseInt(h));let g=f-d;1e3*g<=r.r6&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${_}s`);let w=f-_;d-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,f,d):d-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",w,f,d);let{data:y,error:v}=await this._getUser(n);if(v)throw v;let p={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:_,expires_at:f,refresh_token:l,token_type:c,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(e){if((0,a.f1)(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await (0,o.Dc)(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:i,error:r}=t;if(r&&!(0,a.t)(r))return this._returnResult({error:r});let n=null===(s=i.session)||void 0===s?void 0:s.access_token;if(n){let{error:t}=await this.admin.signOut(n,e);if(t&&!((0,a.Tw)(t)&&(404===t.status||401===t.status||403===t.status)||(0,a.t)(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=(0,o.xP)(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{let{data:{session:i},error:r}=t;if(r)throw r;await (null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(t){await (null===(i=this.stateChangeEmitters.get(e))||void 0===i?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let s=null,i=null;"pkce"===this.flowType&&([s,i]=await (0,o.__)(this.storage,this.storageKey,!0));try{return await (0,n.cY)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),(0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:s,error:i}=await this._useSession(async t=>{var s,i,r,a,o;let{data:l,error:u}=t;if(u)throw u;let h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(s=e.options)||void 0===s?void 0:s.redirectTo,scopes:null===(i=e.options)||void 0===i?void 0:i.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:!0});return await (0,n.cY)(this.fetch,"GET",h,{headers:this.headers,jwt:null!==(o=null===(a=l.session)||void 0===a?void 0:a.access_token)&&void 0!==o?o:void 0})});if(i)throw i;return!(0,o.jU)()||(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)||window.location.assign(null==s?void 0:s.url),this._returnResult({data:{provider:e.provider,url:null==s?void 0:s.url},error:null})}catch(t){if((0,a.f1)(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var s;try{let{error:i,data:{session:r}}=t;if(i)throw i;let{options:o,provider:l,token:u,access_token:h,nonce:c}=e,{data:d,error:_}=await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(s=null==r?void 0:r.access_token)&&void 0!==s?s:void 0,body:{provider:l,id_token:u,access_token:h,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:n.vI});if(_)return this._returnResult({data:{user:null,session:null},error:_});if(!d||!d.session||!d.user)return this._returnResult({data:{user:null,session:null},error:new a.eV});return d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:_})}catch(e){if(await (0,o.Sv)(this.storage,`${this.storageKey}-code-verifier`),(0,a.f1)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:r,error:a}=t;if(a)throw a;return await (0,n.cY)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(i=null===(s=r.session)||void 0===s?void 0:s.access_token)&&void 0!==i?i:void 0})})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await (0,o.Rd)(async s=>(s>0&&await (0,o._v)(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await (0,n.cY)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:n.vI})),(e,t)=>t&&(0,a.AO)(t)&&Date.now()+200*Math.pow(2,e)-s{try{await s.callback(e,t)}catch(e){i.push(e)}});if(await Promise.all(r),i.length>0){for(let e=0;ethis._autoRefreshTokenTick(),r.r6);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((1e3*s.expires_at-e)/r.r6);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${r.r6}ms, refresh threshold is ${r.Js} ticks`),i<=r.Js&&await this._callRefreshToken(s.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof u.mL)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,o.jU)()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if("visible"!==document.visibilityState){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let i=[`provider=${encodeURIComponent(t)}`];if((null==s?void 0:s.redirectTo)&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),(null==s?void 0:s.scopes)&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),"pkce"===this.flowType){let[e,t]=await (0,o.__)(this.storage,this.storageKey),s=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});i.push(s.toString())}if(null==s?void 0:s.queryParams){let e=new URLSearchParams(s.queryParams);i.push(e.toString())}return(null==s?void 0:s.skipBrowserRedirect)&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:r}=t;return r?this._returnResult({data:null,error:r}):await (0,n.cY)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.access_token})})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:r,error:a}=t;if(a)return this._returnResult({data:null,error:a});let o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:l,error:u}=await (0,n.cY)(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):("totp"===e.factorType&&"totp"===l.type&&(null===(i=null==l?void 0:l.totp)||void 0===i?void 0:i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:r}=t;if(r)return this._returnResult({data:null,error:r});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?(0,f.xd)(e.webauthn.credential_response):(0,f.eR)(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await (0,n.cY)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:l}))})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:r}=t;if(r)return this._returnResult({data:null,error:r});let a=await (0,n.cY)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.access_token});if(a.error)return a;let{data:o}=a;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:(0,f.By)(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:(0,f.jE)(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:s}=await this.getUser();if(s)return{data:null,error:s};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])i.all.push(s),"verified"===s.status&&i[s.factor_type].push(s);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,s,i,r;if(e)try{let{payload:i}=(0,o.xp)(e),r=null;i.aal&&(r=i.aal);let a=r,{data:{user:n},error:l}=await this.getUser(e);if(l)return this._returnResult({data:null,error:l});(null!==(s=null===(t=null==n?void 0:n.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==s?s:[]).length>0&&(a="aal2");let u=i.amr||[];return{data:{currentLevel:r,nextLevel:a,currentAuthenticationMethods:u},error:null}}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:n},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:u}=(0,o.xp)(n.access_token),h=null;u.aal&&(h=u.aal);let c=h;return(null!==(r=null===(i=n.user.factors)||void 0===i?void 0:i.filter(e=>"verified"===e.status))&&void 0!==r?r:[]).length>0&&(c="aal2"),{data:{currentLevel:h,nextLevel:c,currentAuthenticationMethods:u.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:s},error:i}=t;return i?this._returnResult({data:null,error:i}):s?await (0,n.cY)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new a.GF})})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async s=>{let{data:{session:i},error:r}=s;if(r)return this._returnResult({data:null,error:r});if(!i)return this._returnResult({data:null,error:new a.GF});let l=await (0,n.cY)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return l.data&&l.data.redirect_url&&(0,o.jU)()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(l.data.redirect_url),l})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async s=>{let{data:{session:i},error:r}=s;if(r)return this._returnResult({data:null,error:r});if(!i)return this._returnResult({data:null,error:new a.GF});let l=await (0,n.cY)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return l.data&&l.data.redirect_url&&(0,o.jU)()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(l.data.redirect_url),l})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;return s?this._returnResult({data:null,error:s}):t?await (0,n.cY)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new a.GF})})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:s},error:i}=t;return i?this._returnResult({data:null,error:i}):s?(await (0,n.cY)(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new a.GF})})}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(t=>t.kid===e);if(s)return s;let i=Date.now();if((s=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+r.Kd>i)return s;let{data:a,error:o}=await (0,n.cY)(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return a.keys&&0!==a.keys.length&&(this.jwks=a,this.jwks_cached_at=i,s=a.keys.find(t=>t.kid===e))?s:null}async getClaims(e,t={}){try{let s=e;if(!s){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});s=e.session.access_token}let{header:i,payload:r,signature:n,raw:{header:l,payload:u}}=(0,o.xp)(s);(null==t?void 0:t.allowExpired)||(0,o.RZ)(r.exp);let h=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!h){let{error:e}=await this.getUser(s);if(e)throw e;return{data:{claims:r,header:i,signature:n},error:null}}let c=(0,o.Z2)(i.alg),_=await crypto.subtle.importKey("jwk",h,c,!0,["verify"]);if(!await crypto.subtle.verify(c,_,n,(0,d.sy)(`${l}.${u}`)))throw new a.UQ("Invalid JWT signature");return{data:{claims:r,header:i,signature:n},error:null}}catch(e){if((0,a.f1)(e))return this._returnResult({data:null,error:e});throw e}}}v.nextInstanceID={},t.Z=v}}]);