heyio 3.0.7 → 3.0.9
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/api/middleware/auth.js +3 -3
- package/dist/api/middleware/auth.js.map +1 -1
- package/node_modules/@io/shared/package.json +1 -1
- package/package.json +1 -1
- package/public/assets/{index-2RY89H3W.js → index-dINUWXx2.js} +2 -2
- package/public/assets/{index-2RY89H3W.js.map → index-dINUWXx2.js.map} +1 -1
- package/public/index.html +1 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import jwt from 'jsonwebtoken';
|
|
2
2
|
import { createChildLogger } from '../../logging/logger.js';
|
|
3
3
|
const logger = () => createChildLogger('auth');
|
|
4
|
-
// Routes that don't require authentication
|
|
4
|
+
// Routes that don't require authentication (paths relative to /api mount)
|
|
5
5
|
const EXEMPT_ROUTES = [
|
|
6
|
-
{ method: 'GET', path: '/
|
|
7
|
-
{ method: 'GET', path: '/
|
|
6
|
+
{ method: 'GET', path: '/health' },
|
|
7
|
+
{ method: 'GET', path: '/config' },
|
|
8
8
|
];
|
|
9
9
|
function isExempt(method, path) {
|
|
10
10
|
return EXEMPT_ROUTES.some((r) => r.method === method.toUpperCase() && path.startsWith(r.path));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/api/middleware/auth.ts"],"names":[],"mappings":"AACA,OAAO,GAAG,MAAM,cAAc,CAAC;AAE/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;AAE/C,
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/api/middleware/auth.ts"],"names":[],"mappings":"AACA,OAAO,GAAG,MAAM,cAAc,CAAC;AAE/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;AAE/C,0EAA0E;AAC1E,MAAM,aAAa,GAA4C;IAC9D,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE;IAClC,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE;CAClC,CAAC;AAEF,SAAS,QAAQ,CAAC,MAAc,EAAE,IAAY;IAC7C,OAAO,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AAChG,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,MAAgB;IAC9C,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAQ,EAAE;QAChE,6EAA6E;QAC7E,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC;YAChC,IAAI,EAAE,CAAC;YACP,OAAO;QACR,CAAC;QAED,mCAAmC;QACnC,IAAI,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACpC,IAAI,EAAE,CAAC;YACP,OAAO;QACR,CAAC;QAED,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC;QAC7C,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;YACxC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,yCAAyC,EAAE,CAAC,CAAC;YAC3E,OAAO;QACR,CAAC;QAED,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAElC,IAAI,CAAC;YACJ,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE;gBAC5C,UAAU,EAAE,CAAC,OAAO,CAAC;aACrB,CAAC,CAAC;YACH,IAAI,EAAE,CAAC;QACR,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACd,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,EAAE,yBAAyB,CAAC,CAAC;YACnD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,0BAA0B,EAAE,CAAC,CAAC;QAC7D,CAAC;IACF,CAAC,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,MAAgB,EAAE,KAAoB;IACnE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,CAAC;QAChC,OAAO,IAAI,CAAC,CAAC,6BAA6B;IAC3C,CAAC;IAED,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,OAAO,KAAK,CAAC;IACd,CAAC;IAED,IAAI,CAAC;QACJ,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,SAAS,EAAE,EAAE,UAAU,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACxE,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -196,7 +196,7 @@ Request ID: ${c}`),f){let k=`
|
|
|
196
196
|
Resources:`;for(const E of f){if(!E||typeof E!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${E}`);k+=`
|
|
197
197
|
- ${E}`}S+=k}return`${y}
|
|
198
198
|
${S}`}class At extends Error{constructor({message:e,code:r,cause:n,name:i}){var a;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(a=i??(n instanceof Error?n.name:void 0))!==null&&a!==void 0?a:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Jf extends At{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function Cq({error:t,options:e}){var r,n,i;const{publicKey:a}=e;if(!a)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new At({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=a.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new At({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=a.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new At({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=a.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new At({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new At({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new At({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return a.pubKeyCredParams.filter(u=>u.type==="public-key").length===0?new At({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new At({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(GR(s)){if(a.rp.id!==s)return new At({message:`The RP ID "${a.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new At({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new At({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new At({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new At({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function jq({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new At({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new At({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(GR(n)){if(r.rpId!==n)return new At({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new At({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new At({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new At({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Rq{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const h0=new Rq;function Rk(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:n}=t,i=ah(t,["challenge","user","excludeCredentials"]),a=Xo(e).buffer,s=Object.assign(Object.assign({},r),{id:Xo(r.id).buffer}),u=Object.assign(Object.assign({},i),{challenge:a,user:s});if(n&&n.length>0){u.excludeCredentials=new Array(n.length);for(let c=0;c<n.length;c++){const f=n[c];u.excludeCredentials[c]=Object.assign(Object.assign({},f),{id:Xo(f.id).buffer,type:f.type||"public-key",transports:f.transports})}}return u}function Ik(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,n=ah(t,["challenge","allowCredentials"]),i=Xo(e).buffer,a=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){a.allowCredentials=new Array(r.length);for(let s=0;s<r.length;s++){const u=r[s];a.allowCredentials[s]=Object.assign(Object.assign({},u),{id:Xo(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function $k(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:La(new Uint8Array(t.response.attestationObject)),clientDataJSON:La(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Nk(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,n=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:La(new Uint8Array(i.authenticatorData)),clientDataJSON:La(new Uint8Array(i.clientDataJSON)),signature:La(new Uint8Array(i.signature)),userHandle:i.userHandle?La(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function GR(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Qf(){var t,e;return!!(Jt()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function XR(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Jf("Browser returned unexpected credential type",e)}:{data:null,error:new Jf("Empty credential response",e)}}catch(e){return{data:null,error:Cq({error:e,options:t})}}}async function YR(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Jf("Browser returned unexpected credential type",e)}:{data:null,error:new Jf("Empty credential response",e)}}catch(e){return{data:null,error:jq({error:e,options:t})}}}const Iq={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},$q={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Zf(...t){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(const i of t)if(i)for(const a in i){const s=i[a];if(s!==void 0)if(Array.isArray(s))n[a]=s;else if(r(s))n[a]=s;else if(e(s)){const u=n[a];e(u)?n[a]=Zf(u,s):n[a]=Zf(s)}else n[a]=s}return n}function Nq(t,e){return Zf(Iq,t,e||{})}function Mq(t,e){return Zf($q,t,e||{})}class Lq{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},a){var s;try{const{data:u,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!u)return{data:null,error:c};const f=i??h0.createNewAbortSignal();if(u.webauthn.type==="create"){const{user:p}=u.webauthn.credential_options.publicKey;if(!p.name){const h=n;if(h)p.name=`${p.id}:${h}`;else{const v=(await this.client.getUser()).data.user,w=((s=v==null?void 0:v.user_metadata)===null||s===void 0?void 0:s.name)||(v==null?void 0:v.email)||(v==null?void 0:v.id)||"User";p.name=`${p.id}:${w}`}}p.displayName||(p.displayName=p.name)}switch(u.webauthn.type){case"create":{const p=Nq(u.webauthn.credential_options.publicKey,a==null?void 0:a.create),{data:h,error:g}=await XR({publicKey:p,signal:f});return h?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:h}},error:null}:{data:null,error:g}}case"request":{const p=Mq(u.webauthn.credential_options.publicKey,a==null?void 0:a.request),{data:h,error:g}=await YR(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:p,signal:f}));return h?{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:h}},error:null}:{data:null,error:g}}}}catch(u){return he(u)?{data:null,error:u}:{data:null,error:new xn("Unexpected error in challenge",u)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new ts("rpId is required for WebAuthn authentication")};try{if(!Qf())return{data:null,error:new xn("Browser does not support WebAuthn",null)};const{data:s,error:u}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:a});if(!s)return{data:null,error:u};const{webauthn:c}=s;return this._verify({factorId:e,challengeId:s.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:n,credential_response:c.credential_response}})}catch(s){return he(s)?{data:null,error:s}:{data:null,error:new xn("Unexpected error in authenticate",s)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new ts("rpId is required for WebAuthn registration")};try{if(!Qf())return{data:null,error:new xn("Browser does not support WebAuthn",null)};const{data:s,error:u}=await this._enroll({friendlyName:e});if(!s)return await this.client.mfa.listFactors().then(p=>{var h;return(h=p.data)===null||h===void 0?void 0:h.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(p=>p?this.client.mfa.unenroll({factorId:p==null?void 0:p.id}):void 0),{data:null,error:u};const{data:c,error:f}=await this._challenge({factorId:s.id,friendlyName:s.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:a});return c?this._verify({factorId:s.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:n,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:f}}catch(s){return he(s)?{data:null,error:s}:{data:null,error:new xn("Unexpected error in register",s)}}}}Eq();const Dq={url:zU,storageKey:FU,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:WU,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function Mk(t,e,r){return await r()}const $o={};class su{get jwks(){var e,r;return(r=(e=$o[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){$o[this.storageKey]=Object.assign(Object.assign({},$o[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=$o[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){$o[this.storageKey]=Object.assign(Object.assign({},$o[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,i,a;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;const s=Object.assign(Object.assign({},Dq),e);if(this.storageKey=s.storageKey,this.instanceID=(r=su.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,su.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&Jt()){const u=`${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(u),this.logDebugMessages&&console.trace(u)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.experimental=(n=s.experimental)!==null&&n!==void 0?n:{},this.admin=new kq({url:s.url,headers:s.headers,fetch:s.fetch,experimental:this.experimental}),this.url=s.url,this.headers=s.headers,this.fetch=HR(s.fetch),this.lock=s.lock||Mk,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Jt()&&(!((i=globalThis==null?void 0:globalThis.navigator)===null||i===void 0)&&i.locks)?this.lock=Oq:this.lock=Mk,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 Lq(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.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:WR()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ck(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Ck(this.memoryStorage)),Jt()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(u){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",u)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async u=>{this._debug("received broadcast notification from other tab or client",u);try{await this._notifyAllSubscribers(u.data.event,u.data.session,!1)}catch(c){this._debug("#broadcastChannel","error",c)}})}s.skipAutoInitialize||this.initialize().catch(u=>{this._debug("#initialize()","error",u)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${qR}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if(Jt()&&(r=iq(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),Jt()&&this.detectSessionInUrl&&n!=="none"){const{data:i,error:a}=await this._getSessionFromURL(r,n);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),XU(a)){const c=(e=a.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:a}}return{error:a}}const{session:s,redirectType:u}=i;return this._debug("#_initialize()","detected session in URL",s,"redirect type",u),await this._saveSession(s),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return he(r)?this._returnResult({error:r}):this._returnResult({error:new xn("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const a=await xe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:Qr}),{data:s,error:u}=a;if(u||!s)return this._returnResult({data:{user:null,session:null},error:u});const c=s.session,f=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:f,session:c},error:null})}catch(a){if(he(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var r,n,i;try{let a;if("email"in e){const{email:p,password:h,options:g}=e;let v=null,w=null;this.flowType==="pkce"&&([v,w]=await Io(this.storage,this.storageKey)),a=await xe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:p,password:h,data:(r=g==null?void 0:g.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:v,code_challenge_method:w},xform:Qr})}else if("phone"in e){const{phone:p,password:h,options:g}=e;a=await xe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:p,password:h,data:(n=g==null?void 0:g.data)!==null&&n!==void 0?n:{},channel:(i=g==null?void 0:g.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:Qr})}else throw new xf("You must provide either an email or phone number and a password");const{data:s,error:u}=a;if(u||!s)return await Yt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:u});const c=s.session,f=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:f,session:c},error:null})}catch(a){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:a,password:s,options:u}=e;r=await xe(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:s,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Pk})}else if("phone"in e){const{phone:a,password:s,options:u}=e;r=await xe(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:s,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:Pk})}else throw new xf("You must provide either an email or phone number and a password");const{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){const a=new Ro;return this._returnResult({data:{user:null,session:null},error:a})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(he(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,i,a,s,u,c,f,p,h,g;let v,w;if("message"in e)v=e.message,w=e.signature;else{const{chain:x,wallet:y,statement:S,options:k}=e;let E;if(Jt())if(typeof y=="object")E=y;else{const M=window;if("ethereum"in M&&typeof M.ethereum=="object"&&"request"in M.ethereum&&typeof M.ethereum.request=="function")E=M.ethereum;else throw new 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(typeof y!="object"||!(k!=null&&k.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=y}const P=new URL((r=k==null?void 0:k.url)!==null&&r!==void 0?r:window.location.href),O=await E.request({method:"eth_requestAccounts"}).then(M=>M).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!O||O.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const A=KR(O[0]);let C=(n=k==null?void 0:k.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!C){const M=await E.request({method:"eth_chainId"});C=Aq(M)}const R={domain:P.host,address:A,statement:S,uri:P.href,version:"1",chainId:C,nonce:(i=k==null?void 0:k.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(s=(a=k==null?void 0:k.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&s!==void 0?s:new Date,expirationTime:(u=k==null?void 0:k.signInWithEthereum)===null||u===void 0?void 0:u.expirationTime,notBefore:(c=k==null?void 0:k.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(f=k==null?void 0:k.signInWithEthereum)===null||f===void 0?void 0:f.requestId,resources:(p=k==null?void 0:k.signInWithEthereum)===null||p===void 0?void 0:p.resources};v=Tq(R),w=await E.request({method:"personal_sign",params:[Pq(v),A]})}try{const{data:x,error:y}=await xe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:v,signature:w},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:Qr});if(y)throw y;if(!x||!x.session||!x.user){const S=new Ro;return this._returnResult({data:{user:null,session:null},error:S})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:y})}catch(x){if(he(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async signInWithSolana(e){var r,n,i,a,s,u,c,f,p,h,g,v;let w,x;if("message"in e)w=e.message,x=e.signature;else{const{chain:y,wallet:S,statement:k,options:E}=e;let P;if(Jt())if(typeof S=="object")P=S;else{const A=window;if("solana"in A&&typeof A.solana=="object"&&("signIn"in A.solana&&typeof A.solana.signIn=="function"||"signMessage"in A.solana&&typeof A.solana.signMessage=="function"))P=A.solana;else throw new 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(typeof S!="object"||!(E!=null&&E.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");P=S}const O=new URL((r=E==null?void 0:E.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in P&&P.signIn){const A=await P.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},E==null?void 0:E.signInWithSolana),{version:"1",domain:O.host,uri:O.href}),k?{statement:k}:null));let C;if(Array.isArray(A)&&A[0]&&typeof A[0]=="object")C=A[0];else if(A&&typeof A=="object"&&"signedMessage"in A&&"signature"in A)C=A;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in C&&"signature"in C&&(typeof C.signedMessage=="string"||C.signedMessage instanceof Uint8Array)&&C.signature instanceof Uint8Array)w=typeof C.signedMessage=="string"?C.signedMessage:new TextDecoder().decode(C.signedMessage),x=C.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in P)||typeof P.signMessage!="function"||!("publicKey"in P)||typeof P!="object"||!P.publicKey||!("toBase58"in P.publicKey)||typeof P.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");w=[`${O.host} wants you to sign in with your Solana account:`,P.publicKey.toBase58(),...k?["",k,""]:[""],"Version: 1",`URI: ${O.href}`,`Issued At: ${(i=(n=E==null?void 0:E.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((a=E==null?void 0:E.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${E.signInWithSolana.notBefore}`]:[],...!((s=E==null?void 0:E.signInWithSolana)===null||s===void 0)&&s.expirationTime?[`Expiration Time: ${E.signInWithSolana.expirationTime}`]:[],...!((u=E==null?void 0:E.signInWithSolana)===null||u===void 0)&&u.chainId?[`Chain ID: ${E.signInWithSolana.chainId}`]:[],...!((c=E==null?void 0:E.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${E.signInWithSolana.nonce}`]:[],...!((f=E==null?void 0:E.signInWithSolana)===null||f===void 0)&&f.requestId?[`Request ID: ${E.signInWithSolana.requestId}`]:[],...!((h=(p=E==null?void 0:E.signInWithSolana)===null||p===void 0?void 0:p.resources)===null||h===void 0)&&h.length?["Resources",...E.signInWithSolana.resources.map(C=>`- ${C}`)]:[]].join(`
|
|
199
|
-
`);const A=await P.signMessage(new TextEncoder().encode(w),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");x=A}}try{const{data:y,error:S}=await xe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:w,signature:La(x)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(v=e.options)===null||v===void 0?void 0:v.captchaToken}}:null),xform:Qr});if(S)throw S;if(!y||!y.session||!y.user){const k=new Ro;return this._returnResult({data:{user:null,session:null},error:k})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:S})}catch(y){if(he(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){const r=await Pa(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new YU;const{data:a,error:s}=await xe(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Qr});if(await Yt(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!a||!a.session||!a.user){const u=new Ro;return this._returnResult({data:{user:null,session:null,redirectType:null},error:u})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers(i==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:i??null}),error:s})}catch(a){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:r,provider:n,token:i,access_token:a,nonce:s}=e,u=await xe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:a,nonce:s,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:Qr}),{data:c,error:f}=u;if(f)return this._returnResult({data:{user:null,session:null},error:f});if(!c||!c.session||!c.user){const p=new Ro;return this._returnResult({data:{user:null,session:null},error:p})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:f})}catch(r){if(he(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,a,s;try{if("email"in e){const{email:u,options:c}=e;let f=null,p=null;this.flowType==="pkce"&&([f,p]=await Io(this.storage,this.storageKey));const{error:h}=await xe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:f,code_challenge_method:p},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:u,options:c}=e,{data:f,error:p}=await xe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(i=c==null?void 0:c.data)!==null&&i!==void 0?i:{},create_user:(a=c==null?void 0:c.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(s=c==null?void 0:c.channel)!==null&&s!==void 0?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:f==null?void 0:f.message_id},error:p})}throw new xf("You must provide either an email or phone number.")}catch(u){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async verifyOtp(e){var r,n;try{let i,a;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:s,error:u}=await xe(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:Qr});if(u)throw u;if(!s)throw new Error("An error occurred on token verification.");const c=s.session,f=s.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:f,session:c},error:null})}catch(i){if(he(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,a,s;try{let u=null,c=null;this.flowType==="pkce"&&([u,c]=await Io(this.storage,this.storageKey));const f=await xe(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:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:u,code_challenge_method:c}),headers:this.headers,xform:xq});return!((a=f.data)===null||a===void 0)&&a.url&&Jt()&&!(!((s=e.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(f.data.url),this._returnResult(f)}catch(u){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(u))return this._returnResult({data:null,error:u});throw u}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new Ft;const{error:i}=await xe(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(he(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e,{error:s}=await xe(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:s})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:s,error:u}=await xe(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:s==null?void 0:s.message_id},error:u})}throw new xf("You must provide either an email or phone number and a type")}catch(r){if(he(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}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{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Pa(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()<qm:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const s=await Pa(this.userStorage,this.storageKey+"-user");s!=null&&s.user?e.user=s.user:e.user=Fm()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const s={value:this.suppressGetSessionWarning};e.user=vq(e.user,s),s.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await xe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Qi}):await this._useSession(async r=>{var n,i,a;const{data:s,error:u}=r;if(u)throw u;return!(!((n=s.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ft}:await xe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(i=s.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:Qi})})}catch(r){if(he(r))return wf(r)&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new Ft;const s=i.session;let u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await Io(this.storage,this.storageKey));const{data:f,error:p}=await xe(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:s.access_token,xform:Qi});if(p)throw p;return s.user=f.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(n){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(n))return this._returnResult({data:{user:null},error:n});throw n}}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 Ft;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:s}=Sf(e.access_token);if(s.exp&&(n=s.exp,i=n<=r),i){const{data:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!u)return{data:{user:null,session:null},error:null};a=u}else{const{data:u,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});a={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(r){if(he(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}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 r=>{var n;if(!e){const{data:s,error:u}=r;if(u)throw u;e=(n=s.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Ft;const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(he(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!Jt())throw new _f("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _f(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new xk("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new _f("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new xk("No code detected.");const{data:E,error:P}=await this._exchangeCodeForSession(e.code);if(P)throw P;const O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:E.session,redirectType:(n=E.redirectType)!==null&&n!==void 0?n:null},error:null}}const{provider_token:i,provider_refresh_token:a,access_token:s,refresh_token:u,expires_in:c,expires_at:f,token_type:p}=e;if(!s||!c||!u||!p)throw new _f("No session defined in URL");const h=Math.round(Date.now()/1e3),g=parseInt(c);let v=h+g;f&&(v=parseInt(f));const w=v-h;w*1e3<=Uo&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${w}s, should have been closer to ${g}s`);const x=v-g;h-x>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",x,v,h):h-x<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",x,v,h);const{data:y,error:S}=await this._getUser(s);if(S)throw S;const k={provider_token:i,provider_refresh_token:a,access_token:s,expires_in:g,expires_at:v,refresh_token:u,token_type:p,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(i){if(he(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await Pa(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}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 r=>{var n;const{data:i,error:a}=r;if(a&&!wf(a))return this._returnResult({error:a});const s=(n=i.session)===null||n===void 0?void 0:n.access_token;if(s){const{error:u}=await this.admin.signOut(s,e);if(u&&!(GU(u)&&(u.status===404||u.status===401||u.status===403)||wf(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=nq(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{const{data:{session:a},error:s}=r;if(s)throw s;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),wf(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await Io(this.storage,this.storageKey,!0));try{return await xe(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(a){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:n,error:i}=await this._useSession(async a=>{var s,u,c,f,p;const{data:h,error:g}=a;if(g)throw g;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(s=e.options)===null||s===void 0?void 0:s.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await xe(this.fetch,"GET",v,{headers:this.headers,jwt:(p=(f=h.session)===null||f===void 0?void 0:f.access_token)!==null&&p!==void 0?p:void 0})});if(i)throw i;return Jt()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(he(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{const{error:i,data:{session:a}}=r;if(i)throw i;const{options:s,provider:u,token:c,access_token:f,nonce:p}=e,h=await xe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=a==null?void 0:a.access_token)!==null&&n!==void 0?n:void 0,body:{provider:u,id_token:c,access_token:f,nonce:p,link_identity:!0,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:Qr}),{data:g,error:v}=h;return v?this._returnResult({data:{user:null,session:null},error:v}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new Ro}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:v}))}catch(i){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:s}=r;if(s)throw s;return await xe(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await sq(async i=>(i>0&&await oq(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await xe(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Qr})),(i,a)=>{const s=200*Math.pow(2,i);return a&&zm(a)&&Date.now()+s-n<Uo})}catch(n){if(this._debug(r,"error",n),he(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),Jt()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const i=await Pa(this.storage,this.storageKey);if(i&&this.userStorage){let s=await Pa(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!s&&(s={user:i.user},await qo(this.userStorage,this.storageKey+"-user",s)),i.user=(e=s==null?void 0:s.user)!==null&&e!==void 0?e:Fm()}else if(i&&!i.user&&!i.user){const s=await Pa(this.storage,this.storageKey+"-user");s&&(s!=null&&s.user)?(i.user=s.user,await Yt(this.storage,this.storageKey+"-user"),await qo(this.storage,this.storageKey,i)):i.user=Fm()}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}const a=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<qm;if(this._debug(n,`session has${a?"":" not"} expired with margin of ${qm}s`),a){if(this.autoRefreshToken&&i.refresh_token){const{error:s}=await this._callRefreshToken(i.refresh_token);s&&(console.error(s),zm(s)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",s),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:s,error:u}=await this._getUser(i.access_token);!u&&(s!=null&&s.user)?(i.user=s.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(s){console.error("Error getting user data:",s),this._debug(n,"error getting user data, skipping SIGNED_IN notification",s)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new Ft;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new lh;const{data:a,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!a.session)throw new Ft;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const u={data:a.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(a){if(this._debug(i,"error",a),he(a)){const s={data:null,error:a};return zm(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(s),s}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(a),a}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,n=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});const a=[],s=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,r)}catch(c){a.push(c)}});if(await Promise.all(s),a.length>0){for(let u=0;u<a.length;u+=1)console.error(a[u]);throw a[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Yt(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await qo(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const a=Ek(i);await qo(this.storage,this.storageKey,a)}else{const i=Ek(r);await qo(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Yt(this.storage,this.storageKey),await Yt(this.storage,this.storageKey+"-code-verifier"),await Yt(this.storage,this.storageKey+"-user"),this.userStorage&&await Yt(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Jt()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Uo);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((n.expires_at*1e3-e)/Uo);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Uo}ms, refresh threshold is ${u0} ticks`),i<=u0&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof VR)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Jt()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const i=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[a,s]=await Io(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(s)}`});i.push(u.toString())}if(n!=null&&n.queryParams){const a=new URLSearchParams(n.queryParams);i.push(a.toString())}return n!=null&&n.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;return a?this._returnResult({data:null,error:a}):await xe(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:s}=r;if(s)return this._returnResult({data:null,error:s});const u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:f}=await xe(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return f?this._returnResult({data:null,error:f}):(e.factorType==="totp"&&c.type==="totp"&&(!((i=c==null?void 0:c.totp)===null||i===void 0)&&i.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const s=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?$k(e.webauthn.credential_response):Nk(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await xe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:s,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+u.expires_in},u)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:u,error:c}))})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const s=await xe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});if(s.error)return s;const{data:u}=s;if(u.type!=="webauthn")return{data:u,error:null};switch(u.webauthn.type){case"create":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:Rk(u.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:Ik(u.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};const i={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])i.all.push(a),a.status==="verified"&&i[a.factor_type].push(a);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,a;if(e)try{const{payload:v}=Sf(e);let w=null;v.aal&&(w=v.aal);let x=w;const{data:{user:y},error:S}=await this.getUser(e);if(S)return this._returnResult({data:null,error:S});((n=(r=y==null?void 0:y.factors)===null||r===void 0?void 0:r.filter(P=>P.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(x="aal2");const E=v.amr||[];return{data:{currentLevel:w,nextLevel:x,currentAuthenticationMethods:E},error:null}}catch(v){if(he(v))return this._returnResult({data:null,error:v});throw v}const{data:{session:s},error:u}=await this.getSession();if(u)return this._returnResult({data:null,error:u});if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Sf(s.access_token);let f=null;c.aal&&(f=c.aal);let p=f;((a=(i=s.user.factors)===null||i===void 0?void 0:i.filter(v=>v.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(p="aal2");const g=c.amr||[];return{data:{currentLevel:f,nextLevel:p,currentAuthenticationMethods:g},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await xe(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new Ft})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new Ft});const s=await xe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:u=>({data:u,error:null})});return s.data&&s.data.redirect_url&&Jt()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new Ft});const s=await xe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:u=>({data:u,error:null})});return s.data&&s.data.redirect_url&&Jt()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await xe(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Ft})})}catch(e){if(he(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await xe(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ft})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(u=>u.kid===e);if(n)return n;const i=Date.now();if(n=this.jwks.keys.find(u=>u.kid===e),n&&this.jwks_cached_at+VU>i)return n;const{data:a,error:s}=await xe(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=i,n=a.keys.find(u=>u.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:v,error:w}=await this.getSession();if(w||!v.session)return this._returnResult({data:null,error:w});n=v.session.access_token}const{header:i,payload:a,signature:s,raw:{header:u,payload:c}}=Sf(n);r!=null&&r.allowExpired||pq(a.exp);const f=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!f){const{error:v}=await this.getUser(n);if(v)throw v;return{data:{claims:a,header:i,signature:s},error:null}}const p=mq(i.alg),h=await crypto.subtle.importKey("jwk",f,p,!0,["verify"]);if(!await crypto.subtle.verify(p,h,s,tq(`${u}.${c}`)))throw new d0("Invalid JWT signature");return{data:{claims:a,header:i,signature:s},error:null}}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,i;mn(this.experimental);try{if(!Qf())return this._returnResult({data:null,error:new xn("Browser does not support WebAuthn",null)});const{data:a,error:s}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(s||!a)return this._returnResult({data:null,error:s});const u=Ik(a.options),c=(i=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.signal)!==null&&i!==void 0?i:h0.createNewAbortSignal(),{data:f,error:p}=await YR({publicKey:u,signal:c});if(p||!f)return this._returnResult({data:null,error:p??new xn("WebAuthn ceremony failed",null)});const h=Nk(f);return this._verifyPasskeyAuthentication({challengeId:a.challenge_id,credential:h})}catch(a){if(he(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(e){var r,n;mn(this.experimental);try{if(!Qf())return this._returnResult({data:null,error:new xn("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyRegistration();if(a||!i)return this._returnResult({data:null,error:a});const s=Rk(i.options),u=(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:h0.createNewAbortSignal(),{data:c,error:f}=await XR({publicKey:s,signal:u});if(f||!c)return this._returnResult({data:null,error:f??new xn("WebAuthn ceremony failed",null)});const p=$k(c);return this._verifyPasskeyRegistration({challengeId:i.challenge_id,credential:p})}catch(i){if(he(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyRegistration(){mn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new Ft});const{data:i,error:a}=await xe(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(he(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){mn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Ft});const{data:a,error:s}=await xe(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:a,error:null})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;mn(this.experimental);try{const{data:n,error:i}=await xe(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){mn(this.experimental);try{const{data:r,error:n}=await xe(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Qr});return n?this._returnResult({data:null,error:n}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){mn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new Ft});const{data:i,error:a}=await xe(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(he(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){mn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Ft});const{data:a,error:s}=await xe(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:a,error:null})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){mn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Ft});const{error:a}=await xe(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return a?this._returnResult({data:null,error:a}):this._returnResult({data:null,error:null})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}}su.nextInstanceID={};const Bq=su,Uq="2.106.2";let zl="";typeof Deno<"u"?zl="deno":typeof document<"u"?zl="web":typeof navigator<"u"&&navigator.product==="ReactNative"?zl="react-native":zl="node";const qq={"X-Client-Info":`supabase-js-${zl}/${Uq}`},zq={headers:qq},Fq={schema:"public"},Wq={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Hq={},Vq={enabled:!1,respectSamplingDecision:!0};function Kq(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function u(p){try{f(n.next(p))}catch(h){s(h)}}function c(p){try{f(n.throw(p))}catch(h){s(h)}}function f(p){p.done?a(p.value):i(p.value).then(u,c)}f((n=n.apply(t,[])).next())})}let Hm=null;const Gq="@opentelemetry/api";function Xq(){return Hm===null&&(Hm=import(Gq).catch(()=>null)),Hm}function Yq(){return Kq(this,void 0,void 0,function*(){try{const t=yield Xq();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function Jq(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,n,i,a]=e;if(r.length!==2||n.length!==32||i.length!==16||a.length!==2)return null;const s=/^[0-9a-f]+$/i;return!s.test(r)||!s.test(n)||!s.test(i)||!s.test(a)||n==="00000000000000000000000000000000"||i==="0000000000000000"?null:{version:r,traceId:n,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)===1}}function Qq(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const n of e)try{if(typeof n=="string"){if(Zq(r.hostname,n))return!0}else if(n instanceof RegExp){if(n.test(r.hostname))return!0}else if(typeof n=="function"&&n(r))return!0}catch{continue}return!1}function Zq(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function e8(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function lu(t){"@babel/helpers - typeof";return lu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lu(t)}function t8(t,e){if(lu(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(lu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function r8(t){var e=t8(t,"string");return lu(e)=="symbol"?e:e+""}function n8(t,e,r){return(e=r8(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Lk(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function yt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Lk(Object(r),!0).forEach(function(n){n8(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Lk(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}const i8=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),a8=()=>Headers,o8=(t,e,r,n,i)=>{const a=i8(n),s=a8(),u=(i==null?void 0:i.enabled)===!0,c=(i==null?void 0:i.respectSamplingDecision)!==!1,f=u?e8(e):null;return async(p,h)=>{var g;const v=(g=await r())!==null&&g!==void 0?g:t;let w=new s(h==null?void 0:h.headers);if(w.has("apikey")||w.set("apikey",t),w.has("Authorization")||w.set("Authorization",`Bearer ${v}`),f){const x=await s8(p,f,c);x&&(x.traceparent&&!w.has("traceparent")&&w.set("traceparent",x.traceparent),x.tracestate&&!w.has("tracestate")&&w.set("tracestate",x.tracestate),x.baggage&&!w.has("baggage")&&w.set("baggage",x.baggage))}return a(p,yt(yt({},h),{},{headers:w}))}};async function s8(t,e,r){if(!Qq(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=await Yq();if(!n||!n.traceparent)return null;if(r){const i=Jq(n.traceparent);if(i&&!i.isSampled)return null}return n}function Dk(t){return typeof t=="boolean"?{enabled:t}:t}function l8(t){return t.endsWith("/")?t:t+"/"}function u8(t,e){var r,n,i,a,s,u;const{db:c,auth:f,realtime:p,global:h}=t,{db:g,auth:v,realtime:w,global:x}=e,y=Dk(t.tracePropagation),S=Dk(e.tracePropagation),k={db:yt(yt({},g),c),auth:yt(yt({},v),f),realtime:yt(yt({},w),p),storage:{},global:yt(yt(yt({},x),h),{},{headers:yt(yt({},(r=x==null?void 0:x.headers)!==null&&r!==void 0?r:{}),(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(i=(a=y==null?void 0:y.enabled)!==null&&a!==void 0?a:S==null?void 0:S.enabled)!==null&&i!==void 0?i:!1,respectSamplingDecision:(s=(u=y==null?void 0:y.respectSamplingDecision)!==null&&u!==void 0?u:S==null?void 0:S.respectSamplingDecision)!==null&&s!==void 0?s:!0},accessToken:async()=>""};return t.accessToken?k.accessToken=t.accessToken:delete k.accessToken,k}function c8(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(l8(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var f8=class extends Bq{constructor(t){super(t)}},d8=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;const a=c8(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const s=`sb-${a.hostname.split(".")[0]}-auth-token`,u={db:Fq,realtime:Hq,auth:yt(yt({},Wq),{},{storageKey:s}),global:zq,tracePropagation:Vq},c=u8(r??{},u);if(this.settings=c,this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=c.global.headers)!==null&&i!==void 0?i:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(p,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var f;this.auth=this._initSupabaseAuthClient((f=c.auth)!==null&&f!==void 0?f:{},this.headers,c.global.fetch)}this.fetch=o8(e,t,this._getAccessToken.bind(this),c.global.fetch,c.tracePropagation),this.realtime=this._initRealtimeClient(yt({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(p=>this.realtime.setAuth(p)).catch(p=>console.warn("Failed to set initial Realtime auth token:",p)),this.rest=new P4(new URL("rest/v1",a).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new qU(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new y4(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:a,flowType:s,lock:u,debug:c,throwOnError:f,experimental:p,lockAcquireTimeout:h,skipAutoInitialize:g},v,w){const x={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new f8({url:this.authUrl.href,headers:yt(yt({},x),v),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:s,lock:u,debug:c,throwOnError:f,experimental:p,fetch:w,lockAcquireTimeout:h,skipAutoInitialize:g,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new cU(this.realtimeUrl.href,yt(yt({},t),{},{params:yt(yt({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const h8=(t,e,r)=>new d8(t,e,r);function p8(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}p8()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const m8="/api";let Fa=null;function g8(t){Fa=t}function v8(){return(Fa==null?void 0:Fa())??null}async function Tl(t,e){const r=Fa==null?void 0:Fa(),n={"Content-Type":"application/json",...e==null?void 0:e.headers};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${m8}${t}`,{...e,headers:n});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error??`Request failed: ${i.status}`)}return i.json()}const Pt={get:t=>Tl(t),post:(t,e)=>Tl(t,{method:"POST",body:e?JSON.stringify(e):void 0}),patch:(t,e)=>Tl(t,{method:"PATCH",body:JSON.stringify(e)}),put:(t,e)=>Tl(t,{method:"PUT",body:JSON.stringify(e)}),delete:t=>Tl(t,{method:"DELETE"})},JR=$.createContext({session:null,supabase:null,loading:!0,signIn:async()=>({error:"Not initialized"}),signOut:async()=>{}});function QR(){return $.useContext(JR)}function y8({children:t}){const[e,r]=$.useState(null),[n,i]=$.useState(null),[a,s]=$.useState(!0),u=$.useRef(null);$.useEffect(()=>{u.current=n},[n]),$.useEffect(()=>{g8(()=>{var p;return((p=u.current)==null?void 0:p.access_token)??null})},[]),$.useEffect(()=>{Pt.get("/config").then(({config:p})=>{if(p.supabase.projectUrl&&p.supabase.anonKey){const h=h8(p.supabase.projectUrl,p.supabase.anonKey);r(h),h.auth.getSession().then(({data:v})=>{i(v.session),s(!1)});const{data:{subscription:g}}=h.auth.onAuthStateChange((v,w)=>{i(w)});return()=>g.unsubscribe()}s(!1)}).catch(()=>{s(!1)})},[]);async function c(p,h){if(!e)return{error:"Supabase not configured"};const{error:g}=await e.auth.signInWithPassword({email:p,password:h});return{error:(g==null?void 0:g.message)??null}}async function f(){e&&(await e.auth.signOut(),i(null))}return j.jsx(JR.Provider,{value:{session:n,supabase:e,loading:a,signIn:c,signOut:f},children:t})}function b8(t={}){const[e,r]=$.useState(!1),[n,i]=$.useState(null),a=$.useRef(null),s=$.useRef(t);s.current=t,$.useEffect(()=>{let f=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;const p=v8();p&&(f+=`?token=${encodeURIComponent(p)}`);let h,g;function v(){h=new WebSocket(f),h.onopen=()=>{r(!0)},h.onmessage=w=>{var x,y,S,k,E,P,O,A;try{const C=JSON.parse(w.data);switch(C.type){case"connected":i(C.connectionId??null);break;case"delta":(y=(x=s.current).onDelta)==null||y.call(x,C.content??"");break;case"message":(k=(S=s.current).onMessage)==null||k.call(S,C.content??"");break;case"event":(P=(E=s.current).onEvent)==null||P.call(E,C);break;case"error":(A=(O=s.current).onError)==null||A.call(O,C.content??"Unknown error");break}}catch{}},h.onclose=()=>{r(!1),i(null),g=setTimeout(v,3e3)},h.onerror=()=>{h.close()},a.current=h}return v(),()=>{clearTimeout(g),h==null||h.close()}},[]);const u=$.useCallback((c,f="web")=>{var p;((p=a.current)==null?void 0:p.readyState)===WebSocket.OPEN&&a.current.send(JSON.stringify({type:"message",content:c,source:f}))},[]);return{connected:e,connectionId:n,sendMessage:u}}function Qw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Za=Qw();function ZR(t){Za=t}var Na={exec:()=>null};function No(t){let e=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=e[n];return i||(i=t(n),e[n]=i),i}}function qe(t,e=""){let r=typeof t=="string"?t:t.source,n={replace:(i,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(lr.caret,"$1"),r=r.replace(i,s),n},getRegex:()=>new RegExp(r,e)};return n}var w8=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),lr={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:No(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:No(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:No(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:No(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:No(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:No(t=>new RegExp(`^ {0,${t}}>`))},x8=/^(?:[ \t]*(?:\n|$))+/,_8=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,S8=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ku=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,k8=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zw=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,e2=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,t2=qe(e2).replace(/bull/g,Zw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),O8=qe(e2).replace(/bull/g,Zw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ex=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,E8=/^[^\n]+/,tx=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,A8=qe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",tx).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),P8=qe(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Zw).getRegex(),uh="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",rx=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,T8=qe("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",rx).replace("tag",uh).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),r2=qe(ex).replace("hr",Ku).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",uh).getRegex(),C8=qe(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",r2).getRegex(),nx={blockquote:C8,code:_8,def:A8,fences:S8,heading:k8,hr:Ku,html:T8,lheading:t2,list:P8,newline:x8,paragraph:r2,table:Na,text:E8},Bk=qe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ku).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",uh).getRegex(),j8={...nx,lheading:O8,table:Bk,paragraph:qe(ex).replace("hr",Ku).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Bk).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",uh).getRegex()},R8={...nx,html:qe(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",rx).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Na,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:qe(ex).replace("hr",Ku).replace("heading",` *#{1,6} *[^
|
|
199
|
+
`);const A=await P.signMessage(new TextEncoder().encode(w),"utf8");if(!A||!(A instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");x=A}}try{const{data:y,error:S}=await xe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:w,signature:La(x)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(v=e.options)===null||v===void 0?void 0:v.captchaToken}}:null),xform:Qr});if(S)throw S;if(!y||!y.session||!y.user){const k=new Ro;return this._returnResult({data:{user:null,session:null},error:k})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:S})}catch(y){if(he(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){const r=await Pa(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new YU;const{data:a,error:s}=await xe(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Qr});if(await Yt(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!a||!a.session||!a.user){const u=new Ro;return this._returnResult({data:{user:null,session:null,redirectType:null},error:u})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers(i==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:i??null}),error:s})}catch(a){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:r,provider:n,token:i,access_token:a,nonce:s}=e,u=await xe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:a,nonce:s,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:Qr}),{data:c,error:f}=u;if(f)return this._returnResult({data:{user:null,session:null},error:f});if(!c||!c.session||!c.user){const p=new Ro;return this._returnResult({data:{user:null,session:null},error:p})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:f})}catch(r){if(he(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,a,s;try{if("email"in e){const{email:u,options:c}=e;let f=null,p=null;this.flowType==="pkce"&&([f,p]=await Io(this.storage,this.storageKey));const{error:h}=await xe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:f,code_challenge_method:p},redirectTo:c==null?void 0:c.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:u,options:c}=e,{data:f,error:p}=await xe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(i=c==null?void 0:c.data)!==null&&i!==void 0?i:{},create_user:(a=c==null?void 0:c.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(s=c==null?void 0:c.channel)!==null&&s!==void 0?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:f==null?void 0:f.message_id},error:p})}throw new xf("You must provide either an email or phone number.")}catch(u){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async verifyOtp(e){var r,n;try{let i,a;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:s,error:u}=await xe(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:Qr});if(u)throw u;if(!s)throw new Error("An error occurred on token verification.");const c=s.session,f=s.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:f,session:c},error:null})}catch(i){if(he(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,a,s;try{let u=null,c=null;this.flowType==="pkce"&&([u,c]=await Io(this.storage,this.storageKey));const f=await xe(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:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:u,code_challenge_method:c}),headers:this.headers,xform:xq});return!((a=f.data)===null||a===void 0)&&a.url&&Jt()&&!(!((s=e.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(f.data.url),this._returnResult(f)}catch(u){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(u))return this._returnResult({data:null,error:u});throw u}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new Ft;const{error:i}=await xe(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(he(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e,{error:s}=await xe(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:s})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:s,error:u}=await xe(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:s==null?void 0:s.message_id},error:u})}throw new xf("You must provide either an email or phone number and a type")}catch(r){if(he(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}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{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Pa(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()<qm:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const s=await Pa(this.userStorage,this.storageKey+"-user");s!=null&&s.user?e.user=s.user:e.user=Fm()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const s={value:this.suppressGetSessionWarning};e.user=vq(e.user,s),s.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await xe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Qi}):await this._useSession(async r=>{var n,i,a;const{data:s,error:u}=r;if(u)throw u;return!(!((n=s.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ft}:await xe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(i=s.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:Qi})})}catch(r){if(he(r))return wf(r)&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new Ft;const s=i.session;let u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await Io(this.storage,this.storageKey));const{data:f,error:p}=await xe(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:s.access_token,xform:Qi});if(p)throw p;return s.user=f.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(n){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(n))return this._returnResult({data:{user:null},error:n});throw n}}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 Ft;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:s}=Sf(e.access_token);if(s.exp&&(n=s.exp,i=n<=r),i){const{data:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!u)return{data:{user:null,session:null},error:null};a=u}else{const{data:u,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});a={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(r){if(he(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}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 r=>{var n;if(!e){const{data:s,error:u}=r;if(u)throw u;e=(n=s.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new Ft;const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(he(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!Jt())throw new _f("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _f(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new xk("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new _f("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new xk("No code detected.");const{data:E,error:P}=await this._exchangeCodeForSession(e.code);if(P)throw P;const O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:E.session,redirectType:(n=E.redirectType)!==null&&n!==void 0?n:null},error:null}}const{provider_token:i,provider_refresh_token:a,access_token:s,refresh_token:u,expires_in:c,expires_at:f,token_type:p}=e;if(!s||!c||!u||!p)throw new _f("No session defined in URL");const h=Math.round(Date.now()/1e3),g=parseInt(c);let v=h+g;f&&(v=parseInt(f));const w=v-h;w*1e3<=Uo&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${w}s, should have been closer to ${g}s`);const x=v-g;h-x>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",x,v,h):h-x<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",x,v,h);const{data:y,error:S}=await this._getUser(s);if(S)throw S;const k={provider_token:i,provider_refresh_token:a,access_token:s,expires_in:g,expires_at:v,refresh_token:u,token_type:p,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(i){if(he(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await Pa(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}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 r=>{var n;const{data:i,error:a}=r;if(a&&!wf(a))return this._returnResult({error:a});const s=(n=i.session)===null||n===void 0?void 0:n.access_token;if(s){const{error:u}=await this.admin.signOut(s,e);if(u&&!(GU(u)&&(u.status===404||u.status===401||u.status===403)||wf(u)))return this._returnResult({error:u})}return e!=="others"&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=nq(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{const{data:{session:a},error:s}=r;if(s)throw s;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),wf(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await Io(this.storage,this.storageKey,!0));try{return await xe(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(a){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:n,error:i}=await this._useSession(async a=>{var s,u,c,f,p;const{data:h,error:g}=a;if(g)throw g;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(s=e.options)===null||s===void 0?void 0:s.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await xe(this.fetch,"GET",v,{headers:this.headers,jwt:(p=(f=h.session)===null||f===void 0?void 0:f.access_token)!==null&&p!==void 0?p:void 0})});if(i)throw i;return Jt()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(he(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{const{error:i,data:{session:a}}=r;if(i)throw i;const{options:s,provider:u,token:c,access_token:f,nonce:p}=e,h=await xe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=a==null?void 0:a.access_token)!==null&&n!==void 0?n:void 0,body:{provider:u,id_token:c,access_token:f,nonce:p,link_identity:!0,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:Qr}),{data:g,error:v}=h;return v?this._returnResult({data:{user:null,session:null},error:v}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new Ro}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:v}))}catch(i){if(await Yt(this.storage,`${this.storageKey}-code-verifier`),he(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:s}=r;if(s)throw s;return await xe(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await sq(async i=>(i>0&&await oq(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await xe(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Qr})),(i,a)=>{const s=200*Math.pow(2,i);return a&&zm(a)&&Date.now()+s-n<Uo})}catch(n){if(this._debug(r,"error",n),he(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),Jt()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const i=await Pa(this.storage,this.storageKey);if(i&&this.userStorage){let s=await Pa(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!s&&(s={user:i.user},await qo(this.userStorage,this.storageKey+"-user",s)),i.user=(e=s==null?void 0:s.user)!==null&&e!==void 0?e:Fm()}else if(i&&!i.user&&!i.user){const s=await Pa(this.storage,this.storageKey+"-user");s&&(s!=null&&s.user)?(i.user=s.user,await Yt(this.storage,this.storageKey+"-user"),await qo(this.storage,this.storageKey,i)):i.user=Fm()}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}const a=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<qm;if(this._debug(n,`session has${a?"":" not"} expired with margin of ${qm}s`),a){if(this.autoRefreshToken&&i.refresh_token){const{error:s}=await this._callRefreshToken(i.refresh_token);s&&(console.error(s),zm(s)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",s),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:s,error:u}=await this._getUser(i.access_token);!u&&(s!=null&&s.user)?(i.user=s.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(s){console.error("Error getting user data:",s),this._debug(n,"error getting user data, skipping SIGNED_IN notification",s)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new Ft;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new lh;const{data:a,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!a.session)throw new Ft;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const u={data:a.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(a){if(this._debug(i,"error",a),he(a)){const s={data:null,error:a};return zm(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(s),s}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(a),a}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,n=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});const a=[],s=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,r)}catch(c){a.push(c)}});if(await Promise.all(s),a.length>0){for(let u=0;u<a.length;u+=1)console.error(a[u]);throw a[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Yt(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await qo(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const a=Ek(i);await qo(this.storage,this.storageKey,a)}else{const i=Ek(r);await qo(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Yt(this.storage,this.storageKey),await Yt(this.storage,this.storageKey+"-code-verifier"),await Yt(this.storage,this.storageKey+"-user"),this.userStorage&&await Yt(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Jt()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Uo);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((n.expires_at*1e3-e)/Uo);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Uo}ms, refresh threshold is ${u0} ticks`),i<=u0&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof VR)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Jt()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const i=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[a,s]=await Io(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(s)}`});i.push(u.toString())}if(n!=null&&n.queryParams){const a=new URLSearchParams(n.queryParams);i.push(a.toString())}return n!=null&&n.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;return a?this._returnResult({data:null,error:a}):await xe(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:s}=r;if(s)return this._returnResult({data:null,error:s});const u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:f}=await xe(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return f?this._returnResult({data:null,error:f}):(e.factorType==="totp"&&c.type==="totp"&&(!((i=c==null?void 0:c.totp)===null||i===void 0)&&i.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const s=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?$k(e.webauthn.credential_response):Nk(e.webauthn.credential_response)})}:{code:e.code}),{data:u,error:c}=await xe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:s,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+u.expires_in},u)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",u),this._returnResult({data:u,error:c}))})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const s=await xe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});if(s.error)return s;const{data:u}=s;if(u.type!=="webauthn")return{data:u,error:null};switch(u.webauthn.type){case"create":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:Rk(u.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},u),{webauthn:Object.assign(Object.assign({},u.webauthn),{credential_options:Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:Ik(u.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};const i={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])i.all.push(a),a.status==="verified"&&i[a.factor_type].push(a);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,a;if(e)try{const{payload:v}=Sf(e);let w=null;v.aal&&(w=v.aal);let x=w;const{data:{user:y},error:S}=await this.getUser(e);if(S)return this._returnResult({data:null,error:S});((n=(r=y==null?void 0:y.factors)===null||r===void 0?void 0:r.filter(P=>P.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(x="aal2");const E=v.amr||[];return{data:{currentLevel:w,nextLevel:x,currentAuthenticationMethods:E},error:null}}catch(v){if(he(v))return this._returnResult({data:null,error:v});throw v}const{data:{session:s},error:u}=await this.getSession();if(u)return this._returnResult({data:null,error:u});if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=Sf(s.access_token);let f=null;c.aal&&(f=c.aal);let p=f;((a=(i=s.user.factors)===null||i===void 0?void 0:i.filter(v=>v.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(p="aal2");const g=c.amr||[];return{data:{currentLevel:f,nextLevel:p,currentAuthenticationMethods:g},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await xe(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new Ft})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new Ft});const s=await xe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:u=>({data:u,error:null})});return s.data&&s.data.redirect_url&&Jt()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new Ft});const s=await xe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:u=>({data:u,error:null})});return s.data&&s.data.redirect_url&&Jt()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await xe(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Ft})})}catch(e){if(he(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await xe(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ft})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(u=>u.kid===e);if(n)return n;const i=Date.now();if(n=this.jwks.keys.find(u=>u.kid===e),n&&this.jwks_cached_at+VU>i)return n;const{data:a,error:s}=await xe(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=i,n=a.keys.find(u=>u.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:v,error:w}=await this.getSession();if(w||!v.session)return this._returnResult({data:null,error:w});n=v.session.access_token}const{header:i,payload:a,signature:s,raw:{header:u,payload:c}}=Sf(n);r!=null&&r.allowExpired||pq(a.exp);const f=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!f){const{error:v}=await this.getUser(n);if(v)throw v;return{data:{claims:a,header:i,signature:s},error:null}}const p=mq(i.alg),h=await crypto.subtle.importKey("jwk",f,p,!0,["verify"]);if(!await crypto.subtle.verify(p,h,s,tq(`${u}.${c}`)))throw new d0("Invalid JWT signature");return{data:{claims:a,header:i,signature:s},error:null}}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,i;mn(this.experimental);try{if(!Qf())return this._returnResult({data:null,error:new xn("Browser does not support WebAuthn",null)});const{data:a,error:s}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(s||!a)return this._returnResult({data:null,error:s});const u=Ik(a.options),c=(i=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.signal)!==null&&i!==void 0?i:h0.createNewAbortSignal(),{data:f,error:p}=await YR({publicKey:u,signal:c});if(p||!f)return this._returnResult({data:null,error:p??new xn("WebAuthn ceremony failed",null)});const h=Nk(f);return this._verifyPasskeyAuthentication({challengeId:a.challenge_id,credential:h})}catch(a){if(he(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(e){var r,n;mn(this.experimental);try{if(!Qf())return this._returnResult({data:null,error:new xn("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyRegistration();if(a||!i)return this._returnResult({data:null,error:a});const s=Rk(i.options),u=(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:h0.createNewAbortSignal(),{data:c,error:f}=await XR({publicKey:s,signal:u});if(f||!c)return this._returnResult({data:null,error:f??new xn("WebAuthn ceremony failed",null)});const p=$k(c);return this._verifyPasskeyRegistration({challengeId:i.challenge_id,credential:p})}catch(i){if(he(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyRegistration(){mn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new Ft});const{data:i,error:a}=await xe(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(he(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){mn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Ft});const{data:a,error:s}=await xe(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:a,error:null})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;mn(this.experimental);try{const{data:n,error:i}=await xe(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})}catch(n){if(he(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){mn(this.experimental);try{const{data:r,error:n}=await xe(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Qr});return n?this._returnResult({data:null,error:n}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){mn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new Ft});const{data:i,error:a}=await xe(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(he(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){mn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Ft});const{data:a,error:s}=await xe(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:a,error:null})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){mn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Ft});const{error:a}=await xe(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return a?this._returnResult({data:null,error:a}):this._returnResult({data:null,error:null})})}catch(r){if(he(r))return this._returnResult({data:null,error:r});throw r}}}su.nextInstanceID={};const Bq=su,Uq="2.106.2";let zl="";typeof Deno<"u"?zl="deno":typeof document<"u"?zl="web":typeof navigator<"u"&&navigator.product==="ReactNative"?zl="react-native":zl="node";const qq={"X-Client-Info":`supabase-js-${zl}/${Uq}`},zq={headers:qq},Fq={schema:"public"},Wq={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Hq={},Vq={enabled:!1,respectSamplingDecision:!0};function Kq(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function u(p){try{f(n.next(p))}catch(h){s(h)}}function c(p){try{f(n.throw(p))}catch(h){s(h)}}function f(p){p.done?a(p.value):i(p.value).then(u,c)}f((n=n.apply(t,[])).next())})}let Hm=null;const Gq="@opentelemetry/api";function Xq(){return Hm===null&&(Hm=import(Gq).catch(()=>null)),Hm}function Yq(){return Kq(this,void 0,void 0,function*(){try{const t=yield Xq();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function Jq(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,n,i,a]=e;if(r.length!==2||n.length!==32||i.length!==16||a.length!==2)return null;const s=/^[0-9a-f]+$/i;return!s.test(r)||!s.test(n)||!s.test(i)||!s.test(a)||n==="00000000000000000000000000000000"||i==="0000000000000000"?null:{version:r,traceId:n,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)===1}}function Qq(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const n of e)try{if(typeof n=="string"){if(Zq(r.hostname,n))return!0}else if(n instanceof RegExp){if(n.test(r.hostname))return!0}else if(typeof n=="function"&&n(r))return!0}catch{continue}return!1}function Zq(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function e8(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function lu(t){"@babel/helpers - typeof";return lu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lu(t)}function t8(t,e){if(lu(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(lu(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function r8(t){var e=t8(t,"string");return lu(e)=="symbol"?e:e+""}function n8(t,e,r){return(e=r8(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Lk(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function yt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Lk(Object(r),!0).forEach(function(n){n8(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Lk(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}const i8=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),a8=()=>Headers,o8=(t,e,r,n,i)=>{const a=i8(n),s=a8(),u=(i==null?void 0:i.enabled)===!0,c=(i==null?void 0:i.respectSamplingDecision)!==!1,f=u?e8(e):null;return async(p,h)=>{var g;const v=(g=await r())!==null&&g!==void 0?g:t;let w=new s(h==null?void 0:h.headers);if(w.has("apikey")||w.set("apikey",t),w.has("Authorization")||w.set("Authorization",`Bearer ${v}`),f){const x=await s8(p,f,c);x&&(x.traceparent&&!w.has("traceparent")&&w.set("traceparent",x.traceparent),x.tracestate&&!w.has("tracestate")&&w.set("tracestate",x.tracestate),x.baggage&&!w.has("baggage")&&w.set("baggage",x.baggage))}return a(p,yt(yt({},h),{},{headers:w}))}};async function s8(t,e,r){if(!Qq(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=await Yq();if(!n||!n.traceparent)return null;if(r){const i=Jq(n.traceparent);if(i&&!i.isSampled)return null}return n}function Dk(t){return typeof t=="boolean"?{enabled:t}:t}function l8(t){return t.endsWith("/")?t:t+"/"}function u8(t,e){var r,n,i,a,s,u;const{db:c,auth:f,realtime:p,global:h}=t,{db:g,auth:v,realtime:w,global:x}=e,y=Dk(t.tracePropagation),S=Dk(e.tracePropagation),k={db:yt(yt({},g),c),auth:yt(yt({},v),f),realtime:yt(yt({},w),p),storage:{},global:yt(yt(yt({},x),h),{},{headers:yt(yt({},(r=x==null?void 0:x.headers)!==null&&r!==void 0?r:{}),(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(i=(a=y==null?void 0:y.enabled)!==null&&a!==void 0?a:S==null?void 0:S.enabled)!==null&&i!==void 0?i:!1,respectSamplingDecision:(s=(u=y==null?void 0:y.respectSamplingDecision)!==null&&u!==void 0?u:S==null?void 0:S.respectSamplingDecision)!==null&&s!==void 0?s:!0},accessToken:async()=>""};return t.accessToken?k.accessToken=t.accessToken:delete k.accessToken,k}function c8(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(l8(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var f8=class extends Bq{constructor(t){super(t)}},d8=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;const a=c8(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const s=`sb-${a.hostname.split(".")[0]}-auth-token`,u={db:Fq,realtime:Hq,auth:yt(yt({},Wq),{},{storageKey:s}),global:zq,tracePropagation:Vq},c=u8(r??{},u);if(this.settings=c,this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=c.global.headers)!==null&&i!==void 0?i:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(p,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var f;this.auth=this._initSupabaseAuthClient((f=c.auth)!==null&&f!==void 0?f:{},this.headers,c.global.fetch)}this.fetch=o8(e,t,this._getAccessToken.bind(this),c.global.fetch,c.tracePropagation),this.realtime=this._initRealtimeClient(yt({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(p=>this.realtime.setAuth(p)).catch(p=>console.warn("Failed to set initial Realtime auth token:",p)),this.rest=new P4(new URL("rest/v1",a).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new qU(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new y4(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:a,flowType:s,lock:u,debug:c,throwOnError:f,experimental:p,lockAcquireTimeout:h,skipAutoInitialize:g},v,w){const x={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new f8({url:this.authUrl.href,headers:yt(yt({},x),v),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:s,lock:u,debug:c,throwOnError:f,experimental:p,fetch:w,lockAcquireTimeout:h,skipAutoInitialize:g,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new cU(this.realtimeUrl.href,yt(yt({},t),{},{params:yt(yt({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const h8=(t,e,r)=>new d8(t,e,r);function p8(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}p8()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const m8="/api";let Fa=null;function g8(t){Fa=t}function v8(){return(Fa==null?void 0:Fa())??null}async function Tl(t,e){const r=Fa==null?void 0:Fa(),n={"Content-Type":"application/json",...e==null?void 0:e.headers};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${m8}${t}`,{...e,headers:n});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error??`Request failed: ${i.status}`)}return i.json()}const Pt={get:t=>Tl(t),post:(t,e)=>Tl(t,{method:"POST",body:e?JSON.stringify(e):void 0}),patch:(t,e)=>Tl(t,{method:"PATCH",body:JSON.stringify(e)}),put:(t,e)=>Tl(t,{method:"PUT",body:JSON.stringify(e)}),delete:t=>Tl(t,{method:"DELETE"})},JR=$.createContext({session:null,supabase:null,loading:!0,signIn:async()=>({error:"Not initialized"}),signOut:async()=>{}});function QR(){return $.useContext(JR)}function y8({children:t}){const[e,r]=$.useState(null),[n,i]=$.useState(null),[a,s]=$.useState(!0),u=$.useRef(null);$.useEffect(()=>{g8(()=>{var p;return((p=u.current)==null?void 0:p.access_token)??null})},[]),$.useEffect(()=>{Pt.get("/config").then(({config:p})=>{if(p.supabase.projectUrl&&p.supabase.anonKey){const h=h8(p.supabase.projectUrl,p.supabase.anonKey);r(h),h.auth.getSession().then(({data:v})=>{u.current=v.session,i(v.session),s(!1)});const{data:{subscription:g}}=h.auth.onAuthStateChange((v,w)=>{u.current=w,i(w)});return()=>g.unsubscribe()}s(!1)}).catch(()=>{s(!1)})},[]);async function c(p,h){if(!e)return{error:"Supabase not configured"};const{error:g}=await e.auth.signInWithPassword({email:p,password:h});return{error:(g==null?void 0:g.message)??null}}async function f(){e&&(await e.auth.signOut(),u.current=null,i(null))}return j.jsx(JR.Provider,{value:{session:n,supabase:e,loading:a,signIn:c,signOut:f},children:t})}function b8(t={}){const[e,r]=$.useState(!1),[n,i]=$.useState(null),a=$.useRef(null),s=$.useRef(t);s.current=t,$.useEffect(()=>{let f=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;const p=v8();p&&(f+=`?token=${encodeURIComponent(p)}`);let h,g;function v(){h=new WebSocket(f),h.onopen=()=>{r(!0)},h.onmessage=w=>{var x,y,S,k,E,P,O,A;try{const C=JSON.parse(w.data);switch(C.type){case"connected":i(C.connectionId??null);break;case"delta":(y=(x=s.current).onDelta)==null||y.call(x,C.content??"");break;case"message":(k=(S=s.current).onMessage)==null||k.call(S,C.content??"");break;case"event":(P=(E=s.current).onEvent)==null||P.call(E,C);break;case"error":(A=(O=s.current).onError)==null||A.call(O,C.content??"Unknown error");break}}catch{}},h.onclose=()=>{r(!1),i(null),g=setTimeout(v,3e3)},h.onerror=()=>{h.close()},a.current=h}return v(),()=>{clearTimeout(g),h==null||h.close()}},[]);const u=$.useCallback((c,f="web")=>{var p;((p=a.current)==null?void 0:p.readyState)===WebSocket.OPEN&&a.current.send(JSON.stringify({type:"message",content:c,source:f}))},[]);return{connected:e,connectionId:n,sendMessage:u}}function Qw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Za=Qw();function ZR(t){Za=t}var Na={exec:()=>null};function No(t){let e=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=e[n];return i||(i=t(n),e[n]=i),i}}function qe(t,e=""){let r=typeof t=="string"?t:t.source,n={replace:(i,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(lr.caret,"$1"),r=r.replace(i,s),n},getRegex:()=>new RegExp(r,e)};return n}var w8=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),lr={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:No(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:No(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:No(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:No(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:No(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:No(t=>new RegExp(`^ {0,${t}}>`))},x8=/^(?:[ \t]*(?:\n|$))+/,_8=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,S8=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ku=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,k8=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zw=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,e2=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,t2=qe(e2).replace(/bull/g,Zw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),O8=qe(e2).replace(/bull/g,Zw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ex=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,E8=/^[^\n]+/,tx=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,A8=qe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",tx).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),P8=qe(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Zw).getRegex(),uh="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",rx=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,T8=qe("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",rx).replace("tag",uh).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),r2=qe(ex).replace("hr",Ku).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",uh).getRegex(),C8=qe(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",r2).getRegex(),nx={blockquote:C8,code:_8,def:A8,fences:S8,heading:k8,hr:Ku,html:T8,lheading:t2,list:P8,newline:x8,paragraph:r2,table:Na,text:E8},Bk=qe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ku).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",uh).getRegex(),j8={...nx,lheading:O8,table:Bk,paragraph:qe(ex).replace("hr",Ku).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Bk).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",uh).getRegex()},R8={...nx,html:qe(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",rx).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Na,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:qe(ex).replace("hr",Ku).replace("heading",` *#{1,6} *[^
|
|
200
200
|
]`).replace("lheading",t2).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},I8=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,$8=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,n2=/^( {2,}|\\)\n(?!\s*$)/,N8=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Rs=/[\p{P}\p{S}]/u,ch=/[\s\p{P}\p{S}]/u,ix=/[^\s\p{P}\p{S}]/u,M8=qe(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ch).getRegex(),i2=/(?!~)[\p{P}\p{S}]/u,L8=/(?!~)[\s\p{P}\p{S}]/u,D8=/(?:[^\s\p{P}\p{S}]|~)/u,B8=qe(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",w8?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),a2=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,U8=qe(a2,"u").replace(/punct/g,Rs).getRegex(),q8=qe(a2,"u").replace(/punct/g,i2).getRegex(),o2="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",z8=qe(o2,"gu").replace(/notPunctSpace/g,ix).replace(/punctSpace/g,ch).replace(/punct/g,Rs).getRegex(),F8=qe(o2,"gu").replace(/notPunctSpace/g,D8).replace(/punctSpace/g,L8).replace(/punct/g,i2).getRegex(),W8=qe("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ix).replace(/punctSpace/g,ch).replace(/punct/g,Rs).getRegex(),H8=qe(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Rs).getRegex(),V8="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",K8=qe(V8,"gu").replace(/notPunctSpace/g,ix).replace(/punctSpace/g,ch).replace(/punct/g,Rs).getRegex(),G8=qe(/\\(punct)/,"gu").replace(/punct/g,Rs).getRegex(),X8=qe(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Y8=qe(rx).replace("(?:-->|$)","-->").getRegex(),J8=qe("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Y8).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ed=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Q8=qe(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ed).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),s2=qe(/^!?\[(label)\]\[(ref)\]/).replace("label",ed).replace("ref",tx).getRegex(),l2=qe(/^!?\[(ref)\](?:\[\])?/).replace("ref",tx).getRegex(),Z8=qe("reflink|nolink(?!\\()","g").replace("reflink",s2).replace("nolink",l2).getRegex(),Uk=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ax={_backpedal:Na,anyPunctuation:G8,autolink:X8,blockSkip:B8,br:n2,code:$8,del:Na,delLDelim:Na,delRDelim:Na,emStrongLDelim:U8,emStrongRDelimAst:z8,emStrongRDelimUnd:W8,escape:I8,link:Q8,nolink:l2,punctuation:M8,reflink:s2,reflinkSearch:Z8,tag:J8,text:N8,url:Na},e5={...ax,link:qe(/^!?\[(label)\]\((.*?)\)/).replace("label",ed).getRegex(),reflink:qe(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ed).getRegex()},p0={...ax,emStrongRDelimAst:F8,emStrongLDelim:q8,delLDelim:H8,delRDelim:K8,url:qe(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Uk).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:qe(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Uk).getRegex()},t5={...p0,br:qe(n2).replace("{2,}","*").getRegex(),text:qe(p0.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},kf={normal:nx,gfm:j8,pedantic:R8},Cl={normal:ax,gfm:p0,breaks:t5,pedantic:e5},r5={"&":"&","<":"<",">":">",'"':""","'":"'"},qk=t=>r5[t];function $n(t,e){if(e){if(lr.escapeTest.test(t))return t.replace(lr.escapeReplace,qk)}else if(lr.escapeTestNoEncode.test(t))return t.replace(lr.escapeReplaceNoEncode,qk);return t}function zk(t){try{t=encodeURI(t).replace(lr.percentDecode,"%")}catch{return null}return t}function Fk(t,e){var a;let r=t.replace(lr.findPipe,(s,u,c)=>{let f=!1,p=u;for(;--p>=0&&c[p]==="\\";)f=!f;return f?"|":" |"}),n=r.split(lr.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!((a=n.at(-1))!=null&&a.trim())&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(lr.slashPipe,"|");return n}function Gi(t,e,r){let n=t.length;if(n===0)return"";let i=0;for(;i<n&&t.charAt(n-i-1)===e;)i++;return t.slice(0,n-i)}function Wk(t){let e=t.split(`
|
|
201
201
|
`),r=e.length-1;for(;r>=0&&lr.blankLine.test(e[r]);)r--;return e.length-r<=2?t:e.slice(0,r+1).join(`
|
|
202
202
|
`)}function n5(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let n=0;n<t.length;n++)if(t[n]==="\\")n++;else if(t[n]===e[0])r++;else if(t[n]===e[1]&&(r--,r<0))return n;return r>0?-2:-1}function i5(t,e=0){let r=e,n="";for(let i of t)if(i===" "){let a=4-r%4;n+=" ".repeat(a),r+=a}else n+=i,r++;return n}function Hk(t,e,r,n,i){let a=e.href,s=e.title||null,u=t[1].replace(i.other.outputLinkReplace,"$1");n.state.inLink=!0;let c={type:t[0].charAt(0)==="!"?"image":"link",raw:r,href:a,title:s,text:u,tokens:n.inlineTokens(u)};return n.state.inLink=!1,c}function a5(t,e,r){let n=t.match(r.other.indentCodeCompensation);if(n===null)return e;let i=n[1];return e.split(`
|
|
@@ -333,4 +333,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
333
333
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ON(t,e){if(t){if(typeof t=="string")return Mw(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Mw(t,e)}}function yte(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function bte(t){if(Array.isArray(t))return Mw(t)}function Mw(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function Lj(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function re(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Lj(Object(r),!0).forEach(function(n){Te(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Lj(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Te(t,e,r){return e=EN(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function EN(t){var e=wte(t,"string");return Es(e)=="symbol"?e:e+""}function wte(t,e){if(Es(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Es(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var xte={xAxis:["bottom","top"],yAxis:["left","right"]},_te={width:"100%",height:"100%"},AN={x:0,y:0};function Lf(t){return t}var Ste=function(e,r){return r==="horizontal"?e.x:r==="vertical"?e.y:r==="centric"?e.angle:e.radius},kte=function(e,r,n,i){var a=r.find(function(p){return p&&p.index===n});if(a){if(e==="horizontal")return{x:a.coordinate,y:i.y};if(e==="vertical")return{x:i.x,y:a.coordinate};if(e==="centric"){var s=a.coordinate,u=i.radius;return re(re(re({},i),it(i.cx,i.cy,u,s)),{},{angle:s,radius:u})}var c=a.coordinate,f=i.angle;return re(re(re({},i),it(i.cx,i.cy,c,f)),{},{angle:f,radius:c})}return AN},Yh=function(e,r){var n=r.graphicalItems,i=r.dataStartIndex,a=r.dataEndIndex,s=(n??[]).reduce(function(u,c){var f=c.props.data;return f&&f.length?[].concat(As(u),As(f)):u},[]);return s.length>0?s:e&&e.length&&fe(i)&&fe(a)?e.slice(i,a+1):[]};function PN(t){return t==="number"?[0,"auto"]:void 0}var Lw=function(e,r,n,i){var a=e.graphicalItems,s=e.tooltipAxis,u=Yh(r,e);return n<0||!a||!a.length||n>=u.length?null:a.reduce(function(c,f){var p,h=(p=f.props.data)!==null&&p!==void 0?p:r;h&&e.dataStartIndex+e.dataEndIndex!==0&&e.dataEndIndex-e.dataStartIndex>=n&&(h=h.slice(e.dataStartIndex,e.dataEndIndex+1));var g;if(s.dataKey&&!s.allowDuplicatedCategory){var v=h===void 0?u:h;g=nd(v,s.dataKey,i)}else g=h&&h[n]||u[n];return g?[].concat(As(c),[g$(f,g)]):c},[])},Dj=function(e,r,n,i){var a=i||{x:e.chartX,y:e.chartY},s=Ste(a,n),u=e.orderedTooltipTicks,c=e.tooltipAxis,f=e.tooltipTicks,p=cK(s,u,f,c);if(p>=0&&f){var h=f[p]&&f[p].value,g=Lw(e,r,p,h),v=kte(n,u,p,a);return{activeTooltipIndex:p,activeLabel:h,activePayload:g,activeCoordinate:v}}return null},Ote=function(e,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,s=r.axisIdKey,u=r.stackGroups,c=r.dataStartIndex,f=r.dataEndIndex,p=e.layout,h=e.children,g=e.stackOffset,v=f$(p,a);return n.reduce(function(w,x){var y,S=x.type.defaultProps!==void 0?re(re({},x.type.defaultProps),x.props):x.props,k=S.type,E=S.dataKey,P=S.allowDataOverflow,O=S.allowDuplicatedCategory,A=S.scale,C=S.ticks,R=S.includeHidden,M=S[s];if(w[M])return w;var H=Yh(e.data,{graphicalItems:i.filter(function(W){var te,ue=s in W.props?W.props[s]:(te=W.type.defaultProps)===null||te===void 0?void 0:te[s];return ue===M}),dataStartIndex:c,dataEndIndex:f}),z=H.length,B,F,J;Jee(S.domain,P,k)&&(B=Q0(S.domain,null,P),v&&(k==="number"||A!=="auto")&&(J=Ql(H,E,"category")));var V=PN(k);if(!B||B.length===0){var K,Z=(K=S.domain)!==null&&K!==void 0?K:V;if(E){if(B=Ql(H,E,k),k==="category"&&v){var G=nz(B);O&&G?(F=B,B=zd(0,z)):O||(B=FT(Z,B,x).reduce(function(W,te){return W.indexOf(te)>=0?W:[].concat(As(W),[te])},[]))}else if(k==="category")O?B=B.filter(function(W){return W!==""&&!Me(W)}):B=FT(Z,B,x).reduce(function(W,te){return W.indexOf(te)>=0||te===""||Me(te)?W:[].concat(As(W),[te])},[]);else if(k==="number"){var ee=mK(H,i.filter(function(W){var te,ue,le=s in W.props?W.props[s]:(te=W.type.defaultProps)===null||te===void 0?void 0:te[s],de="hide"in W.props?W.props.hide:(ue=W.type.defaultProps)===null||ue===void 0?void 0:ue.hide;return le===M&&(R||!de)}),E,a,p);ee&&(B=ee)}v&&(k==="number"||A!=="auto")&&(J=Ql(H,E,"category"))}else v?B=zd(0,z):u&&u[M]&&u[M].hasStack&&k==="number"?B=g==="expand"?[0,1]:m$(u[M].stackGroups,c,f):B=c$(H,i.filter(function(W){var te=s in W.props?W.props[s]:W.type.defaultProps[s],ue="hide"in W.props?W.props.hide:W.type.defaultProps.hide;return te===M&&(R||!ue)}),k,p,!0);if(k==="number")B=$w(h,B,M,a,C),Z&&(B=Q0(Z,B,P));else if(k==="category"&&Z){var U=Z,L=B.every(function(W){return U.indexOf(W)>=0});L&&(B=U)}}return re(re({},w),{},Te({},M,re(re({},S),{},{axisType:a,domain:B,categoricalDomain:J,duplicateDomain:F,originalDomain:(y=S.domain)!==null&&y!==void 0?y:V,isCategorical:v,layout:p})))},{})},Ete=function(e,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,s=r.axisIdKey,u=r.stackGroups,c=r.dataStartIndex,f=r.dataEndIndex,p=e.layout,h=e.children,g=Yh(e.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:f}),v=g.length,w=f$(p,a),x=-1;return n.reduce(function(y,S){var k=S.type.defaultProps!==void 0?re(re({},S.type.defaultProps),S.props):S.props,E=k[s],P=PN("number");if(!y[E]){x++;var O;return w?O=zd(0,v):u&&u[E]&&u[E].hasStack?(O=m$(u[E].stackGroups,c,f),O=$w(h,O,E,a)):(O=Q0(P,c$(g,n.filter(function(A){var C,R,M=s in A.props?A.props[s]:(C=A.type.defaultProps)===null||C===void 0?void 0:C[s],H="hide"in A.props?A.props.hide:(R=A.type.defaultProps)===null||R===void 0?void 0:R.hide;return M===E&&!H}),"number",p),i.defaultProps.allowDataOverflow),O=$w(h,O,E,a)),re(re({},y),{},Te({},E,re(re({axisType:a},i.defaultProps),{},{hide:!0,orientation:Mr(xte,"".concat(a,".").concat(x%2),null),domain:O,originalDomain:P,isCategorical:w,layout:p})))}return y},{})},Ate=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,s=r.graphicalItems,u=r.stackGroups,c=r.dataStartIndex,f=r.dataEndIndex,p=e.children,h="".concat(i,"Id"),g=tn(p,a),v={};return g&&g.length?v=Ote(e,{axes:g,graphicalItems:s,axisType:i,axisIdKey:h,stackGroups:u,dataStartIndex:c,dataEndIndex:f}):s&&s.length&&(v=Ete(e,{Axis:a,graphicalItems:s,axisType:i,axisIdKey:h,stackGroups:u,dataStartIndex:c,dataEndIndex:f})),v},Pte=function(e){var r=zo(e),n=qa(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:Ax(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:Td(r,n)}},Bj=function(e){var r=e.children,n=e.defaultShowTooltip,i=Ir(r,vs),a=0,s=0;return e.data&&e.data.length!==0&&(s=e.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(s=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:s,activeTooltipIndex:-1,isTooltipActive:!!n}},Tte=function(e){return!e||!e.length?!1:e.some(function(r){var n=ui(r&&r.type);return n&&n.indexOf("Bar")>=0})},Uj=function(e){return e==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:e==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:e==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},Cte=function(e,r){var n=e.props,i=e.graphicalItems,a=e.xAxisMap,s=a===void 0?{}:a,u=e.yAxisMap,c=u===void 0?{}:u,f=n.width,p=n.height,h=n.children,g=n.margin||{},v=Ir(h,vs),w=Ir(h,Jo),x=Object.keys(c).reduce(function(O,A){var C=c[A],R=C.orientation;return!C.mirror&&!C.hide?re(re({},O),{},Te({},R,O[R]+C.width)):O},{left:g.left||0,right:g.right||0}),y=Object.keys(s).reduce(function(O,A){var C=s[A],R=C.orientation;return!C.mirror&&!C.hide?re(re({},O),{},Te({},R,Mr(O,"".concat(R))+C.height)):O},{top:g.top||0,bottom:g.bottom||0}),S=re(re({},y),x),k=S.bottom;v&&(S.bottom+=v.props.height||vs.defaultProps.height),w&&r&&(S=hK(S,i,n,r));var E=f-S.left-S.right,P=p-S.top-S.bottom;return re(re({brushBottom:k},S),{},{width:Math.max(E,0),height:Math.max(P,0)})},jte=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},TN=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,a=i===void 0?"axis":i,s=e.validateTooltipEventTypes,u=s===void 0?["axis"]:s,c=e.axisComponents,f=e.legendContent,p=e.formatAxisMap,h=e.defaultProps,g=function(S,k){var E=k.graphicalItems,P=k.stackGroups,O=k.offset,A=k.updateId,C=k.dataStartIndex,R=k.dataEndIndex,M=S.barSize,H=S.layout,z=S.barGap,B=S.barCategoryGap,F=S.maxBarSize,J=Uj(H),V=J.numericAxisName,K=J.cateAxisName,Z=Tte(E),G=[];return E.forEach(function(ee,U){var L=Yh(S.data,{graphicalItems:[ee],dataStartIndex:C,dataEndIndex:R}),W=ee.type.defaultProps!==void 0?re(re({},ee.type.defaultProps),ee.props):ee.props,te=W.dataKey,ue=W.maxBarSize,le=W["".concat(V,"Id")],de=W["".concat(K,"Id")],Re={},pe=c.reduce(function(er,ot){var Er=k["".concat(ot.axisType,"Map")],la=W["".concat(ot.axisType,"Id")];Er&&Er[la]||ot.axisType==="zAxis"||Ja();var ua=Er[la];return re(re({},er),{},Te(Te({},ot.axisType,ua),"".concat(ot.axisType,"Ticks"),qa(ua)))},Re),ne=pe[K],_e=pe["".concat(K,"Ticks")],Oe=P&&P[le]&&P[le].hasStack&&kK(ee,P[le].stackGroups),ie=ui(ee.type).indexOf("Bar")>=0,ze=Td(ne,_e),Ie=[],ct=Z&&fK({barSize:M,stackGroups:P,totalSize:jte(pe,K)});if(ie){var at,ft,pr=Me(ue)?F:ue,St=(at=(ft=Td(ne,_e,!0))!==null&&ft!==void 0?ft:pr)!==null&&at!==void 0?at:0;Ie=dK({barGap:z,barCategoryGap:B,bandSize:St!==ze?St:ze,sizeList:ct[de],maxBarSize:pr}),St!==ze&&(Ie=Ie.map(function(er){return re(re({},er),{},{position:re(re({},er.position),{},{offset:er.position.offset-St/2})})}))}var Dr=ee&&ee.type&&ee.type.getComposedData;Dr&&G.push({props:re(re({},Dr(re(re({},pe),{},{displayedData:L,props:S,dataKey:te,item:ee,bandSize:ze,barPosition:Ie,offset:O,stackedData:Oe,layout:H,dataStartIndex:C,dataEndIndex:R}))),{},Te(Te(Te({key:ee.key||"item-".concat(U)},V,pe[V]),K,pe[K]),"animationId",A)),childIndex:gz(ee,S.children),item:ee})}),G},v=function(S,k){var E=S.props,P=S.dataStartIndex,O=S.dataEndIndex,A=S.updateId;if(!rE({props:E}))return null;var C=E.children,R=E.layout,M=E.stackOffset,H=E.data,z=E.reverseStackOrder,B=Uj(R),F=B.numericAxisName,J=B.cateAxisName,V=tn(C,n),K=_K(H,V,"".concat(F,"Id"),"".concat(J,"Id"),M,z),Z=c.reduce(function(W,te){var ue="".concat(te.axisType,"Map");return re(re({},W),{},Te({},ue,Ate(E,re(re({},te),{},{graphicalItems:V,stackGroups:te.axisType===F&&K,dataStartIndex:P,dataEndIndex:O}))))},{}),G=Cte(re(re({},Z),{},{props:E,graphicalItems:V}),k==null?void 0:k.legendBBox);Object.keys(Z).forEach(function(W){Z[W]=p(E,Z[W],G,W.replace("Map",""),r)});var ee=Z["".concat(J,"Map")],U=Pte(ee),L=g(E,re(re({},Z),{},{dataStartIndex:P,dataEndIndex:O,updateId:A,graphicalItems:V,stackGroups:K,offset:G}));return re(re({formattedGraphicalItems:L,graphicalItems:V,offset:G,stackGroups:K},U),Z)},w=(function(y){function S(k){var E,P,O;return cte(this,S),O=hte(this,S,[k]),Te(O,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Te(O,"accessibilityManager",new Yee),Te(O,"handleLegendBBoxUpdate",function(A){if(A){var C=O.state,R=C.dataStartIndex,M=C.dataEndIndex,H=C.updateId;O.setState(re({legendBBox:A},v({props:O.props,dataStartIndex:R,dataEndIndex:M,updateId:H},re(re({},O.state),{},{legendBBox:A}))))}}),Te(O,"handleReceiveSyncEvent",function(A,C,R){if(O.props.syncId===A){if(R===O.eventEmitterSymbol&&typeof O.props.syncMethod!="function")return;O.applySyncEvent(C)}}),Te(O,"handleBrushChange",function(A){var C=A.startIndex,R=A.endIndex;if(C!==O.state.dataStartIndex||R!==O.state.dataEndIndex){var M=O.state.updateId;O.setState(function(){return re({dataStartIndex:C,dataEndIndex:R},v({props:O.props,dataStartIndex:C,dataEndIndex:R,updateId:M},O.state))}),O.triggerSyncEvent({dataStartIndex:C,dataEndIndex:R})}}),Te(O,"handleMouseEnter",function(A){var C=O.getMouseInfo(A);if(C){var R=re(re({},C),{},{isTooltipActive:!0});O.setState(R),O.triggerSyncEvent(R);var M=O.props.onMouseEnter;$e(M)&&M(R,A)}}),Te(O,"triggeredAfterMouseMove",function(A){var C=O.getMouseInfo(A),R=C?re(re({},C),{},{isTooltipActive:!0}):{isTooltipActive:!1};O.setState(R),O.triggerSyncEvent(R);var M=O.props.onMouseMove;$e(M)&&M(R,A)}),Te(O,"handleItemMouseEnter",function(A){O.setState(function(){return{isTooltipActive:!0,activeItem:A,activePayload:A.tooltipPayload,activeCoordinate:A.tooltipPosition||{x:A.cx,y:A.cy}}})}),Te(O,"handleItemMouseLeave",function(){O.setState(function(){return{isTooltipActive:!1}})}),Te(O,"handleMouseMove",function(A){A.persist(),O.throttleTriggeredAfterMouseMove(A)}),Te(O,"handleMouseLeave",function(A){O.throttleTriggeredAfterMouseMove.cancel();var C={isTooltipActive:!1};O.setState(C),O.triggerSyncEvent(C);var R=O.props.onMouseLeave;$e(R)&&R(C,A)}),Te(O,"handleOuterEvent",function(A){var C=mz(A),R=Mr(O.props,"".concat(C));if(C&&$e(R)){var M,H;/.*touch.*/i.test(C)?H=O.getMouseInfo(A.changedTouches[0]):H=O.getMouseInfo(A),R((M=H)!==null&&M!==void 0?M:{},A)}}),Te(O,"handleClick",function(A){var C=O.getMouseInfo(A);if(C){var R=re(re({},C),{},{isTooltipActive:!0});O.setState(R),O.triggerSyncEvent(R);var M=O.props.onClick;$e(M)&&M(R,A)}}),Te(O,"handleMouseDown",function(A){var C=O.props.onMouseDown;if($e(C)){var R=O.getMouseInfo(A);C(R,A)}}),Te(O,"handleMouseUp",function(A){var C=O.props.onMouseUp;if($e(C)){var R=O.getMouseInfo(A);C(R,A)}}),Te(O,"handleTouchMove",function(A){A.changedTouches!=null&&A.changedTouches.length>0&&O.throttleTriggeredAfterMouseMove(A.changedTouches[0])}),Te(O,"handleTouchStart",function(A){A.changedTouches!=null&&A.changedTouches.length>0&&O.handleMouseDown(A.changedTouches[0])}),Te(O,"handleTouchEnd",function(A){A.changedTouches!=null&&A.changedTouches.length>0&&O.handleMouseUp(A.changedTouches[0])}),Te(O,"handleDoubleClick",function(A){var C=O.props.onDoubleClick;if($e(C)){var R=O.getMouseInfo(A);C(R,A)}}),Te(O,"handleContextMenu",function(A){var C=O.props.onContextMenu;if($e(C)){var R=O.getMouseInfo(A);C(R,A)}}),Te(O,"triggerSyncEvent",function(A){O.props.syncId!==void 0&&Hb.emit(Vb,O.props.syncId,A,O.eventEmitterSymbol)}),Te(O,"applySyncEvent",function(A){var C=O.props,R=C.layout,M=C.syncMethod,H=O.state.updateId,z=A.dataStartIndex,B=A.dataEndIndex;if(A.dataStartIndex!==void 0||A.dataEndIndex!==void 0)O.setState(re({dataStartIndex:z,dataEndIndex:B},v({props:O.props,dataStartIndex:z,dataEndIndex:B,updateId:H},O.state)));else if(A.activeTooltipIndex!==void 0){var F=A.chartX,J=A.chartY,V=A.activeTooltipIndex,K=O.state,Z=K.offset,G=K.tooltipTicks;if(!Z)return;if(typeof M=="function")V=M(G,A);else if(M==="value"){V=-1;for(var ee=0;ee<G.length;ee++)if(G[ee].value===A.activeLabel){V=ee;break}}var U=re(re({},Z),{},{x:Z.left,y:Z.top}),L=Math.min(F,U.x+U.width),W=Math.min(J,U.y+U.height),te=G[V]&&G[V].value,ue=Lw(O.state,O.props.data,V),le=G[V]?{x:R==="horizontal"?G[V].coordinate:L,y:R==="horizontal"?W:G[V].coordinate}:AN;O.setState(re(re({},A),{},{activeLabel:te,activeCoordinate:le,activePayload:ue,activeTooltipIndex:V}))}else O.setState(A)}),Te(O,"renderCursor",function(A){var C,R=O.state,M=R.isTooltipActive,H=R.activeCoordinate,z=R.activePayload,B=R.offset,F=R.activeTooltipIndex,J=R.tooltipAxisBandSize,V=O.getTooltipEventType(),K=(C=A.props.active)!==null&&C!==void 0?C:M,Z=O.props.layout,G=A.key||"_recharts-cursor";return I.createElement(nte,{key:G,activeCoordinate:H,activePayload:z,activeTooltipIndex:F,chartName:r,element:A,isActive:K,layout:Z,offset:B,tooltipAxisBandSize:J,tooltipEventType:V})}),Te(O,"renderPolarAxis",function(A,C,R){var M=Mr(A,"type.axisType"),H=Mr(O.state,"".concat(M,"Map")),z=A.type.defaultProps,B=z!==void 0?re(re({},z),A.props):A.props,F=H&&H[B["".concat(M,"Id")]];return $.cloneElement(A,re(re({},F),{},{className:Le(M,F.className),key:A.key||"".concat(C,"-").concat(R),ticks:qa(F,!0)}))}),Te(O,"renderPolarGrid",function(A){var C=A.props,R=C.radialLines,M=C.polarAngles,H=C.polarRadius,z=O.state,B=z.radiusAxisMap,F=z.angleAxisMap,J=zo(B),V=zo(F),K=V.cx,Z=V.cy,G=V.innerRadius,ee=V.outerRadius;return $.cloneElement(A,{polarAngles:Array.isArray(M)?M:qa(V,!0).map(function(U){return U.coordinate}),polarRadius:Array.isArray(H)?H:qa(J,!0).map(function(U){return U.coordinate}),cx:K,cy:Z,innerRadius:G,outerRadius:ee,key:A.key||"polar-grid",radialLines:R})}),Te(O,"renderLegend",function(){var A=O.state.formattedGraphicalItems,C=O.props,R=C.children,M=C.width,H=C.height,z=O.props.margin||{},B=M-(z.left||0)-(z.right||0),F=l$({children:R,formattedGraphicalItems:A,legendWidth:B,legendContent:f});if(!F)return null;var J=F.item,V=Mj(F,ite);return $.cloneElement(J,re(re({},V),{},{chartWidth:M,chartHeight:H,margin:z,onBBoxUpdate:O.handleLegendBBoxUpdate}))}),Te(O,"renderTooltip",function(){var A,C=O.props,R=C.children,M=C.accessibilityLayer,H=Ir(R,vn);if(!H)return null;var z=O.state,B=z.isTooltipActive,F=z.activeCoordinate,J=z.activePayload,V=z.activeLabel,K=z.offset,Z=(A=H.props.active)!==null&&A!==void 0?A:B;return $.cloneElement(H,{viewBox:re(re({},K),{},{x:K.left,y:K.top}),active:Z,label:V,payload:Z?J:[],coordinate:F,accessibilityLayer:M})}),Te(O,"renderBrush",function(A){var C=O.props,R=C.margin,M=C.data,H=O.state,z=H.offset,B=H.dataStartIndex,F=H.dataEndIndex,J=H.updateId;return $.cloneElement(A,{key:A.key||"_recharts-brush",onChange:Rf(O.handleBrushChange,A.props.onChange),data:M,x:fe(A.props.x)?A.props.x:z.left,y:fe(A.props.y)?A.props.y:z.top+z.height+z.brushBottom-(R.bottom||0),width:fe(A.props.width)?A.props.width:z.width,startIndex:B,endIndex:F,updateId:"brush-".concat(J)})}),Te(O,"renderReferenceElement",function(A,C,R){if(!A)return null;var M=O,H=M.clipPathId,z=O.state,B=z.xAxisMap,F=z.yAxisMap,J=z.offset,V=A.type.defaultProps||{},K=A.props,Z=K.xAxisId,G=Z===void 0?V.xAxisId:Z,ee=K.yAxisId,U=ee===void 0?V.yAxisId:ee;return $.cloneElement(A,{key:A.key||"".concat(C,"-").concat(R),xAxis:B[G],yAxis:F[U],viewBox:{x:J.left,y:J.top,width:J.width,height:J.height},clipPathId:H})}),Te(O,"renderActivePoints",function(A){var C=A.item,R=A.activePoint,M=A.basePoint,H=A.childIndex,z=A.isRange,B=[],F=C.props.key,J=C.item.type.defaultProps!==void 0?re(re({},C.item.type.defaultProps),C.item.props):C.item.props,V=J.activeDot,K=J.dataKey,Z=re(re({index:H,dataKey:K,cx:R.x,cy:R.y,r:4,fill:Zx(C.item),strokeWidth:2,stroke:"#fff",payload:R.payload,value:R.value},Ee(V,!1)),id(V));return B.push(S.renderActiveDot(V,Z,"".concat(F,"-activePoint-").concat(H))),M?B.push(S.renderActiveDot(V,re(re({},Z),{},{cx:M.x,cy:M.y}),"".concat(F,"-basePoint-").concat(H))):z&&B.push(null),B}),Te(O,"renderGraphicChild",function(A,C,R){var M=O.filterFormatItem(A,C,R);if(!M)return null;var H=O.getTooltipEventType(),z=O.state,B=z.isTooltipActive,F=z.tooltipAxis,J=z.activeTooltipIndex,V=z.activeLabel,K=O.props.children,Z=Ir(K,vn),G=M.props,ee=G.points,U=G.isRange,L=G.baseLine,W=M.item.type.defaultProps!==void 0?re(re({},M.item.type.defaultProps),M.item.props):M.item.props,te=W.activeDot,ue=W.hide,le=W.activeBar,de=W.activeShape,Re=!!(!ue&&B&&Z&&(te||le||de)),pe={};H!=="axis"&&Z&&Z.props.trigger==="click"?pe={onClick:Rf(O.handleItemMouseEnter,A.props.onClick)}:H!=="axis"&&(pe={onMouseLeave:Rf(O.handleItemMouseLeave,A.props.onMouseLeave),onMouseEnter:Rf(O.handleItemMouseEnter,A.props.onMouseEnter)});var ne=$.cloneElement(A,re(re({},M.props),pe));function _e(ot){return typeof F.dataKey=="function"?F.dataKey(ot.payload):null}if(Re)if(J>=0){var Oe,ie;if(F.dataKey&&!F.allowDuplicatedCategory){var ze=typeof F.dataKey=="function"?_e:"payload.".concat(F.dataKey.toString());Oe=nd(ee,ze,V),ie=U&&L&&nd(L,ze,V)}else Oe=ee==null?void 0:ee[J],ie=U&&L&&L[J];if(de||le){var Ie=A.props.activeIndex!==void 0?A.props.activeIndex:J;return[$.cloneElement(A,re(re(re({},M.props),pe),{},{activeIndex:Ie})),null,null]}if(!Me(Oe))return[ne].concat(As(O.renderActivePoints({item:M,activePoint:Oe,basePoint:ie,childIndex:J,isRange:U})))}else{var ct,at=(ct=O.getItemByXY(O.state.activeCoordinate))!==null&&ct!==void 0?ct:{graphicalItem:ne},ft=at.graphicalItem,pr=ft.item,St=pr===void 0?A:pr,Dr=ft.childIndex,er=re(re(re({},M.props),pe),{},{activeIndex:Dr});return[$.cloneElement(St,er),null,null]}return U?[ne,null,null]:[ne,null]}),Te(O,"renderCustomized",function(A,C,R){return $.cloneElement(A,re(re({key:"recharts-customized-".concat(R)},O.props),O.state))}),Te(O,"renderMap",{CartesianGrid:{handler:Lf,once:!0},ReferenceArea:{handler:O.renderReferenceElement},ReferenceLine:{handler:Lf},ReferenceDot:{handler:O.renderReferenceElement},XAxis:{handler:Lf},YAxis:{handler:Lf},Brush:{handler:O.renderBrush,once:!0},Bar:{handler:O.renderGraphicChild},Line:{handler:O.renderGraphicChild},Area:{handler:O.renderGraphicChild},Radar:{handler:O.renderGraphicChild},RadialBar:{handler:O.renderGraphicChild},Scatter:{handler:O.renderGraphicChild},Pie:{handler:O.renderGraphicChild},Funnel:{handler:O.renderGraphicChild},Tooltip:{handler:O.renderCursor,once:!0},PolarGrid:{handler:O.renderPolarGrid,once:!0},PolarAngleAxis:{handler:O.renderPolarAxis},PolarRadiusAxis:{handler:O.renderPolarAxis},Customized:{handler:O.renderCustomized}}),O.clipPathId="".concat((E=k.id)!==null&&E!==void 0?E:Ms("recharts"),"-clip"),O.throttleTriggeredAfterMouseMove=lI(O.triggeredAfterMouseMove,(P=k.throttleDelay)!==null&&P!==void 0?P:1e3/60),O.state={},O}return gte(S,y),dte(S,[{key:"componentDidMount",value:function(){var E,P;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(E=this.props.margin.left)!==null&&E!==void 0?E:0,top:(P=this.props.margin.top)!==null&&P!==void 0?P:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var E=this.props,P=E.children,O=E.data,A=E.height,C=E.layout,R=Ir(P,vn);if(R){var M=R.props.defaultIndex;if(!(typeof M!="number"||M<0||M>this.state.tooltipTicks.length-1)){var H=this.state.tooltipTicks[M]&&this.state.tooltipTicks[M].value,z=Lw(this.state,O,M,H),B=this.state.tooltipTicks[M].coordinate,F=(this.state.offset.top+A)/2,J=C==="horizontal",V=J?{x:B,y:F}:{y:B,x:F},K=this.state.formattedGraphicalItems.find(function(G){var ee=G.item;return ee.type.name==="Scatter"});K&&(V=re(re({},V),K.props.points[M].tooltipPosition),z=K.props.points[M].tooltipPayload);var Z={activeTooltipIndex:M,isTooltipActive:!0,activeLabel:H,activePayload:z,activeCoordinate:V};this.setState(Z),this.renderCursor(R),this.accessibilityManager.setIndex(M)}}}},{key:"getSnapshotBeforeUpdate",value:function(E,P){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==P.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==E.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==E.margin){var O,A;this.accessibilityManager.setDetails({offset:{left:(O=this.props.margin.left)!==null&&O!==void 0?O:0,top:(A=this.props.margin.top)!==null&&A!==void 0?A:0}})}return null}},{key:"componentDidUpdate",value:function(E){w0([Ir(E.children,vn)],[Ir(this.props.children,vn)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var E=Ir(this.props.children,vn);if(E&&typeof E.props.shared=="boolean"){var P=E.props.shared?"axis":"item";return u.indexOf(P)>=0?P:a}return a}},{key:"getMouseInfo",value:function(E){if(!this.container)return null;var P=this.container,O=P.getBoundingClientRect(),A=rW(O),C={chartX:Math.round(E.pageX-A.left),chartY:Math.round(E.pageY-A.top)},R=O.width/P.offsetWidth||1,M=this.inRange(C.chartX,C.chartY,R);if(!M)return null;var H=this.state,z=H.xAxisMap,B=H.yAxisMap,F=this.getTooltipEventType(),J=Dj(this.state,this.props.data,this.props.layout,M);if(F!=="axis"&&z&&B){var V=zo(z).scale,K=zo(B).scale,Z=V&&V.invert?V.invert(C.chartX):null,G=K&&K.invert?K.invert(C.chartY):null;return re(re({},C),{},{xValue:Z,yValue:G},J)}return J?re(re({},C),J):null}},{key:"inRange",value:function(E,P){var O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,A=this.props.layout,C=E/O,R=P/O;if(A==="horizontal"||A==="vertical"){var M=this.state.offset,H=C>=M.left&&C<=M.left+M.width&&R>=M.top&&R<=M.top+M.height;return H?{x:C,y:R}:null}var z=this.state,B=z.angleAxisMap,F=z.radiusAxisMap;if(B&&F){var J=zo(B);return VT({x:C,y:R},J)}return null}},{key:"parseEventsOfWrapper",value:function(){var E=this.props.children,P=this.getTooltipEventType(),O=Ir(E,vn),A={};O&&P==="axis"&&(O.props.trigger==="click"?A={onClick:this.handleClick}:A={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var C=id(this.props,this.handleOuterEvent);return re(re({},C),A)}},{key:"addListener",value:function(){Hb.on(Vb,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Hb.removeListener(Vb,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(E,P,O){for(var A=this.state.formattedGraphicalItems,C=0,R=A.length;C<R;C++){var M=A[C];if(M.item===E||M.props.key===E.key||P===ui(M.item.type)&&O===M.childIndex)return M}return null}},{key:"renderClipPath",value:function(){var E=this.clipPathId,P=this.state.offset,O=P.left,A=P.top,C=P.height,R=P.width;return I.createElement("defs",null,I.createElement("clipPath",{id:E},I.createElement("rect",{x:O,y:A,height:C,width:R})))}},{key:"getXScales",value:function(){var E=this.state.xAxisMap;return E?Object.entries(E).reduce(function(P,O){var A=Nj(O,2),C=A[0],R=A[1];return re(re({},P),{},Te({},C,R.scale))},{}):null}},{key:"getYScales",value:function(){var E=this.state.yAxisMap;return E?Object.entries(E).reduce(function(P,O){var A=Nj(O,2),C=A[0],R=A[1];return re(re({},P),{},Te({},C,R.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(E){var P;return(P=this.state.xAxisMap)===null||P===void 0||(P=P[E])===null||P===void 0?void 0:P.scale}},{key:"getYScaleByAxisId",value:function(E){var P;return(P=this.state.yAxisMap)===null||P===void 0||(P=P[E])===null||P===void 0?void 0:P.scale}},{key:"getItemByXY",value:function(E){var P=this.state,O=P.formattedGraphicalItems,A=P.activeItem;if(O&&O.length)for(var C=0,R=O.length;C<R;C++){var M=O[C],H=M.props,z=M.item,B=z.type.defaultProps!==void 0?re(re({},z.type.defaultProps),z.props):z.props,F=ui(z.type);if(F==="Bar"){var J=(H.data||[]).find(function(G){return SY(E,G)});if(J)return{graphicalItem:M,payload:J}}else if(F==="RadialBar"){var V=(H.data||[]).find(function(G){return VT(E,G)});if(V)return{graphicalItem:M,payload:V}}else if(Uh(M,A)||qh(M,A)||Lu(M,A)){var K=VJ({graphicalItem:M,activeTooltipItem:A,itemData:B.data}),Z=B.activeIndex===void 0?K:B.activeIndex;return{graphicalItem:re(re({},M),{},{childIndex:Z}),payload:Lu(M,A)?B.data[K]:M.props.data[K]}}}return null}},{key:"render",value:function(){var E=this;if(!rE(this))return null;var P=this.props,O=P.children,A=P.className,C=P.width,R=P.height,M=P.style,H=P.compact,z=P.title,B=P.desc,F=Mj(P,ate),J=Ee(F,!1);if(H)return I.createElement(bj,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},I.createElement(_0,Go({},J,{width:C,height:R,title:z,desc:B}),this.renderClipPath(),iE(O,this.renderMap)));if(this.props.accessibilityLayer){var V,K;J.tabIndex=(V=this.props.tabIndex)!==null&&V!==void 0?V:0,J.role=(K=this.props.role)!==null&&K!==void 0?K:"application",J.onKeyDown=function(G){E.accessibilityManager.keyboardEvent(G)},J.onFocus=function(){E.accessibilityManager.focus()}}var Z=this.parseEventsOfWrapper();return I.createElement(bj,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},I.createElement("div",Go({className:Le("recharts-wrapper",A),style:re({position:"relative",cursor:"default",width:C,height:R},M)},Z,{ref:function(ee){E.container=ee}}),I.createElement(_0,Go({},J,{width:C,height:R,title:z,desc:B,style:_te}),this.renderClipPath(),iE(O,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])})($.Component);Te(w,"displayName",r),Te(w,"defaultProps",re({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},h)),Te(w,"getDerivedStateFromProps",function(y,S){var k=y.dataKey,E=y.data,P=y.children,O=y.width,A=y.height,C=y.layout,R=y.stackOffset,M=y.margin,H=S.dataStartIndex,z=S.dataEndIndex;if(S.updateId===void 0){var B=Bj(y);return re(re(re({},B),{},{updateId:0},v(re(re({props:y},B),{},{updateId:0}),S)),{},{prevDataKey:k,prevData:E,prevWidth:O,prevHeight:A,prevLayout:C,prevStackOffset:R,prevMargin:M,prevChildren:P})}if(k!==S.prevDataKey||E!==S.prevData||O!==S.prevWidth||A!==S.prevHeight||C!==S.prevLayout||R!==S.prevStackOffset||!Yo(M,S.prevMargin)){var F=Bj(y),J={chartX:S.chartX,chartY:S.chartY,isTooltipActive:S.isTooltipActive},V=re(re({},Dj(S,E,C)),{},{updateId:S.updateId+1}),K=re(re(re({},F),J),V);return re(re(re({},K),v(re({props:y},K),S)),{},{prevDataKey:k,prevData:E,prevWidth:O,prevHeight:A,prevLayout:C,prevStackOffset:R,prevMargin:M,prevChildren:P})}if(!w0(P,S.prevChildren)){var Z,G,ee,U,L=Ir(P,vs),W=L&&(Z=(G=L.props)===null||G===void 0?void 0:G.startIndex)!==null&&Z!==void 0?Z:H,te=L&&(ee=(U=L.props)===null||U===void 0?void 0:U.endIndex)!==null&&ee!==void 0?ee:z,ue=W!==H||te!==z,le=!Me(E),de=le&&!ue?S.updateId:S.updateId+1;return re(re({updateId:de},v(re(re({props:y},S),{},{updateId:de,dataStartIndex:W,dataEndIndex:te}),S)),{},{prevChildren:P,dataStartIndex:W,dataEndIndex:te})}return null}),Te(w,"renderActiveDot",function(y,S,k){var E;return $.isValidElement(y)?E=$.cloneElement(y,S):$e(y)?E=y(S):E=I.createElement(Nh,S),I.createElement(Ue,{className:"recharts-active-dot",key:k},E)});var x=$.forwardRef(function(S,k){return I.createElement(w,Go({},S,{ref:k}))});return x.displayName=w.displayName,x},Rte=TN({chartName:"PieChart",GraphicalChild:xi,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:Bh},{axisType:"radiusAxis",AxisComp:Lh}],formatAxisMap:$K,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}}),Ite=TN({chartName:"AreaChart",GraphicalChild:sa,axisComponents:[{axisType:"xAxis",AxisComp:Gh},{axisType:"yAxis",AxisComp:Xh}],formatAxisMap:YQ});const Df=["#E43A9C","#D83333","#F041FF","#38bdf8","#a78bfa","#34d399","#f59e0b"];function $te(){const[t,e]=$.useState(null),[r,n]=$.useState("7d");if($.useEffect(()=>{const c=new Date;r==="7d"?c.setDate(c.getDate()-7):r==="30d"?c.setDate(c.getDate()-30):c.setDate(c.getDate()-1),Pt.get(`/usage?since=${c.toISOString()}`).then(e).catch(()=>{})},[r]),!t)return j.jsx("div",{className:"h-full flex items-center justify-center text-[var(--color-muted-foreground)]",children:"Loading..."});const i=new Map;for(const c of t.entries){const f=c.timestamp.slice(0,10),p=i.get(f)??{date:f,tokens:0,cost:0};p.tokens+=c.inputTokens+c.outputTokens,p.cost+=c.estimatedCostUsd??0,i.set(f,p)}const a=Array.from(i.values()).sort((c,f)=>c.date.localeCompare(f.date)),s=new Map;for(const c of t.entries)s.set(c.model,(s.get(c.model)??0)+c.inputTokens+c.outputTokens);const u=Array.from(s.entries()).map(([c,f])=>({name:c,value:f}));return j.jsxs("div",{className:"h-full overflow-y-auto p-6",children:[j.jsxs("header",{className:"flex items-center justify-between mb-6",children:[j.jsxs("div",{children:[j.jsx("h1",{className:"text-2xl font-bold gradient-text",children:"Usage"}),j.jsx("p",{className:"text-sm text-[var(--color-muted-foreground)] mt-1",children:"Token usage and cost tracking"})]}),j.jsx("div",{className:"flex gap-1 p-1 rounded-lg bg-white/3",children:["1d","7d","30d"].map(c=>j.jsx("button",{type:"button",onClick:()=>n(c),className:`px-3 py-1.5 rounded-md text-xs font-medium ${r===c?"bg-white/10 text-[var(--color-foreground)]":"text-[var(--color-muted-foreground)]"}`,children:c},c))})]}),j.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[j.jsx(Bf,{label:"Total Tokens",value:Ul(t.totals.inputTokens+t.totals.outputTokens)}),j.jsx(Bf,{label:"Input Tokens",value:Ul(t.totals.inputTokens)}),j.jsx(Bf,{label:"Output Tokens",value:Ul(t.totals.outputTokens)}),j.jsx(Bf,{label:"Est. Cost",value:`$${t.totals.estimatedCost.toFixed(4)}`})]}),j.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[j.jsxs("div",{className:"lg:col-span-2 glass-card p-4",children:[j.jsx("h3",{className:"text-sm font-semibold mb-4",children:"Tokens Over Time"}),a.length>0?j.jsx(EP,{width:"100%",height:250,children:j.jsxs(Ite,{data:a,children:[j.jsx("defs",{children:j.jsxs("linearGradient",{id:"colorTokens",x1:"0",y1:"0",x2:"0",y2:"1",children:[j.jsx("stop",{offset:"5%",stopColor:"#E43A9C",stopOpacity:.3}),j.jsx("stop",{offset:"95%",stopColor:"#E43A9C",stopOpacity:0})]})}),j.jsx(Gh,{dataKey:"date",tick:{fontSize:11,fill:"#9ca3af"},axisLine:!1,tickLine:!1}),j.jsx(Xh,{tick:{fontSize:11,fill:"#9ca3af"},axisLine:!1,tickLine:!1,tickFormatter:Ul}),j.jsx(vn,{contentStyle:{background:"#222",border:"1px solid #333",borderRadius:"8px",fontSize:"12px"},labelStyle:{color:"#9ca3af"}}),j.jsx(sa,{type:"monotone",dataKey:"tokens",stroke:"#E43A9C",fill:"url(#colorTokens)",strokeWidth:2})]})}):j.jsx("div",{className:"h-[250px] flex items-center justify-center text-[var(--color-muted-foreground)]",children:"No data for this period"})]}),j.jsxs("div",{className:"glass-card p-4",children:[j.jsx("h3",{className:"text-sm font-semibold mb-4",children:"By Model"}),u.length>0?j.jsxs(j.Fragment,{children:[j.jsx(EP,{width:"100%",height:180,children:j.jsxs(Rte,{children:[j.jsx(xi,{data:u,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:70,strokeWidth:0,children:u.map((c,f)=>{var p;return j.jsx(Sh,{fill:Df[f%Df.length]},(p=u[f])==null?void 0:p.name)})}),j.jsx(vn,{contentStyle:{background:"#222",border:"1px solid #333",borderRadius:"8px",fontSize:"12px"}})]})}),j.jsx("div",{className:"space-y-1 mt-2",children:u.map((c,f)=>j.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[j.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:Df[f%Df.length]}}),j.jsx("span",{className:"text-[var(--color-muted-foreground)] truncate",children:c.name}),j.jsx("span",{className:"ml-auto font-mono",children:Ul(c.value)})]},c.name))})]}):j.jsx("div",{className:"h-[180px] flex items-center justify-center text-[var(--color-muted-foreground)]",children:"No data"})]})]})]})}function Bf({label:t,value:e}){return j.jsxs("div",{className:"glass-card p-4",children:[j.jsx("p",{className:"text-xs text-[var(--color-muted-foreground)]",children:t}),j.jsx("p",{className:"text-xl font-semibold mt-1",children:e})]})}function Ul(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function Nte(){const[t,e]=$.useState("shared"),[r,n]=$.useState([]),[i,a]=$.useState(null),[s,u]=$.useState(""),[c,f]=$.useState(!1),[p,h]=$.useState(""),[g,v]=$.useState(!1),[w,x]=$.useState("");$.useEffect(()=>{y()},[t]);function y(){Pt.get(`/wiki/${t}`).then(P=>n(P.pages)).catch(()=>n([]))}async function S(P){try{const O=await Pt.get(`/wiki/${t}/${P}`);u(O.content),a(P),f(!1)}catch{sr.error("Failed to load page")}}async function k(){if(i)try{await Pt.put(`/wiki/${t}/${i}`,{content:p}),u(p),f(!1),sr.success("Page saved")}catch{sr.error("Failed to save")}}async function E(){if(w.trim())try{await Pt.put(`/wiki/${t}/${w}`,{content:`# ${w}
|
|
334
334
|
|
|
335
335
|
`}),sr.success("Page created"),v(!1),x(""),y(),S(w)}catch{sr.error("Failed to create page")}}return j.jsxs("div",{className:"flex h-full",children:[j.jsxs("div",{className:"w-64 border-r border-[var(--color-border)] flex flex-col h-full",children:[j.jsx("header",{className:"h-14 flex items-center px-4 border-b border-[var(--color-border)] shrink-0",children:j.jsx("h1",{className:"text-lg font-semibold gradient-text",children:"Wiki"})}),j.jsx("div",{className:"flex gap-1 p-2 border-b border-[var(--color-border)]",children:["io","shared"].map(P=>j.jsx("button",{type:"button",onClick:()=>{e(P),a(null)},className:`px-2 py-1 rounded text-xs ${t===P?"bg-white/10 text-[var(--color-foreground)]":"text-[var(--color-muted-foreground)]"}`,children:P},P))}),j.jsx("div",{className:"flex-1 overflow-y-auto p-2",children:r.map(P=>j.jsxs("button",{type:"button",onClick:()=>S(P.name),className:`w-full text-left px-3 py-2 rounded-md text-sm flex items-center gap-2 transition-colors ${i===P.name?"bg-white/10":"hover:bg-white/5"}`,children:[j.jsx(GB,{size:14,className:"text-[var(--color-muted-foreground)]"}),P.name]},P.name))}),j.jsx("div",{className:"p-2 border-t border-[var(--color-border)]",children:g?j.jsxs("div",{className:"flex gap-1",children:[j.jsx("input",{type:"text",value:w,onChange:P=>x(P.target.value),placeholder:"page-name",className:"flex-1 px-2 py-1 rounded text-xs bg-[var(--color-input)] border border-[var(--color-border)] outline-none",onKeyDown:P=>P.key==="Enter"&&E()}),j.jsx("button",{type:"button",onClick:E,className:"px-2 py-1 rounded text-xs bg-[var(--color-accent)] text-white",children:"OK"})]}):j.jsxs("button",{type:"button",onClick:()=>v(!0),className:"w-full flex items-center gap-2 px-3 py-2 rounded-md text-xs text-[var(--color-muted-foreground)] hover:bg-white/5",children:[j.jsx(Xw,{size:14})," New page"]})})]}),j.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:i?j.jsxs(j.Fragment,{children:[j.jsxs("div",{className:"h-14 flex items-center px-6 border-b border-[var(--color-border)] justify-between shrink-0",children:[j.jsx("h2",{className:"font-semibold",children:i}),j.jsx("div",{className:"flex gap-2",children:c?j.jsxs("button",{type:"button",onClick:k,className:"flex items-center gap-1 px-3 py-1.5 rounded-md bg-[var(--color-accent)] text-white text-xs",children:[j.jsx(AR,{size:12})," Save"]}):j.jsx("button",{type:"button",onClick:()=>{f(!0),h(s)},className:"px-3 py-1.5 rounded-md bg-white/5 text-xs hover:bg-white/10",children:"Edit"})})]}),j.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:c?j.jsx("textarea",{value:p,onChange:P=>h(P.target.value),className:"w-full h-full bg-transparent font-mono text-sm outline-none resize-none"}):j.jsx("div",{className:"prose-io",dangerouslySetInnerHTML:{__html:Ve.parse(s)}})})]}):j.jsx("div",{className:"h-full flex items-center justify-center text-[var(--color-muted-foreground)]",children:j.jsxs("div",{className:"text-center",children:[j.jsx(OR,{size:48,className:"mx-auto mb-3 opacity-30"}),j.jsx("p",{children:"Select a page to view"})]})})})]})}function Mte({children:t}){const{session:e,supabase:r,loading:n}=QR();return n?j.jsx("div",{className:"min-h-screen flex items-center justify-center text-[var(--color-muted-foreground)]",children:"Loading..."}):r?e?j.jsx(j.Fragment,{children:t}):j.jsx(u5,{}):j.jsx(j.Fragment,{children:t})}function Lte(){return j.jsxs(y8,{children:[j.jsx("div",{className:"orb orb-1"}),j.jsx("div",{className:"orb orb-2"}),j.jsx("div",{className:"orb orb-3"}),j.jsx(Mte,{children:j.jsx(ND,{children:j.jsxs(Jr,{element:j.jsx(p4,{}),children:[j.jsx(Jr,{index:!0,element:j.jsx(s5,{})}),j.jsx(Jr,{path:"squads",element:j.jsx(Kk,{})}),j.jsx(Jr,{path:"squads/:name",element:j.jsx(Kk,{})}),j.jsx(Jr,{path:"feed",element:j.jsx(l5,{})}),j.jsx(Jr,{path:"skills",element:j.jsx(d5,{})}),j.jsx(Jr,{path:"schedules",element:j.jsx(c5,{})}),j.jsx(Jr,{path:"wiki",element:j.jsx(Nte,{})}),j.jsx(Jr,{path:"settings",element:j.jsx(f5,{})}),j.jsx(Jr,{path:"usage",element:j.jsx($te,{})}),j.jsx(Jr,{path:"*",element:j.jsx(RD,{to:"/",replace:!0})})]})})})]})}RL.createRoot(document.getElementById("root")).render(j.jsx($.StrictMode,{children:j.jsxs(a3,{children:[j.jsx(Lte,{}),j.jsx(z3,{theme:"dark",position:"bottom-right"})]})}));
|
|
336
|
-
//# sourceMappingURL=index-
|
|
336
|
+
//# sourceMappingURL=index-dINUWXx2.js.map
|