heyio 3.1.8 → 3.1.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.
@@ -426,7 +426,7 @@ Request ID: ${u}`),d){let A=`
426
426
  Resources:`;for(const O of d){if(!O||typeof O!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${O}`);A+=`
427
427
  - ${O}`}k+=A}return`${b}
428
428
  ${k}`}class Zt 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 zf extends Zt{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function aU({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 Zt({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 Zt({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 Zt({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 Zt({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 Zt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Zt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return a.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new Zt({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Zt({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 o=window.location.hostname;if(WN(o)){if(a.rp.id!==o)return new Zt({message:`The RP ID "${a.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Zt({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 Zt({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 Zt({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 Zt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function oU({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 Zt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Zt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(WN(n)){if(r.rpId!==n)return new Zt({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Zt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Zt({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 Zt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class sU{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 ex=new sU;function yE(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=Jh(t,["challenge","user","excludeCredentials"]),a=Ls(e).buffer,o=Object.assign(Object.assign({},r),{id:Ls(r.id).buffer}),l=Object.assign(Object.assign({},i),{challenge:a,user:o});if(n&&n.length>0){l.excludeCredentials=new Array(n.length);for(let u=0;u<n.length;u++){const d=n[u];l.excludeCredentials[u]=Object.assign(Object.assign({},d),{id:Ls(d.id).buffer,type:d.type||"public-key",transports:d.transports})}}return l}function vE(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=Jh(t,["challenge","allowCredentials"]),i=Ls(e).buffer,a=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){a.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){const l=r[o];a.allowCredentials[o]=Object.assign(Object.assign({},l),{id:Ls(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return a}function bE(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:_o(new Uint8Array(t.response.attestationObject)),clientDataJSON:_o(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function xE(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:_o(new Uint8Array(i.authenticatorData)),clientDataJSON:_o(new Uint8Array(i.clientDataJSON)),signature:_o(new Uint8Array(i.signature)),userHandle:i.userHandle?_o(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function WN(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Bf(){var t,e;return!!(xr()&&"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 GN(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new zf("Browser returned unexpected credential type",e)}:{data:null,error:new zf("Empty credential response",e)}}catch(e){return{data:null,error:aU({error:e,options:t})}}}async function KN(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new zf("Browser returned unexpected credential type",e)}:{data:null,error:new zf("Empty credential response",e)}}catch(e){return{data:null,error:oU({error:e,options:t})}}}const lU={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},cU={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Uf(...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 o=i[a];if(o!==void 0)if(Array.isArray(o))n[a]=o;else if(r(o))n[a]=o;else if(e(o)){const l=n[a];e(l)?n[a]=Uf(l,o):n[a]=Uf(o)}else n[a]=o}return n}function uU(t,e){return Uf(lU,t,e||{})}function dU(t,e){return Uf(cU,t,e||{})}class fU{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 o;try{const{data:l,error:u}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!l)return{data:null,error:u};const d=i??ex.createNewAbortSignal();if(l.webauthn.type==="create"){const{user:p}=l.webauthn.credential_options.publicKey;if(!p.name){const f=n;if(f)p.name=`${p.id}:${f}`;else{const v=(await this.client.getUser()).data.user,x=((o=v==null?void 0:v.user_metadata)===null||o===void 0?void 0:o.name)||(v==null?void 0:v.email)||(v==null?void 0:v.id)||"User";p.name=`${p.id}:${x}`}}p.displayName||(p.displayName=p.name)}switch(l.webauthn.type){case"create":{const p=uU(l.webauthn.credential_options.publicKey,a==null?void 0:a.create),{data:f,error:g}=await GN({publicKey:p,signal:d});return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}case"request":{const p=dU(l.webauthn.credential_options.publicKey,a==null?void 0:a.request),{data:f,error:g}=await KN(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:p,signal:d}));return f?{data:{factorId:e,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}}}catch(l){return be(l)?{data:null,error:l}:{data:null,error:new Xn("Unexpected error in challenge",l)}}}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 Fs("rpId is required for WebAuthn authentication")};try{if(!Bf())return{data:null,error:new Xn("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:a});if(!o)return{data:null,error:l};const{webauthn:u}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:u.type,rpId:r,rpOrigins:n,credential_response:u.credential_response}})}catch(o){return be(o)?{data:null,error:o}:{data:null,error:new Xn("Unexpected error in authenticate",o)}}}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 Fs("rpId is required for WebAuthn registration")};try{if(!Bf())return{data:null,error:new Xn("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(p=>{var f;return(f=p.data)===null||f===void 0?void 0:f.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:l};const{data:u,error:d}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:a});return u?this._verify({factorId:o.id,challengeId:u.challengeId,webauthn:{rpId:r,rpOrigins:n,type:u.webauthn.type,credential_response:u.webauthn.credential_response}}):{data:null,error:d}}catch(o){return be(o)?{data:null,error:o}:{data:null,error:new Xn("Unexpected error in register",o)}}}}tU();const hU={url:y6,storageKey:v6,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:b6,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function wE(t,e,r){return await r()}const _s={};class qc{get jwks(){var e,r;return(r=(e=_s[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){_s[this.storageKey]=Object.assign(Object.assign({},_s[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=_s[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){_s[this.storageKey]=Object.assign(Object.assign({},_s[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 o=Object.assign(Object.assign({},hU),e);if(this.storageKey=o.storageKey,this.instanceID=(r=qc.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,qc.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!o.debug,typeof o.debug=="function"&&(this.logger=o.debug),this.instanceID>0&&xr()){const l=`${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(l),this.logDebugMessages&&console.trace(l)}if(this.persistSession=o.persistSession,this.autoRefreshToken=o.autoRefreshToken,this.experimental=(n=o.experimental)!==null&&n!==void 0?n:{},this.admin=new Q6({url:o.url,headers:o.headers,fetch:o.fetch,experimental:this.experimental}),this.url=o.url,this.headers=o.headers,this.fetch=qN(o.fetch),this.lock=o.lock||wE,this.detectSessionInUrl=o.detectSessionInUrl,this.flowType=o.flowType,this.hasCustomAuthorizationHeader=o.hasCustomAuthorizationHeader,this.throwOnError=o.throwOnError,this.lockAcquireTimeout=o.lockAcquireTimeout,o.lock?this.lock=o.lock:this.persistSession&&xr()&&(!((i=globalThis==null?void 0:globalThis.navigator)===null||i===void 0)&&i.locks)?this.lock=eU:this.lock=wE,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 fU(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?(o.storage?this.storage=o.storage:UN()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=mE(this.memoryStorage)),o.userStorage&&(this.userStorage=o.userStorage)):(this.memoryStorage={},this.storage=mE(this.memoryStorage)),xr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(l){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",l)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async l=>{this._debug("received broadcast notification from other tab or client",l);try{await this._notifyAllSubscribers(l.data.event,l.data.session,!1)}catch(u){this._debug("#broadcastChannel","error",u)}})}o.skipAutoInitialize||this.initialize().catch(l=>{this._debug("#initialize()","error",l)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${DN}) ${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(xr()&&(r=R6(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),xr()&&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),k6(a)){const u=(e=a.details)===null||e===void 0?void 0:e.code;if(u==="identity_already_exists"||u==="identity_not_found"||u==="single_identity_not_deletable")return{error:a}}return{error:a}}const{session:o,redirectType:l}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return be(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 Pe(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:On}),{data:o,error:l}=a;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(be(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:f,options:g}=e;let v=null,x=null;this.flowType==="pkce"&&([v,x]=await ws(this.storage,this.storageKey)),a=await Pe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:p,password:f,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:x},xform:On})}else if("phone"in e){const{phone:p,password:f,options:g}=e;a=await Pe(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:p,password:f,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:On})}else throw new lf("You must provide either an email or phone number and a password");const{data:o,error:l}=a;if(l||!o)return await br(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(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:o,options:l}=e;r=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:hE})}else if("phone"in e){const{phone:a,password:o,options:l}=e;r=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:hE})}else throw new lf("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 xs;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(be(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,o,l,u,d,p,f,g;let v,x;if("message"in e)v=e.message,x=e.signature;else{const{chain:_,wallet:b,statement:k,options:A}=e;let O;if(xr())if(typeof b=="object")O=b;else{const I=window;if("ethereum"in I&&typeof I.ethereum=="object"&&"request"in I.ethereum&&typeof I.ethereum.request=="function")O=I.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 b!="object"||!(A!=null&&A.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=b}const C=new URL((r=A==null?void 0:A.url)!==null&&r!==void 0?r:window.location.href),E=await O.request({method:"eth_requestAccounts"}).then(I=>I).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!E||E.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=HN(E[0]);let P=(n=A==null?void 0:A.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!P){const I=await O.request({method:"eth_chainId"});P=rU(I)}const N={domain:C.host,address:T,statement:k,uri:C.href,version:"1",chainId:P,nonce:(i=A==null?void 0:A.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(a=A==null?void 0:A.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=A==null?void 0:A.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(u=A==null?void 0:A.signInWithEthereum)===null||u===void 0?void 0:u.notBefore,requestId:(d=A==null?void 0:A.signInWithEthereum)===null||d===void 0?void 0:d.requestId,resources:(p=A==null?void 0:A.signInWithEthereum)===null||p===void 0?void 0:p.resources};v=iU(N),x=await O.request({method:"personal_sign",params:[nU(v),T]})}try{const{data:_,error:b}=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:v,signature:x},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:On});if(b)throw b;if(!_||!_.session||!_.user){const k=new xs;return this._returnResult({data:{user:null,session:null},error:k})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:b})}catch(_){if(be(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async signInWithSolana(e){var r,n,i,a,o,l,u,d,p,f,g,v;let x,_;if("message"in e)x=e.message,_=e.signature;else{const{chain:b,wallet:k,statement:A,options:O}=e;let C;if(xr())if(typeof k=="object")C=k;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))C=T.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 k!="object"||!(O!=null&&O.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");C=k}const E=new URL((r=O==null?void 0:O.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in C&&C.signIn){const T=await C.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},O==null?void 0:O.signInWithSolana),{version:"1",domain:E.host,uri:E.href}),A?{statement:A}:null));let P;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")P=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)P=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)x=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),_=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in C)||typeof C.signMessage!="function"||!("publicKey"in C)||typeof C!="object"||!C.publicKey||!("toBase58"in C.publicKey)||typeof C.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");x=[`${E.host} wants you to sign in with your Solana account:`,C.publicKey.toBase58(),...A?["",A,""]:[""],"Version: 1",`URI: ${E.href}`,`Issued At: ${(i=(n=O==null?void 0:O.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((a=O==null?void 0:O.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${O.signInWithSolana.notBefore}`]:[],...!((o=O==null?void 0:O.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${O.signInWithSolana.expirationTime}`]:[],...!((l=O==null?void 0:O.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${O.signInWithSolana.chainId}`]:[],...!((u=O==null?void 0:O.signInWithSolana)===null||u===void 0)&&u.nonce?[`Nonce: ${O.signInWithSolana.nonce}`]:[],...!((d=O==null?void 0:O.signInWithSolana)===null||d===void 0)&&d.requestId?[`Request ID: ${O.signInWithSolana.requestId}`]:[],...!((f=(p=O==null?void 0:O.signInWithSolana)===null||p===void 0?void 0:p.resources)===null||f===void 0)&&f.length?["Resources",...O.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
429
- `);const T=await C.signMessage(new TextEncoder().encode(x),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");_=T}}try{const{data:b,error:k}=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:x,signature:_o(_)},!((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:On});if(k)throw k;if(!b||!b.session||!b.user){const A=new xs;return this._returnResult({data:{user:null,session:null},error:A})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:k})}catch(b){if(be(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){const r=await go(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new E6;const{data:a,error:o}=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:On});if(await br(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!a||!a.session||!a.user){const l=new xs;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}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:o})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(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:o}=e,l=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:a,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:On}),{data:u,error:d}=l;if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!u||!u.session||!u.user){const p=new xs;return this._returnResult({data:{user:null,session:null},error:p})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",u.session)),this._returnResult({data:u,error:d})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,a,o;try{if("email"in e){const{email:l,options:u}=e;let d=null,p=null;this.flowType==="pkce"&&([d,p]=await ws(this.storage,this.storageKey));const{error:f}=await Pe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=u==null?void 0:u.data)!==null&&r!==void 0?r:{},create_user:(n=u==null?void 0:u.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:d,code_challenge_method:p},redirectTo:u==null?void 0:u.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){const{phone:l,options:u}=e,{data:d,error:p}=await Pe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=u==null?void 0:u.data)!==null&&i!==void 0?i:{},create_user:(a=u==null?void 0:u.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},channel:(o=u==null?void 0:u.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:p})}throw new lf("You must provide either an email or phone number.")}catch(l){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}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:o,error:l}=await Pe(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:On});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const u=o.session,d=o.user;return u!=null&&u.access_token&&(await this._saveSession(u),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(i){if(be(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,a,o;try{let l=null,u=null;this.flowType==="pkce"&&([l,u]=await ws(this.storage,this.storageKey));const d=await Pe(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:l,code_challenge_method:u}),headers:this.headers,xform:Y6});return!((a=d.data)===null||a===void 0)&&a.url&&xr()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(d.data.url),this._returnResult(d)}catch(l){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(l))return this._returnResult({data:null,error:l});throw l}}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 pr;const{error:i}=await Pe(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(be(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:o}=await Pe(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:o})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:o,error:l}=await Pe(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:o==null?void 0:o.message_id},error:l})}throw new lf("You must provide either an email or phone number and a type")}catch(r){if(be(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 go(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()<_g:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const o=await go(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=kg()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=G6(e.user,o),o.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 Pe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Pa}):await this._useSession(async r=>{var n,i,a;const{data:o,error:l}=r;if(l)throw l;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new pr}:await Pe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:Pa})})}catch(r){if(be(r))return sf(r)&&(await this._removeSession(),await br(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 pr;const o=i.session;let l=null,u=null;this.flowType==="pkce"&&e.email!=null&&([l,u]=await ws(this.storage,this.storageKey));const{data:d,error:p}=await Pe(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:u}),jwt:o.access_token,xform:Pa});if(p)throw p;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(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 pr;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:o}=uf(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){const{data:l,error:u}=await this._callRefreshToken(e.refresh_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l)return{data:{user:null,session:null},error:null};a=l}else{const{data:l,error:u}=await this._getUser(e.access_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});a={access_token:e.access_token,refresh_token:e.refresh_token,user:l.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(be(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:o,error:l}=r;if(l)throw l;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new pr;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(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!xr())throw new cf("No browser detected.");if(e.error||e.error_description||e.error_code)throw new cf(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 oE("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new cf("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 oE("No code detected.");const{data:O,error:C}=await this._exchangeCodeForSession(e.code);if(C)throw C;const E=new URL(window.location.href);return E.searchParams.delete("code"),window.history.replaceState(window.history.state,"",E.toString()),{data:{session:O.session,redirectType:(n=O.redirectType)!==null&&n!==void 0?n:null},error:null}}const{provider_token:i,provider_refresh_token:a,access_token:o,refresh_token:l,expires_in:u,expires_at:d,token_type:p}=e;if(!o||!u||!l||!p)throw new cf("No session defined in URL");const f=Math.round(Date.now()/1e3),g=parseInt(u);let v=f+g;d&&(v=parseInt(d));const x=v-f;x*1e3<=js&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${g}s`);const _=v-g;f-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,v,f):f-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",_,v,f);const{data:b,error:k}=await this._getUser(o);if(k)throw k;const A={provider_token:i,provider_refresh_token:a,access_token:o,expires_in:g,expires_at:v,refresh_token:l,token_type:p,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:A,redirectType:e.type},error:null})}catch(i){if(be(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 go(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&&!sf(a))return this._returnResult({error:a});const o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(S6(l)&&(l.status===404||l.status===401||l.status===403)||sf(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await br(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=N6(),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:o}=r;if(o)throw o;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),sf(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await ws(this.storage,this.storageKey,!0));try{return await Pe(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 br(this.storage,`${this.storageKey}-code-verifier`),be(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(be(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 o,l,u,d,p;const{data:f,error:g}=a;if(g)throw g;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return await Pe(this.fetch,"GET",v,{headers:this.headers,jwt:(p=(d=f.session)===null||d===void 0?void 0:d.access_token)!==null&&p!==void 0?p:void 0})});if(i)throw i;return xr()&&!(!((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(be(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:o,provider:l,token:u,access_token:d,nonce:p}=e,f=await Pe(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:l,id_token:u,access_token:d,nonce:p,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:On}),{data:g,error:v}=f;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 xs}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:v}))}catch(i){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(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:o}=r;if(o)throw o;return await Pe(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(be(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 M6(async i=>(i>0&&await $6(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Pe(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:On})),(i,a)=>{const o=200*Math.pow(2,i);return a&&Sg(a)&&Date.now()+o-n<js})}catch(n){if(this._debug(r,"error",n),be(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),xr()&&!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 go(this.storage,this.storageKey);if(i&&this.userStorage){let o=await go(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await Ps(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:kg()}else if(i&&!i.user&&!i.user){const o=await go(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(i.user=o.user,await br(this.storage,this.storageKey+"-user"),await Ps(this.storage,this.storageKey,i)):i.user=kg()}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()<_g;if(this._debug(n,`session has${a?"":" not"} expired with margin of ${_g}s`),a){if(this.autoRefreshToken&&i.refresh_token){const{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Sg(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:l}=await this._getUser(i.access_token);!l&&(o!=null&&o.user)?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}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 pr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ep;const{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new pr;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const l={data:a.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(a){if(this._debug(i,"error",a),be(a)){const o={data:null,error:a};return Sg(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}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=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,r)}catch(u){a.push(u)}});if(await Promise.all(o),a.length>0){for(let l=0;l<a.length;l+=1)console.error(a[l]);throw a[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await br(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 Ps(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const a=dE(i);await Ps(this.storage,this.storageKey,a)}else{const i=dE(r);await Ps(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await br(this.storage,this.storageKey),await br(this.storage,this.storageKey+"-code-verifier"),await br(this.storage,this.storageKey+"-user"),this.userStorage&&await br(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&xr()&&(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(),js);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)/js);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${js}ms, refresh threshold is ${Yb} ticks`),i<=Yb&&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 FN)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!xr()||!(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,o]=await ws(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(l.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 Pe(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(be(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:o}=r;if(o)return this._returnResult({data:null,error:o});const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:u,error:d}=await Pe(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return d?this._returnResult({data:null,error:d}):(e.factorType==="totp"&&u.type==="totp"&&(!((i=u==null?void 0:u.totp)===null||i===void 0)&&i.qr_code)&&(u.totp.qr_code=`data:image/svg+xml;utf-8,${u.totp.qr_code}`),this._returnResult({data:u,error:null}))})}catch(r){if(be(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 o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?bE(e.webauthn.credential_response):xE(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await Pe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(r){if(be(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 o=await Pe(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(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:yE(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:vE(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(be(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}=uf(e);let x=null;v.aal&&(x=v.aal);let _=x;const{data:{user:b},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((n=(r=b==null?void 0:b.factors)===null||r===void 0?void 0:r.filter(C=>C.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(_="aal2");const O=v.amr||[];return{data:{currentLevel:x,nextLevel:_,currentAuthenticationMethods:O},error:null}}catch(v){if(be(v))return this._returnResult({data:null,error:v});throw v}const{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:u}=uf(o.access_token);let d=null;u.aal&&(d=u.aal);let p=d;((a=(i=o.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=u.amr||[];return{data:{currentLevel:d,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 Pe(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 pr})})}catch(r){if(be(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 pr});const o=await Pe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(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 pr});const o=await Pe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(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 Pe(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 pr})})}catch(e){if(be(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 Pe(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 pr})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(l=>l.kid===e);if(n)return n;const i=Date.now();if(n=this.jwks.keys.find(l=>l.kid===e),n&&this.jwks_cached_at+w6>i)return n;const{data:a,error:o}=await Pe(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=i,n=a.keys.find(l=>l.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:v,error:x}=await this.getSession();if(x||!v.session)return this._returnResult({data:null,error:x});n=v.session.access_token}const{header:i,payload:a,signature:o,raw:{header:l,payload:u}}=uf(n);r!=null&&r.allowExpired||F6(a.exp);const d=!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(!d){const{error:v}=await this.getUser(n);if(v)throw v;return{data:{claims:a,header:i,signature:o},error:null}}const p=H6(i.alg),f=await crypto.subtle.importKey("jwk",d,p,!0,["verify"]);if(!await crypto.subtle.verify(p,f,o,j6(`${l}.${u}`)))throw new Qb("Invalid JWT signature");return{data:{claims:a,header:i,signature:o},error:null}}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,i;qn(this.experimental);try{if(!Bf())return this._returnResult({data:null,error:new Xn("Browser does not support WebAuthn",null)});const{data:a,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!a)return this._returnResult({data:null,error:o});const l=vE(a.options),u=(i=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.signal)!==null&&i!==void 0?i:ex.createNewAbortSignal(),{data:d,error:p}=await KN({publicKey:l,signal:u});if(p||!d)return this._returnResult({data:null,error:p??new Xn("WebAuthn ceremony failed",null)});const f=xE(d);return this._verifyPasskeyAuthentication({challengeId:a.challenge_id,credential:f})}catch(a){if(be(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(e){var r,n;qn(this.experimental);try{if(!Bf())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 o=yE(i.options),l=(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:ex.createNewAbortSignal(),{data:u,error:d}=await GN({publicKey:o,signal:l});if(d||!u)return this._returnResult({data:null,error:d??new Xn("WebAuthn ceremony failed",null)});const p=bE(u);return this._verifyPasskeyRegistration({challengeId:i.challenge_id,credential:p})}catch(i){if(be(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyRegistration(){qn(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 pr});const{data:i,error:a}=await Pe(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(be(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){qn(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 pr});const{data:a,error:o}=await Pe(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;qn(this.experimental);try{const{data:n,error:i}=await Pe(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(be(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){qn(this.experimental);try{const{data:r,error:n}=await Pe(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:On});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(be(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){qn(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 pr});const{data:i,error:a}=await Pe(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){qn(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 pr});const{data:a,error:o}=await Pe(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){qn(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 pr});const{error:a}=await Pe(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(be(r))return this._returnResult({data:null,error:r});throw r}}}qc.nextInstanceID={};const pU=qc,mU="2.106.2";let Ec="";typeof Deno<"u"?Ec="deno":typeof document<"u"?Ec="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ec="react-native":Ec="node";const gU={"X-Client-Info":`supabase-js-${Ec}/${mU}`},yU={headers:gU},vU={schema:"public"},bU={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},xU={},wU={enabled:!1,respectSamplingDecision:!0};function _U(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function l(p){try{d(n.next(p))}catch(f){o(f)}}function u(p){try{d(n.throw(p))}catch(f){o(f)}}function d(p){p.done?a(p.value):i(p.value).then(l,u)}d((n=n.apply(t,[])).next())})}let Og=null;const SU="@opentelemetry/api";function kU(){return Og===null&&(Og=import(SU).catch(()=>null)),Og}function EU(){return _U(this,void 0,void 0,function*(){try{const t=yield kU();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 OU(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 o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(n)||!o.test(i)||!o.test(a)||n==="00000000000000000000000000000000"||i==="0000000000000000"?null:{version:r,traceId:n,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)===1}}function AU(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(TU(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 TU(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 CU(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 Fc(t){"@babel/helpers - typeof";return Fc=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},Fc(t)}function jU(t,e){if(Fc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Fc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function PU(t){var e=jU(t,"string");return Fc(e)=="symbol"?e:e+""}function NU(t,e,r){return(e=PU(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _E(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 Ft(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?_E(Object(r),!0).forEach(function(n){NU(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):_E(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}const RU=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),IU=()=>Headers,$U=(t,e,r,n,i)=>{const a=RU(n),o=IU(),l=(i==null?void 0:i.enabled)===!0,u=(i==null?void 0:i.respectSamplingDecision)!==!1,d=l?CU(e):null;return async(p,f)=>{var g;const v=(g=await r())!==null&&g!==void 0?g:t;let x=new o(f==null?void 0:f.headers);if(x.has("apikey")||x.set("apikey",t),x.has("Authorization")||x.set("Authorization",`Bearer ${v}`),d){const _=await MU(p,d,u);_&&(_.traceparent&&!x.has("traceparent")&&x.set("traceparent",_.traceparent),_.tracestate&&!x.has("tracestate")&&x.set("tracestate",_.tracestate),_.baggage&&!x.has("baggage")&&x.set("baggage",_.baggage))}return a(p,Ft(Ft({},f),{},{headers:x}))}};async function MU(t,e,r){if(!AU(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=await EU();if(!n||!n.traceparent)return null;if(r){const i=OU(n.traceparent);if(i&&!i.isSampled)return null}return n}function SE(t){return typeof t=="boolean"?{enabled:t}:t}function LU(t){return t.endsWith("/")?t:t+"/"}function DU(t,e){var r,n,i,a,o,l;const{db:u,auth:d,realtime:p,global:f}=t,{db:g,auth:v,realtime:x,global:_}=e,b=SE(t.tracePropagation),k=SE(e.tracePropagation),A={db:Ft(Ft({},g),u),auth:Ft(Ft({},v),d),realtime:Ft(Ft({},x),p),storage:{},global:Ft(Ft(Ft({},_),f),{},{headers:Ft(Ft({},(r=_==null?void 0:_.headers)!==null&&r!==void 0?r:{}),(n=f==null?void 0:f.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(i=(a=b==null?void 0:b.enabled)!==null&&a!==void 0?a:k==null?void 0:k.enabled)!==null&&i!==void 0?i:!1,respectSamplingDecision:(o=(l=b==null?void 0:b.respectSamplingDecision)!==null&&l!==void 0?l:k==null?void 0:k.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?A.accessToken=t.accessToken:delete A.accessToken,A}function zU(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(LU(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var BU=class extends pU{constructor(t){super(t)}},UU=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;const a=zU(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 o=`sb-${a.hostname.split(".")[0]}-auth-token`,l={db:vU,realtime:xU,auth:Ft(Ft({},bU),{},{storageKey:o}),global:yU,tracePropagation:wU},u=DU(r??{},l);if(this.settings=u,this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken)this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(p,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}});else{var d;this.auth=this._initSupabaseAuthClient((d=u.auth)!==null&&d!==void 0?d:{},this.headers,u.global.fetch)}this.fetch=$U(e,t,this._getAccessToken.bind(this),u.global.fetch,u.tracePropagation),this.realtime=this._initRealtimeClient(Ft({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},u.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 n8(new URL("rest/v1",a).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch,timeout:u.db.timeout,urlLengthLimit:u.db.urlLengthLimit}),this.storage=new g6(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new KB(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:o,lock:l,debug:u,throwOnError:d,experimental:p,lockAcquireTimeout:f,skipAutoInitialize:g},v,x){const _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new BU({url:this.authUrl.href,headers:Ft(Ft({},_),v),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:l,debug:u,throwOnError:d,experimental:p,fetch:x,lockAcquireTimeout:f,skipAutoInitialize:g,hasCustomAuthorizationHeader:Object.keys(this.headers).some(b=>b.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new z8(this.realtimeUrl.href,Ft(Ft({},t),{},{params:Ft(Ft({},{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 qU=(t,e,r)=>new UU(t,e,r);function FU(){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}FU()&&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 VN=R.createContext({session:null,supabase:null,loading:!0,signIn:async()=>({error:"Not initialized"}),signOut:async()=>{}});function tp(){return R.useContext(VN)}function HU({children:t}){const[e,r]=R.useState(null),[n,i]=R.useState(null),[a,o]=R.useState(!0),l=R.useRef(null);R.useEffect(()=>{X4(()=>{var p;return((p=l.current)==null?void 0:p.access_token)??null})},[]),R.useEffect(()=>{et.get("/config").then(({config:p})=>{if(p.supabase.projectUrl&&p.supabase.anonKey){const f=qU(p.supabase.projectUrl,p.supabase.anonKey);r(f),f.auth.getSession().then(({data:v})=>{l.current=v.session,i(v.session),o(!1)});const{data:{subscription:g}}=f.auth.onAuthStateChange((v,x)=>{l.current=x,i(x)});return()=>g.unsubscribe()}o(!1)}).catch(()=>{o(!1)})},[]);async function u(p,f){if(!e)return{error:"Supabase not configured"};const{error:g}=await e.auth.signInWithPassword({email:p,password:f});return{error:(g==null?void 0:g.message)??null}}async function d(){e&&(await e.auth.signOut(),l.current=null,i(null))}return y.jsx(VN.Provider,{value:{session:n,supabase:e,loading:a,signIn:u,signOut:d},children:t})}const WU=[{to:"/squads",icon:Vh,label:"Squads"},{to:"/skills",icon:Mb,label:"Skills"},{to:"/schedules",icon:R5,label:"Schedules"},{to:"/wiki",icon:BP,label:"Wiki"},{to:"/usage",icon:$5,label:"Usage"}],GU=[{to:"/",icon:WP,label:"Chat"},{to:"/feed",icon:Ib,label:"Inbox"},{to:"/settings",icon:M4,label:"Settings"}];function kE({to:t,icon:e,label:r,collapsed:n,badge:i}){return y.jsxs(LP,{to:t,end:t==="/",title:n?r:void 0,className:({isActive:a})=>Sc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono transition-colors cursor-pointer relative",n?"justify-center":"",a?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04]"),style:({isActive:a})=>a?{background:"rgba(228,58,156,0.1)"}:void 0,children:[y.jsx(e,{className:"w-3.5 h-3.5 flex-shrink-0"}),!n&&r,i!=null&&i>0&&y.jsx("span",{className:"absolute top-1 right-1 min-w-[14px] h-[14px] flex items-center justify-center rounded-full bg-[#E43A9C] text-[9px] text-white font-mono px-1",children:i>99?"99+":i})]})}function KU(){const[t,e]=R.useState(!1),[r,n]=R.useState("..."),[i,a]=R.useState(0),{supabase:o}=tp();return R.useEffect(()=>{let l=!0;et.get("/version").then(({version:d})=>{l&&n(d)}).catch(()=>{l&&n("unknown")}),et.get("/inbox/unread-count").then(({count:d})=>{l&&a(d)}).catch(()=>{});const u=setInterval(()=>{et.get("/inbox/unread-count").then(({count:d})=>{l&&a(d)}).catch(()=>{})},3e4);return()=>{l=!1,clearInterval(u)}},[]),y.jsxs("div",{className:"flex h-screen overflow-hidden bg-background relative",children:[y.jsxs("div",{className:Sc("flex-shrink-0 flex flex-col border-r border-white/[0.06] bg-[#181818] transition-all duration-200",t?"w-[52px]":"w-[210px]"),children:[y.jsx("div",{className:Sc("h-[52px] flex items-center border-b border-white/[0.06] flex-shrink-0",t?"justify-center px-3":"justify-between pl-4 pr-3"),children:t?y.jsx(Ra,{height:26}):y.jsxs("div",{className:"flex items-center gap-2.5",children:[y.jsx(Ra,{height:26}),y.jsx("span",{className:"text-2xl text-white tracking-wider leading-none",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"IO"})]})}),y.jsx("nav",{className:"flex-1 py-2 px-1.5 space-y-0.5 overflow-y-auto",children:WU.map(l=>y.jsx(kE,{collapsed:t,...l},l.to))}),y.jsxs("div",{className:"flex-shrink-0 border-t border-white/[0.06]",children:[y.jsx("div",{className:"py-1.5 px-1.5 space-y-0.5",children:GU.map(l=>y.jsx(kE,{collapsed:t,badge:l.to==="/feed"?i:void 0,...l},l.to))}),y.jsxs("div",{className:"border-t border-white/[0.05] py-1.5 px-1.5 space-y-0.5",children:[y.jsxs("a",{href:"https://github.com/michaeljolley/io",target:"_blank",rel:"noreferrer",title:"GitHub",className:Sc("flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:[y.jsx(l4,{className:"w-3.5 h-3.5 flex-shrink-0"}),!t&&y.jsxs("span",{className:"text-zinc-700",children:["v",r]})]}),y.jsx("button",{type:"button",onClick:()=>e(!t),title:t?"Expand sidebar":"Collapse sidebar",className:Sc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:t?y.jsx(jw,{className:"w-3.5 h-3.5 flex-shrink-0"}):y.jsx(Cu,{className:"w-3.5 h-3.5 flex-shrink-0"})})]})]})]}),y.jsxs("div",{className:"flex flex-col flex-1 min-w-0 overflow-hidden",children:[y.jsxs("div",{className:"h-[52px] flex-shrink-0 flex items-center justify-between px-4 border-b border-white/[0.06] bg-[#181818]",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(UB,{status:"connected"}),y.jsx("span",{className:"text-[11px] font-mono text-green-400",children:"connected"})]}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[y.jsx(rz,{}),o&&y.jsx("button",{type:"button",onClick:()=>o.auth.signOut(),className:"p-2 rounded-xl hover:bg-white/[0.05] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",title:"Sign out",children:y.jsx(y4,{className:"w-3.5 h-3.5"})})]})]}),y.jsxs("main",{className:"flex-1 overflow-hidden flex flex-col min-h-0 relative",children:[y.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",style:{zIndex:0},children:[y.jsx("div",{className:"orb orb-pink"}),y.jsx("div",{className:"orb orb-gray"})]}),y.jsx(uD,{})]})]})]})}function VU(){const{session:t}=tp(),e=ml(),{messages:r,streaming:n,isStreaming:i,isThinking:a,sendChatMessage:o,addUserMessage:l,uploadAttachment:u}=eN(),[d,p]=R.useState(""),[f,g]=R.useState(null),[v,x]=R.useState(null),_=R.useRef(null),b=R.useRef(null),k=R.useRef(null);R.useLayoutEffect(()=>{const E=_.current;E&&(E.scrollTop=E.scrollHeight)},[r,n,a]);async function A(){const E=d.trim();if(!E&&!f||i||a)return;const T=crypto.randomUUID(),P=f==null?void 0:f.name,N=[E,P?`Attachment: ${P}`:""].filter(Boolean).join(`
429
+ `);const T=await C.signMessage(new TextEncoder().encode(x),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");_=T}}try{const{data:b,error:k}=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:x,signature:_o(_)},!((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:On});if(k)throw k;if(!b||!b.session||!b.user){const A=new xs;return this._returnResult({data:{user:null,session:null},error:A})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:k})}catch(b){if(be(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){const r=await go(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new E6;const{data:a,error:o}=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:On});if(await br(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!a||!a.session||!a.user){const l=new xs;return this._returnResult({data:{user:null,session:null,redirectType:null},error:l})}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:o})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(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:o}=e,l=await Pe(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:a,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:On}),{data:u,error:d}=l;if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!u||!u.session||!u.user){const p=new xs;return this._returnResult({data:{user:null,session:null},error:p})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",u.session)),this._returnResult({data:u,error:d})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,a,o;try{if("email"in e){const{email:l,options:u}=e;let d=null,p=null;this.flowType==="pkce"&&([d,p]=await ws(this.storage,this.storageKey));const{error:f}=await Pe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(r=u==null?void 0:u.data)!==null&&r!==void 0?r:{},create_user:(n=u==null?void 0:u.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:d,code_challenge_method:p},redirectTo:u==null?void 0:u.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){const{phone:l,options:u}=e,{data:d,error:p}=await Pe(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=u==null?void 0:u.data)!==null&&i!==void 0?i:{},create_user:(a=u==null?void 0:u.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},channel:(o=u==null?void 0:u.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:p})}throw new lf("You must provide either an email or phone number.")}catch(l){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}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:o,error:l}=await Pe(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:On});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const u=o.session,d=o.user;return u!=null&&u.access_token&&(await this._saveSession(u),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(i){if(be(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,a,o;try{let l=null,u=null;this.flowType==="pkce"&&([l,u]=await ws(this.storage,this.storageKey));const d=await Pe(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:l,code_challenge_method:u}),headers:this.headers,xform:Y6});return!((a=d.data)===null||a===void 0)&&a.url&&xr()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(d.data.url),this._returnResult(d)}catch(l){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(l))return this._returnResult({data:null,error:l});throw l}}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 pr;const{error:i}=await Pe(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(be(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:o}=await Pe(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:o})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:o,error:l}=await Pe(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:o==null?void 0:o.message_id},error:l})}throw new lf("You must provide either an email or phone number and a type")}catch(r){if(be(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 go(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()<_g:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const o=await go(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=kg()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=G6(e.user,o),o.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 Pe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Pa}):await this._useSession(async r=>{var n,i,a;const{data:o,error:l}=r;if(l)throw l;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new pr}:await Pe(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:Pa})})}catch(r){if(be(r))return sf(r)&&(await this._removeSession(),await br(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 pr;const o=i.session;let l=null,u=null;this.flowType==="pkce"&&e.email!=null&&([l,u]=await ws(this.storage,this.storageKey));const{data:d,error:p}=await Pe(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:u}),jwt:o.access_token,xform:Pa});if(p)throw p;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(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 pr;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:o}=uf(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){const{data:l,error:u}=await this._callRefreshToken(e.refresh_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l)return{data:{user:null,session:null},error:null};a=l}else{const{data:l,error:u}=await this._getUser(e.access_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});a={access_token:e.access_token,refresh_token:e.refresh_token,user:l.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(be(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:o,error:l}=r;if(l)throw l;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new pr;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(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!xr())throw new cf("No browser detected.");if(e.error||e.error_description||e.error_code)throw new cf(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 oE("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new cf("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 oE("No code detected.");const{data:O,error:C}=await this._exchangeCodeForSession(e.code);if(C)throw C;const E=new URL(window.location.href);return E.searchParams.delete("code"),window.history.replaceState(window.history.state,"",E.toString()),{data:{session:O.session,redirectType:(n=O.redirectType)!==null&&n!==void 0?n:null},error:null}}const{provider_token:i,provider_refresh_token:a,access_token:o,refresh_token:l,expires_in:u,expires_at:d,token_type:p}=e;if(!o||!u||!l||!p)throw new cf("No session defined in URL");const f=Math.round(Date.now()/1e3),g=parseInt(u);let v=f+g;d&&(v=parseInt(d));const x=v-f;x*1e3<=js&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${g}s`);const _=v-g;f-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,v,f):f-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",_,v,f);const{data:b,error:k}=await this._getUser(o);if(k)throw k;const A={provider_token:i,provider_refresh_token:a,access_token:o,expires_in:g,expires_at:v,refresh_token:l,token_type:p,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:A,redirectType:e.type},error:null})}catch(i){if(be(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 go(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&&!sf(a))return this._returnResult({error:a});const o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){const{error:l}=await this.admin.signOut(o,e);if(l&&!(S6(l)&&(l.status===404||l.status===401||l.status===403)||sf(l)))return this._returnResult({error:l})}return e!=="others"&&(await this._removeSession(),await br(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=N6(),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:o}=r;if(o)throw o;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),sf(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await ws(this.storage,this.storageKey,!0));try{return await Pe(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 br(this.storage,`${this.storageKey}-code-verifier`),be(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(be(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 o,l,u,d,p;const{data:f,error:g}=a;if(g)throw g;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=e.options)===null||l===void 0?void 0:l.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return await Pe(this.fetch,"GET",v,{headers:this.headers,jwt:(p=(d=f.session)===null||d===void 0?void 0:d.access_token)!==null&&p!==void 0?p:void 0})});if(i)throw i;return xr()&&!(!((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(be(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:o,provider:l,token:u,access_token:d,nonce:p}=e,f=await Pe(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:l,id_token:u,access_token:d,nonce:p,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:On}),{data:g,error:v}=f;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 xs}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:v}))}catch(i){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(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:o}=r;if(o)throw o;return await Pe(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(be(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 M6(async i=>(i>0&&await $6(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Pe(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:On})),(i,a)=>{const o=200*Math.pow(2,i);return a&&Sg(a)&&Date.now()+o-n<js})}catch(n){if(this._debug(r,"error",n),be(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),xr()&&!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 go(this.storage,this.storageKey);if(i&&this.userStorage){let o=await go(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await Ps(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:kg()}else if(i&&!i.user&&!i.user){const o=await go(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(i.user=o.user,await br(this.storage,this.storageKey+"-user"),await Ps(this.storage,this.storageKey,i)):i.user=kg()}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()<_g;if(this._debug(n,`session has${a?"":" not"} expired with margin of ${_g}s`),a){if(this.autoRefreshToken&&i.refresh_token){const{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Sg(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:l}=await this._getUser(i.access_token);!l&&(o!=null&&o.user)?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}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 pr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ep;const{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new pr;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const l={data:a.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(a){if(this._debug(i,"error",a),be(a)){const o={data:null,error:a};return Sg(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}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=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(e,r)}catch(u){a.push(u)}});if(await Promise.all(o),a.length>0){for(let l=0;l<a.length;l+=1)console.error(a[l]);throw a[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await br(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 Ps(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const a=dE(i);await Ps(this.storage,this.storageKey,a)}else{const i=dE(r);await Ps(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await br(this.storage,this.storageKey),await br(this.storage,this.storageKey+"-code-verifier"),await br(this.storage,this.storageKey+"-user"),this.userStorage&&await br(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&xr()&&(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(),js);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)/js);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${js}ms, refresh threshold is ${Yb} ticks`),i<=Yb&&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 FN)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!xr()||!(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,o]=await ws(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(l.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 Pe(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(be(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:o}=r;if(o)return this._returnResult({data:null,error:o});const l=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:u,error:d}=await Pe(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return d?this._returnResult({data:null,error:d}):(e.factorType==="totp"&&u.type==="totp"&&(!((i=u==null?void 0:u.totp)===null||i===void 0)&&i.qr_code)&&(u.totp.qr_code=`data:image/svg+xml;utf-8,${u.totp.qr_code}`),this._returnResult({data:u,error:null}))})}catch(r){if(be(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 o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?bE(e.webauthn.credential_response):xE(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await Pe(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(r){if(be(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 o=await Pe(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(o.error)return o;const{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:yE(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:vE(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(be(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}=uf(e);let x=null;v.aal&&(x=v.aal);let _=x;const{data:{user:b},error:k}=await this.getUser(e);if(k)return this._returnResult({data:null,error:k});((n=(r=b==null?void 0:b.factors)===null||r===void 0?void 0:r.filter(C=>C.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(_="aal2");const O=v.amr||[];return{data:{currentLevel:x,nextLevel:_,currentAuthenticationMethods:O},error:null}}catch(v){if(be(v))return this._returnResult({data:null,error:v});throw v}const{data:{session:o},error:l}=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:u}=uf(o.access_token);let d=null;u.aal&&(d=u.aal);let p=d;((a=(i=o.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=u.amr||[];return{data:{currentLevel:d,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 Pe(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 pr})})}catch(r){if(be(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 pr});const o=await Pe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(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 pr});const o=await Pe(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(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 Pe(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 pr})})}catch(e){if(be(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 Pe(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 pr})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(l=>l.kid===e);if(n)return n;const i=Date.now();if(n=this.jwks.keys.find(l=>l.kid===e),n&&this.jwks_cached_at+w6>i)return n;const{data:a,error:o}=await Pe(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=i,n=a.keys.find(l=>l.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:v,error:x}=await this.getSession();if(x||!v.session)return this._returnResult({data:null,error:x});n=v.session.access_token}const{header:i,payload:a,signature:o,raw:{header:l,payload:u}}=uf(n);r!=null&&r.allowExpired||F6(a.exp);const d=!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(!d){const{error:v}=await this.getUser(n);if(v)throw v;return{data:{claims:a,header:i,signature:o},error:null}}const p=H6(i.alg),f=await crypto.subtle.importKey("jwk",d,p,!0,["verify"]);if(!await crypto.subtle.verify(p,f,o,j6(`${l}.${u}`)))throw new Qb("Invalid JWT signature");return{data:{claims:a,header:i,signature:o},error:null}}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,i;qn(this.experimental);try{if(!Bf())return this._returnResult({data:null,error:new Xn("Browser does not support WebAuthn",null)});const{data:a,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!a)return this._returnResult({data:null,error:o});const l=vE(a.options),u=(i=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.signal)!==null&&i!==void 0?i:ex.createNewAbortSignal(),{data:d,error:p}=await KN({publicKey:l,signal:u});if(p||!d)return this._returnResult({data:null,error:p??new Xn("WebAuthn ceremony failed",null)});const f=xE(d);return this._verifyPasskeyAuthentication({challengeId:a.challenge_id,credential:f})}catch(a){if(be(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(e){var r,n;qn(this.experimental);try{if(!Bf())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 o=yE(i.options),l=(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:ex.createNewAbortSignal(),{data:u,error:d}=await GN({publicKey:o,signal:l});if(d||!u)return this._returnResult({data:null,error:d??new Xn("WebAuthn ceremony failed",null)});const p=bE(u);return this._verifyPasskeyRegistration({challengeId:i.challenge_id,credential:p})}catch(i){if(be(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyRegistration(){qn(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 pr});const{data:i,error:a}=await Pe(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(be(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){qn(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 pr});const{data:a,error:o}=await Pe(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;qn(this.experimental);try{const{data:n,error:i}=await Pe(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(be(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){qn(this.experimental);try{const{data:r,error:n}=await Pe(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:On});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(be(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){qn(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 pr});const{data:i,error:a}=await Pe(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){qn(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 pr});const{data:a,error:o}=await Pe(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){qn(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 pr});const{error:a}=await Pe(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(be(r))return this._returnResult({data:null,error:r});throw r}}}qc.nextInstanceID={};const pU=qc,mU="2.106.2";let Ec="";typeof Deno<"u"?Ec="deno":typeof document<"u"?Ec="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ec="react-native":Ec="node";const gU={"X-Client-Info":`supabase-js-${Ec}/${mU}`},yU={headers:gU},vU={schema:"public"},bU={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},xU={},wU={enabled:!1,respectSamplingDecision:!0};function _U(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function l(p){try{d(n.next(p))}catch(f){o(f)}}function u(p){try{d(n.throw(p))}catch(f){o(f)}}function d(p){p.done?a(p.value):i(p.value).then(l,u)}d((n=n.apply(t,[])).next())})}let Og=null;const SU="@opentelemetry/api";function kU(){return Og===null&&(Og=import(SU).catch(()=>null)),Og}function EU(){return _U(this,void 0,void 0,function*(){try{const t=yield kU();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 OU(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 o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(n)||!o.test(i)||!o.test(a)||n==="00000000000000000000000000000000"||i==="0000000000000000"?null:{version:r,traceId:n,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)===1}}function AU(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(TU(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 TU(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 CU(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 Fc(t){"@babel/helpers - typeof";return Fc=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},Fc(t)}function jU(t,e){if(Fc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Fc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function PU(t){var e=jU(t,"string");return Fc(e)=="symbol"?e:e+""}function NU(t,e,r){return(e=PU(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _E(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 Ft(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?_E(Object(r),!0).forEach(function(n){NU(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):_E(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}const RU=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),IU=()=>Headers,$U=(t,e,r,n,i)=>{const a=RU(n),o=IU(),l=(i==null?void 0:i.enabled)===!0,u=(i==null?void 0:i.respectSamplingDecision)!==!1,d=l?CU(e):null;return async(p,f)=>{var g;const v=(g=await r())!==null&&g!==void 0?g:t;let x=new o(f==null?void 0:f.headers);if(x.has("apikey")||x.set("apikey",t),x.has("Authorization")||x.set("Authorization",`Bearer ${v}`),d){const _=await MU(p,d,u);_&&(_.traceparent&&!x.has("traceparent")&&x.set("traceparent",_.traceparent),_.tracestate&&!x.has("tracestate")&&x.set("tracestate",_.tracestate),_.baggage&&!x.has("baggage")&&x.set("baggage",_.baggage))}return a(p,Ft(Ft({},f),{},{headers:x}))}};async function MU(t,e,r){if(!AU(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=await EU();if(!n||!n.traceparent)return null;if(r){const i=OU(n.traceparent);if(i&&!i.isSampled)return null}return n}function SE(t){return typeof t=="boolean"?{enabled:t}:t}function LU(t){return t.endsWith("/")?t:t+"/"}function DU(t,e){var r,n,i,a,o,l;const{db:u,auth:d,realtime:p,global:f}=t,{db:g,auth:v,realtime:x,global:_}=e,b=SE(t.tracePropagation),k=SE(e.tracePropagation),A={db:Ft(Ft({},g),u),auth:Ft(Ft({},v),d),realtime:Ft(Ft({},x),p),storage:{},global:Ft(Ft(Ft({},_),f),{},{headers:Ft(Ft({},(r=_==null?void 0:_.headers)!==null&&r!==void 0?r:{}),(n=f==null?void 0:f.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(i=(a=b==null?void 0:b.enabled)!==null&&a!==void 0?a:k==null?void 0:k.enabled)!==null&&i!==void 0?i:!1,respectSamplingDecision:(o=(l=b==null?void 0:b.respectSamplingDecision)!==null&&l!==void 0?l:k==null?void 0:k.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?A.accessToken=t.accessToken:delete A.accessToken,A}function zU(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(LU(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var BU=class extends pU{constructor(t){super(t)}},UU=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;const a=zU(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 o=`sb-${a.hostname.split(".")[0]}-auth-token`,l={db:vU,realtime:xU,auth:Ft(Ft({},bU),{},{storageKey:o}),global:yU,tracePropagation:wU},u=DU(r??{},l);if(this.settings=u,this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken)this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(p,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}});else{var d;this.auth=this._initSupabaseAuthClient((d=u.auth)!==null&&d!==void 0?d:{},this.headers,u.global.fetch)}this.fetch=$U(e,t,this._getAccessToken.bind(this),u.global.fetch,u.tracePropagation),this.realtime=this._initRealtimeClient(Ft({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},u.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 n8(new URL("rest/v1",a).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch,timeout:u.db.timeout,urlLengthLimit:u.db.urlLengthLimit}),this.storage=new g6(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new KB(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:o,lock:l,debug:u,throwOnError:d,experimental:p,lockAcquireTimeout:f,skipAutoInitialize:g},v,x){const _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new BU({url:this.authUrl.href,headers:Ft(Ft({},_),v),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:l,debug:u,throwOnError:d,experimental:p,fetch:x,lockAcquireTimeout:f,skipAutoInitialize:g,hasCustomAuthorizationHeader:Object.keys(this.headers).some(b=>b.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new z8(this.realtimeUrl.href,Ft(Ft({},t),{},{params:Ft(Ft({},{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 qU=(t,e,r)=>new UU(t,e,r);function FU(){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}FU()&&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 VN=R.createContext({session:null,supabase:null,loading:!0,signIn:async()=>({error:"Not initialized"}),signOut:async()=>{}});function tp(){return R.useContext(VN)}function HU({children:t}){const[e,r]=R.useState(null),[n,i]=R.useState(null),[a,o]=R.useState(!0),l=R.useRef(null);R.useEffect(()=>{X4(()=>{var p;return((p=l.current)==null?void 0:p.access_token)??null})},[]),R.useEffect(()=>{et.get("/config").then(({config:p})=>{if(p.supabase.projectUrl&&p.supabase.anonKey){const f=qU(p.supabase.projectUrl,p.supabase.anonKey);r(f),f.auth.getSession().then(({data:v})=>{l.current=v.session,i(v.session),o(!1)});const{data:{subscription:g}}=f.auth.onAuthStateChange((v,x)=>{l.current=x,i(x)});return()=>g.unsubscribe()}o(!1)}).catch(()=>{o(!1)})},[]);async function u(p,f){if(!e)return{error:"Supabase not configured"};const{error:g}=await e.auth.signInWithPassword({email:p,password:f});return{error:(g==null?void 0:g.message)??null}}async function d(){e&&(await e.auth.signOut(),l.current=null,i(null))}return y.jsx(VN.Provider,{value:{session:n,supabase:e,loading:a,signIn:u,signOut:d},children:t})}const WU=[{to:"/squads",icon:Vh,label:"Squads"},{to:"/skills",icon:Mb,label:"Skills"},{to:"/schedules",icon:R5,label:"Schedules"},{to:"/wiki",icon:BP,label:"Wiki"},{to:"/usage",icon:$5,label:"Usage"}],GU=[{to:"/",icon:WP,label:"Chat"},{to:"/feed",icon:Ib,label:"Inbox"},{to:"/settings",icon:M4,label:"Settings"}];function kE({to:t,icon:e,label:r,collapsed:n,badge:i}){return y.jsxs(LP,{to:t,end:t==="/",title:n?r:void 0,className:({isActive:a})=>Sc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono transition-colors cursor-pointer relative",n?"justify-center":"",a?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04]"),style:({isActive:a})=>a?{background:"rgba(228,58,156,0.1)"}:void 0,children:[y.jsx(e,{className:"w-3.5 h-3.5 flex-shrink-0"}),!n&&r,i!=null&&i>0&&y.jsx("span",{className:"absolute top-1 right-1 min-w-[14px] h-[14px] flex items-center justify-center rounded-full bg-[#E43A9C] text-[9px] text-white font-mono px-1",children:i>99?"99+":i})]})}function KU(){const[t,e]=R.useState(!1),[r,n]=R.useState("..."),[i,a]=R.useState(0),{supabase:o}=tp();return R.useEffect(()=>{let l=!0;et.get("/version").then(({version:d})=>{l&&n(d)}).catch(()=>{l&&n("unknown")}),et.get("/inbox/unread-count").then(({count:d})=>{l&&a(d)}).catch(()=>{});const u=setInterval(()=>{et.get("/inbox/unread-count").then(({count:d})=>{l&&a(d)}).catch(()=>{})},3e4);return()=>{l=!1,clearInterval(u)}},[]),y.jsxs("div",{className:"flex h-screen overflow-hidden bg-background relative",children:[y.jsxs("div",{className:Sc("flex-shrink-0 flex flex-col border-r border-white/[0.06] bg-[#181818] transition-all duration-200",t?"w-[52px]":"w-[210px]"),children:[y.jsx("div",{className:Sc("h-[52px] flex items-center border-b border-white/[0.06] flex-shrink-0",t?"justify-center px-3":"justify-between pl-4 pr-3"),children:t?y.jsx(Ra,{height:26}):y.jsxs("div",{className:"flex items-center gap-2.5",children:[y.jsx(Ra,{height:26}),y.jsx("span",{className:"text-2xl text-white tracking-wider leading-none",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"IO"})]})}),y.jsx("nav",{className:"flex-1 py-2 px-1.5 space-y-0.5 overflow-y-auto",children:WU.map(l=>y.jsx(kE,{collapsed:t,...l},l.to))}),y.jsxs("div",{className:"flex-shrink-0 border-t border-white/[0.06]",children:[y.jsx("div",{className:"py-1.5 px-1.5 space-y-0.5",children:GU.map(l=>y.jsx(kE,{collapsed:t,badge:l.to==="/feed"?i:void 0,...l},l.to))}),y.jsxs("div",{className:"border-t border-white/[0.05] py-1.5 px-1.5 space-y-0.5",children:[y.jsxs("a",{href:`https://github.com/michaeljolley/io/releases/tag/v${r}`,target:"_blank",rel:"noreferrer",title:"GitHub",className:Sc("flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:[y.jsx(l4,{className:"w-3.5 h-3.5 flex-shrink-0"}),!t&&y.jsxs("span",{className:"text-zinc-700",children:["v",r]})]}),y.jsx("button",{type:"button",onClick:()=>e(!t),title:t?"Expand sidebar":"Collapse sidebar",className:Sc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:t?y.jsx(jw,{className:"w-3.5 h-3.5 flex-shrink-0"}):y.jsx(Cu,{className:"w-3.5 h-3.5 flex-shrink-0"})})]})]})]}),y.jsxs("div",{className:"flex flex-col flex-1 min-w-0 overflow-hidden",children:[y.jsxs("div",{className:"h-[52px] flex-shrink-0 flex items-center justify-between px-4 border-b border-white/[0.06] bg-[#181818]",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(UB,{status:"connected"}),y.jsx("span",{className:"text-[11px] font-mono text-green-400",children:"connected"})]}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[y.jsx(rz,{}),o&&y.jsx("button",{type:"button",onClick:()=>o.auth.signOut(),className:"p-2 rounded-xl hover:bg-white/[0.05] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",title:"Sign out",children:y.jsx(y4,{className:"w-3.5 h-3.5"})})]})]}),y.jsxs("main",{className:"flex-1 overflow-hidden flex flex-col min-h-0 relative",children:[y.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",style:{zIndex:0},children:[y.jsx("div",{className:"orb orb-pink"}),y.jsx("div",{className:"orb orb-gray"})]}),y.jsx(uD,{})]})]})]})}function VU(){const{session:t}=tp(),e=ml(),{messages:r,streaming:n,isStreaming:i,isThinking:a,sendChatMessage:o,addUserMessage:l,uploadAttachment:u}=eN(),[d,p]=R.useState(""),[f,g]=R.useState(null),[v,x]=R.useState(null),_=R.useRef(null),b=R.useRef(null),k=R.useRef(null);R.useLayoutEffect(()=>{const E=_.current;E&&(E.scrollTop=E.scrollHeight)},[r,n,a]);async function A(){const E=d.trim();if(!E&&!f||i||a)return;const T=crypto.randomUUID(),P=f==null?void 0:f.name,N=[E,P?`Attachment: ${P}`:""].filter(Boolean).join(`
430
430
 
431
431
  `);l({id:T,role:"user",content:E,timestamp:new Date().toISOString(),attachmentName:P}),p(""),g(null),k.current&&(k.current.value=""),b.current&&(b.current.style.height="auto");try{f&&await u(f,T),o(N)}catch{}}function O(E){E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),A())}function C(E){p(E.target.value),b.current&&(b.current.style.height="auto",b.current.style.height=`${Math.min(b.current.scrollHeight,160)}px`)}return y.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[y.jsxs("div",{ref:_,className:"flex-1 overflow-y-auto px-5 py-5 space-y-5",children:[r.map(E=>{var T,P;return y.jsxs("div",{className:`flex gap-3 ${E.role==="user"?"flex-row-reverse":""}`,children:[y.jsx("div",{className:`flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center text-[10px] font-mono mt-0.5 ${E.role==="user"?"border border-[#E43A9C]/30 text-[#E43A9C]":"bg-[#282828] border border-white/[0.07] text-zinc-500"}`,style:E.role==="user"?{background:"rgba(228,58,156,0.12)"}:void 0,children:E.role==="user"?((P=(T=t==null?void 0:t.user)==null?void 0:T.email)==null?void 0:P.charAt(0).toUpperCase())??"U":y.jsx(Ra,{height:12})}),y.jsxs("div",{className:`flex flex-col gap-1.5 max-w-[72%] ${E.role==="user"?"items-end":"items-start"}`,children:[E.toolCall&&y.jsxs("button",{type:"button",onClick:()=>x(v===E.id?null:E.id),className:"w-full text-left border border-white/[0.07] bg-[#1e1e1e] rounded-xl px-3 py-2 flex items-center gap-2 hover:border-[#E43A9C]/25 transition-colors",children:[y.jsx(Gh,{className:"w-3 h-3 text-[#E43A9C] flex-shrink-0"}),y.jsx("span",{className:"text-[11px] font-mono text-zinc-400 flex-1",children:E.toolCall.name}),y.jsx(Vt,{variant:E.toolCall.status==="done"?"success":E.toolCall.status==="error"?"error":"warning",children:E.toolCall.status}),y.jsx(L5,{className:`w-3 h-3 text-zinc-600 transition-transform flex-shrink-0 ${v===E.id?"rotate-180":""}`})]}),E.toolCall&&v===E.id&&y.jsx("div",{className:"w-full bg-[#181818] border border-white/[0.06] rounded-xl px-3 py-2",children:y.jsx("p",{className:"text-[11px] font-mono text-zinc-500",children:E.toolCall.result})}),E.attachmentName&&y.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-[#1e1e1e] px-3 py-2 text-[11px] font-mono text-zinc-400",children:E.attachmentName}),E.content&&y.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${E.role==="user"?"text-white rounded-tr-sm":"bg-[#222222] border border-white/[0.07] text-zinc-200 rounded-tl-sm"}`,style:E.role==="user"?{background:"linear-gradient(135deg, #D83333 0%, #C0285E 100%)"}:void 0,children:E.role==="user"?y.jsx("p",{className:"whitespace-pre-wrap",children:E.content}):y.jsx("div",{className:"prose-io",dangerouslySetInnerHTML:{__html:nt.parse(E.content)}})}),y.jsx("span",{className:"text-[11px] text-zinc-700 font-mono px-0.5",children:Nw(E.timestamp,e)})]})]},E.id)}),a&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-3 flex items-center gap-1.5",children:[0,120,240].map(E=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${E}ms`}},E))})]}),i&&n&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-2.5 max-w-[72%]",children:y.jsx("div",{className:"prose-io text-sm",dangerouslySetInnerHTML:{__html:nt.parse(n)}})})]}),i&&!n&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-3 flex items-center gap-1.5",children:[0,120,240].map(E=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${E}ms`}},E))})]})]}),y.jsxs("div",{className:"border-t border-white/[0.06] p-4 flex-shrink-0",children:[y.jsxs("div",{className:"bg-[#1e1e1e] border border-white/[0.08] rounded-2xl overflow-hidden transition-colors focus-within:border-[#E43A9C]/30",children:[y.jsx("input",{ref:k,type:"file",className:"hidden",onChange:E=>{var T;return g(((T=E.target.files)==null?void 0:T[0])??null)}}),f&&y.jsxs("div",{className:"px-4 pt-3 text-[11px] font-mono text-zinc-400",children:["Attached: ",f.name]}),y.jsx("textarea",{ref:b,value:d,onChange:C,onKeyDown:O,placeholder:"Message IO…",rows:1,className:"w-full bg-transparent px-4 pt-3 pb-1 text-sm text-zinc-200 placeholder:text-zinc-700 resize-none focus:outline-none",style:{minHeight:"42px",maxHeight:"160px",fontFamily:"Inter, sans-serif"}}),y.jsxs("div",{className:"flex items-center justify-between px-3 pb-2.5",children:[y.jsx("button",{type:"button",onClick:()=>{var E;return(E=k.current)==null?void 0:E.click()},className:"p-1.5 rounded-lg hover:bg-white/[0.05] text-zinc-700 hover:text-zinc-400 transition-colors",children:y.jsx(GP,{className:"w-4 h-4"})}),y.jsx("div",{className:"flex items-center gap-2",children:i?y.jsxs("button",{type:"button",onClick:()=>{},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-[11px] font-mono text-zinc-300 transition-colors",children:[y.jsx(Kh,{className:"w-3 h-3"})," Stop"]}):y.jsx("button",{type:"button",onClick:A,disabled:!d.trim()&&!f||a,className:"p-2 rounded-xl text-white disabled:opacity-30 disabled:cursor-not-allowed transition-opacity hover:opacity-90",style:{background:"linear-gradient(135deg, #D83333, #E43A9C)"},children:y.jsx(XP,{className:"w-3.5 h-3.5"})})})]})]}),y.jsx("p",{className:"text-center text-[11px] text-zinc-800 font-mono mt-2",children:"IO may make mistakes. Verify important outputs."})]})]})}var Ag,EE;function XU(){if(EE)return Ag;EE=1;function t(M){return M instanceof Map?M.clear=M.delete=M.set=function(){throw new Error("map is read-only")}:M instanceof Set&&(M.add=M.clear=M.delete=function(){throw new Error("set is read-only")}),Object.freeze(M),Object.getOwnPropertyNames(M).forEach(ne=>{const de=M[ne],Re=typeof de;(Re==="object"||Re==="function")&&!Object.isFrozen(de)&&t(de)}),M}class e{constructor(ne){ne.data===void 0&&(ne.data={}),this.data=ne.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function r(M){return M.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function n(M,...ne){const de=Object.create(null);for(const Re in M)de[Re]=M[Re];return ne.forEach(function(Re){for(const ht in Re)de[ht]=Re[ht]}),de}const i="</span>",a=M=>!!M.scope,o=(M,{prefix:ne})=>{if(M.startsWith("language:"))return M.replace("language:","language-");if(M.includes(".")){const de=M.split(".");return[`${ne}${de.shift()}`,...de.map((Re,ht)=>`${Re}${"_".repeat(ht+1)}`)].join(" ")}return`${ne}${M}`};class l{constructor(ne,de){this.buffer="",this.classPrefix=de.classPrefix,ne.walk(this)}addText(ne){this.buffer+=r(ne)}openNode(ne){if(!a(ne))return;const de=o(ne.scope,{prefix:this.classPrefix});this.span(de)}closeNode(ne){a(ne)&&(this.buffer+=i)}value(){return this.buffer}span(ne){this.buffer+=`<span class="${ne}">`}}const u=(M={})=>{const ne={children:[]};return Object.assign(ne,M),ne};class d{constructor(){this.rootNode=u(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(ne){this.top.children.push(ne)}openNode(ne){const de=u({scope:ne});this.add(de),this.stack.push(de)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(ne){return this.constructor._walk(ne,this.rootNode)}static _walk(ne,de){return typeof de=="string"?ne.addText(de):de.children&&(ne.openNode(de),de.children.forEach(Re=>this._walk(ne,Re)),ne.closeNode(de)),ne}static _collapse(ne){typeof ne!="string"&&ne.children&&(ne.children.every(de=>typeof de=="string")?ne.children=[ne.children.join("")]:ne.children.forEach(de=>{d._collapse(de)}))}}class p extends d{constructor(ne){super(),this.options=ne}addText(ne){ne!==""&&this.add(ne)}startScope(ne){this.openNode(ne)}endScope(){this.closeNode()}__addSublanguage(ne,de){const Re=ne.root;de&&(Re.scope=`language:${de}`),this.add(Re)}toHTML(){return new l(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function f(M){return M?typeof M=="string"?M:M.source:null}function g(M){return _("(?=",M,")")}function v(M){return _("(?:",M,")*")}function x(M){return _("(?:",M,")?")}function _(...M){return M.map(de=>f(de)).join("")}function b(M){const ne=M[M.length-1];return typeof ne=="object"&&ne.constructor===Object?(M.splice(M.length-1,1),ne):{}}function k(...M){return"("+(b(M).capture?"":"?:")+M.map(Re=>f(Re)).join("|")+")"}function A(M){return new RegExp(M.toString()+"|").exec("").length-1}function O(M,ne){const de=M&&M.exec(ne);return de&&de.index===0}const C=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function E(M,{joinWith:ne}){let de=0;return M.map(Re=>{de+=1;const ht=de;let Ke=f(Re),ye="";for(;Ke.length>0;){const we=C.exec(Ke);if(!we){ye+=Ke;break}ye+=Ke.substring(0,we.index),Ke=Ke.substring(we.index+we[0].length),we[0][0]==="\\"&&we[1]?ye+="\\"+String(Number(we[1])+ht):(ye+=we[0],we[0]==="("&&de++)}return ye}).map(Re=>`(${Re})`).join(ne)}const T=/\b\B/,P="[a-zA-Z]\\w*",N="[a-zA-Z_]\\w*",I="\\b\\d+(\\.\\d+)?",Y="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",W="\\b(0b[01]+)",B="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",X=(M={})=>{const ne=/^#![ ]*\//;return M.binary&&(M.begin=_(ne,/.*\b/,M.binary,/\b.*/)),n({scope:"meta",begin:ne,end:/$/,relevance:0,"on:begin":(de,Re)=>{de.index!==0&&Re.ignoreMatch()}},M)},K={begin:"\\\\[\\s\\S]",relevance:0},U={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[K]},G={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[K]},J={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},F=function(M,ne,de={}){const Re=n({scope:"comment",begin:M,end:ne,contains:[]},de);Re.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const ht=k("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return Re.contains.push({begin:_(/[ ]+/,"(",ht,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),Re},te=F("//","$"),q=F("/\\*","\\*/"),z=F("#","$"),L={scope:"number",begin:I,relevance:0},Z={scope:"number",begin:Y,relevance:0},se={scope:"number",begin:W,relevance:0},le={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[K,{begin:/\[/,end:/\]/,relevance:0,contains:[K]}]},ve={scope:"title",begin:P,relevance:0},qe={scope:"title",begin:N,relevance:0},xe={begin:"\\.\\s*"+N,relevance:0};var Se=Object.freeze({__proto__:null,APOS_STRING_MODE:U,BACKSLASH_ESCAPE:K,BINARY_NUMBER_MODE:se,BINARY_NUMBER_RE:W,COMMENT:F,C_BLOCK_COMMENT_MODE:q,C_LINE_COMMENT_MODE:te,C_NUMBER_MODE:Z,C_NUMBER_RE:Y,END_SAME_AS_BEGIN:function(M){return Object.assign(M,{"on:begin":(ne,de)=>{de.data._beginMatch=ne[1]},"on:end":(ne,de)=>{de.data._beginMatch!==ne[1]&&de.ignoreMatch()}})},HASH_COMMENT_MODE:z,IDENT_RE:P,MATCH_NOTHING_RE:T,METHOD_GUARD:xe,NUMBER_MODE:L,NUMBER_RE:I,PHRASAL_WORDS_MODE:J,QUOTE_STRING_MODE:G,REGEXP_MODE:le,RE_STARTERS_RE:B,SHEBANG:X,TITLE_MODE:ve,UNDERSCORE_IDENT_RE:N,UNDERSCORE_TITLE_MODE:qe});function Me(M,ne){M.input[M.index-1]==="."&&ne.ignoreMatch()}function oe(M,ne){M.className!==void 0&&(M.scope=M.className,delete M.className)}function tt(M,ne){ne&&M.beginKeywords&&(M.begin="\\b("+M.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",M.__beforeBegin=Me,M.keywords=M.keywords||M.beginKeywords,delete M.beginKeywords,M.relevance===void 0&&(M.relevance=0))}function Fe(M,ne){Array.isArray(M.illegal)&&(M.illegal=k(...M.illegal))}function kt(M,ne){if(M.match){if(M.begin||M.end)throw new Error("begin & end are not supported with match");M.begin=M.match,delete M.match}}function wt(M,ne){M.relevance===void 0&&(M.relevance=1)}const Et=(M,ne)=>{if(!M.beforeMatch)return;if(M.starts)throw new Error("beforeMatch cannot be used with starts");const de=Object.assign({},M);Object.keys(M).forEach(Re=>{delete M[Re]}),M.keywords=de.keywords,M.begin=_(de.beforeMatch,g(de.begin)),M.starts={relevance:0,contains:[Object.assign(de,{endsParent:!0})]},M.relevance=0,delete de.beforeMatch},Sr=["of","and","for","in","not","or","if","then","parent","list","value"],Bt="keyword";function Rr(M,ne,de=Bt){const Re=Object.create(null);return typeof M=="string"?ht(de,M.split(" ")):Array.isArray(M)?ht(de,M):Object.keys(M).forEach(function(Ke){Object.assign(Re,Rr(M[Ke],ne,Ke))}),Re;function ht(Ke,ye){ne&&(ye=ye.map(we=>we.toLowerCase())),ye.forEach(function(we){const Ce=we.split("|");Re[Ce[0]]=[Ke,lr(Ce[0],Ce[1])]})}}function lr(M,ne){return ne?Number(ne):_t(M)?0:1}function _t(M){return Sr.includes(M.toLowerCase())}const kr={},Ir=M=>{console.error(M)},ni=(M,...ne)=>{console.log(`WARN: ${M}`,...ne)},Ur=(M,ne)=>{kr[`${M}/${ne}`]||(console.log(`Deprecated as of ${M}. ${ne}`),kr[`${M}/${ne}`]=!0)},ii=new Error;function ai(M,ne,{key:de}){let Re=0;const ht=M[de],Ke={},ye={};for(let we=1;we<=ne.length;we++)ye[we+Re]=ht[we],Ke[we+Re]=!0,Re+=A(ne[we-1]);M[de]=ye,M[de]._emit=Ke,M[de]._multi=!0}function aa(M){if(Array.isArray(M.begin)){if(M.skip||M.excludeBegin||M.returnBegin)throw Ir("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),ii;if(typeof M.beginScope!="object"||M.beginScope===null)throw Ir("beginScope must be object"),ii;ai(M,M.begin,{key:"beginScope"}),M.begin=E(M.begin,{joinWith:""})}}function qr(M){if(Array.isArray(M.end)){if(M.skip||M.excludeEnd||M.returnEnd)throw Ir("skip, excludeEnd, returnEnd not compatible with endScope: {}"),ii;if(typeof M.endScope!="object"||M.endScope===null)throw Ir("endScope must be object"),ii;ai(M,M.end,{key:"endScope"}),M.end=E(M.end,{joinWith:""})}}function oi(M){M.scope&&typeof M.scope=="object"&&M.scope!==null&&(M.beginScope=M.scope,delete M.scope)}function si(M){oi(M),typeof M.beginScope=="string"&&(M.beginScope={_wrap:M.beginScope}),typeof M.endScope=="string"&&(M.endScope={_wrap:M.endScope}),aa(M),qr(M)}function Ho(M){function ne(ye,we){return new RegExp(f(ye),"m"+(M.case_insensitive?"i":"")+(M.unicodeRegex?"u":"")+(we?"g":""))}class de{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(we,Ce){Ce.position=this.position++,this.matchIndexes[this.matchAt]=Ce,this.regexes.push([Ce,we]),this.matchAt+=A(we)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const we=this.regexes.map(Ce=>Ce[1]);this.matcherRe=ne(E(we,{joinWith:"|"}),!0),this.lastIndex=0}exec(we){this.matcherRe.lastIndex=this.lastIndex;const Ce=this.matcherRe.exec(we);if(!Ce)return null;const ct=Ce.findIndex((cr,Oi)=>Oi>0&&cr!==void 0),gt=this.matchIndexes[ct];return Ce.splice(0,ct),Object.assign(Ce,gt)}}class Re{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(we){if(this.multiRegexes[we])return this.multiRegexes[we];const Ce=new de;return this.rules.slice(we).forEach(([ct,gt])=>Ce.addRule(ct,gt)),Ce.compile(),this.multiRegexes[we]=Ce,Ce}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(we,Ce){this.rules.push([we,Ce]),Ce.type==="begin"&&this.count++}exec(we){const Ce=this.getMatcher(this.regexIndex);Ce.lastIndex=this.lastIndex;let ct=Ce.exec(we);if(this.resumingScanAtSamePosition()&&!(ct&&ct.index===this.lastIndex)){const gt=this.getMatcher(0);gt.lastIndex=this.lastIndex+1,ct=gt.exec(we)}return ct&&(this.regexIndex+=ct.position+1,this.regexIndex===this.count&&this.considerAll()),ct}}function ht(ye){const we=new Re;return ye.contains.forEach(Ce=>we.addRule(Ce.begin,{rule:Ce,type:"begin"})),ye.terminatorEnd&&we.addRule(ye.terminatorEnd,{type:"end"}),ye.illegal&&we.addRule(ye.illegal,{type:"illegal"}),we}function Ke(ye,we){const Ce=ye;if(ye.isCompiled)return Ce;[oe,kt,si,Et].forEach(gt=>gt(ye,we)),M.compilerExtensions.forEach(gt=>gt(ye,we)),ye.__beforeBegin=null,[tt,Fe,wt].forEach(gt=>gt(ye,we)),ye.isCompiled=!0;let ct=null;return typeof ye.keywords=="object"&&ye.keywords.$pattern&&(ye.keywords=Object.assign({},ye.keywords),ct=ye.keywords.$pattern,delete ye.keywords.$pattern),ct=ct||/\w+/,ye.keywords&&(ye.keywords=Rr(ye.keywords,M.case_insensitive)),Ce.keywordPatternRe=ne(ct,!0),we&&(ye.begin||(ye.begin=/\B|\b/),Ce.beginRe=ne(Ce.begin),!ye.end&&!ye.endsWithParent&&(ye.end=/\B|\b/),ye.end&&(Ce.endRe=ne(Ce.end)),Ce.terminatorEnd=f(Ce.end)||"",ye.endsWithParent&&we.terminatorEnd&&(Ce.terminatorEnd+=(ye.end?"|":"")+we.terminatorEnd)),ye.illegal&&(Ce.illegalRe=ne(ye.illegal)),ye.contains||(ye.contains=[]),ye.contains=[].concat(...ye.contains.map(function(gt){return Wo(gt==="self"?ye:gt)})),ye.contains.forEach(function(gt){Ke(gt,Ce)}),ye.starts&&Ke(ye.starts,we),Ce.matcher=ht(Ce),Ce}if(M.compilerExtensions||(M.compilerExtensions=[]),M.contains&&M.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return M.classNameAliases=n(M.classNameAliases||{}),Ke(M)}function Ka(M){return M?M.endsWithParent||Ka(M.starts):!1}function Wo(M){return M.variants&&!M.cachedVariants&&(M.cachedVariants=M.variants.map(function(ne){return n(M,{variants:null},ne)})),M.cachedVariants?M.cachedVariants:Ka(M)?n(M,{starts:M.starts?n(M.starts):null}):Object.isFrozen(M)?n(M):M}var oa="11.11.1";class Va extends Error{constructor(ne,de){super(ne),this.name="HTMLInjectionError",this.html=de}}const Rn=r,$r=n,sa=Symbol("nomatch"),li=7,hn=function(M){const ne=Object.create(null),de=Object.create(null),Re=[];let ht=!0;const Ke="Could not find the language '{}', did you forget to load/include a language module?",ye={disableAutodetect:!0,name:"Plain text",contains:[]};let we={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:p};function Ce(he){return we.noHighlightRe.test(he)}function ct(he){let $e=he.className+" ";$e+=he.parentNode?he.parentNode.className:"";const Ve=we.languageDetectRe.exec($e);if(Ve){const Ze=In(Ve[1]);return Ze||(ni(Ke.replace("{}",Ve[1])),ni("Falling back to no-highlight mode for this block.",he)),Ze?Ve[1]:"no-highlight"}return $e.split(/\s+/).find(Ze=>Ce(Ze)||In(Ze))}function gt(he,$e,Ve){let Ze="",Wt="";typeof $e=="object"?(Ze=he,Ve=$e.ignoreIllegals,Wt=$e.language):(Ur("10.7.0","highlight(lang, code, ...args) has been deprecated."),Ur("10.7.0",`Please use highlight(code, options) instead.
432
432
  https://github.com/highlightjs/highlight.js/issues/2277`),Wt=he,Ze=$e),Ve===void 0&&(Ve=!0);const Lt={code:Ze,language:Wt};Ya("before:highlight",Lt);const ci=Lt.result?Lt.result:cr(Lt.language,Lt.code,Ve);return ci.code=Lt.code,Ya("after:highlight",ci),ci}function cr(he,$e,Ve,Ze){const Wt=Object.create(null);function Lt(me,Ee){return me.keywords[Ee]}function ci(){if(!Ge.keywords){Gt.addText(yt);return}let me=0;Ge.keywordPatternRe.lastIndex=0;let Ee=Ge.keywordPatternRe.exec(yt),He="";for(;Ee;){He+=yt.substring(me,Ee.index);const rt=mn.case_insensitive?Ee[0].toLowerCase():Ee[0],Ut=Lt(Ge,rt);if(Ut){const[ur,Dp]=Ut;if(Gt.addText(He),He="",Wt[rt]=(Wt[rt]||0)+1,Wt[rt]<=li&&(Qa+=Dp),ur.startsWith("_"))He+=Ee[0];else{const Xu=mn.classNameAliases[ur]||ur;Lr(Ee[0],Xu)}}else He+=Ee[0];me=Ge.keywordPatternRe.lastIndex,Ee=Ge.keywordPatternRe.exec(yt)}He+=yt.substring(me),Gt.addText(He)}function Vo(){if(yt==="")return;let me=null;if(typeof Ge.subLanguage=="string"){if(!ne[Ge.subLanguage]){Gt.addText(yt);return}me=cr(Ge.subLanguage,yt,!0,Pl[Ge.subLanguage]),Pl[Ge.subLanguage]=me._top}else me=Xa(yt,Ge.subLanguage.length?Ge.subLanguage:null);Ge.relevance>0&&(Qa+=me.relevance),Gt.__addSublanguage(me._emitter,me.language)}function Mr(){Ge.subLanguage!=null?Vo():ci(),yt=""}function Lr(me,Ee){me!==""&&(Gt.startScope(Ee),Gt.addText(me),Gt.endScope())}function Ja(me,Ee){let He=1;const rt=Ee.length-1;for(;He<=rt;){if(!me._emit[He]){He++;continue}const Ut=mn.classNameAliases[me[He]]||me[He],ur=Ee[He];Ut?Lr(ur,Ut):(yt=ur,ci(),yt=""),He++}}function la(me,Ee){return me.scope&&typeof me.scope=="string"&&Gt.openNode(mn.classNameAliases[me.scope]||me.scope),me.beginScope&&(me.beginScope._wrap?(Lr(yt,mn.classNameAliases[me.beginScope._wrap]||me.beginScope._wrap),yt=""):me.beginScope._multi&&(Ja(me.beginScope,Ee),yt="")),Ge=Object.create(me,{parent:{value:Ge}}),Ge}function Za(me,Ee,He){let rt=O(me.endRe,He);if(rt){if(me["on:end"]){const Ut=new e(me);me["on:end"](Ee,Ut),Ut.isMatchIgnored&&(rt=!1)}if(rt){for(;me.endsParent&&me.parent;)me=me.parent;return me}}if(me.endsWithParent)return Za(me.parent,Ee,He)}function Mp(me){return Ge.matcher.regexIndex===0?(yt+=me[0],1):(da=!0,0)}function Lp(me){const Ee=me[0],He=me.rule,rt=new e(He),Ut=[He.__beforeBegin,He["on:begin"]];for(const ur of Ut)if(ur&&(ur(me,rt),rt.isMatchIgnored))return Mp(Ee);return He.skip?yt+=Ee:(He.excludeBegin&&(yt+=Ee),Mr(),!He.returnBegin&&!He.excludeBegin&&(yt=Ee)),la(He,me),He.returnBegin?0:Ee.length}function Cl(me){const Ee=me[0],He=$e.substring(me.index),rt=Za(Ge,me,He);if(!rt)return sa;const Ut=Ge;Ge.endScope&&Ge.endScope._wrap?(Mr(),Lr(Ee,Ge.endScope._wrap)):Ge.endScope&&Ge.endScope._multi?(Mr(),Ja(Ge.endScope,me)):Ut.skip?yt+=Ee:(Ut.returnEnd||Ut.excludeEnd||(yt+=Ee),Mr(),Ut.excludeEnd&&(yt=Ee));do Ge.scope&&Gt.closeNode(),!Ge.skip&&!Ge.subLanguage&&(Qa+=Ge.relevance),Ge=Ge.parent;while(Ge!==rt.parent);return rt.starts&&la(rt.starts,me),Ut.returnEnd?0:Ee.length}function Vu(){const me=[];for(let Ee=Ge;Ee!==mn;Ee=Ee.parent)Ee.scope&&me.unshift(Ee.scope);me.forEach(Ee=>Gt.openNode(Ee))}let ca={};function ua(me,Ee){const He=Ee&&Ee[0];if(yt+=me,He==null)return Mr(),0;if(ca.type==="begin"&&Ee.type==="end"&&ca.index===Ee.index&&He===""){if(yt+=$e.slice(Ee.index,Ee.index+1),!ht){const rt=new Error(`0 width match regex (${he})`);throw rt.languageName=he,rt.badRule=ca.rule,rt}return 1}if(ca=Ee,Ee.type==="begin")return Lp(Ee);if(Ee.type==="illegal"&&!Ve){const rt=new Error('Illegal lexeme "'+He+'" for mode "'+(Ge.scope||"<unnamed>")+'"');throw rt.mode=Ge,rt}else if(Ee.type==="end"){const rt=Cl(Ee);if(rt!==sa)return rt}if(Ee.type==="illegal"&&He==="")return yt+=`
@@ -502,4 +502,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
502
502
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function mM(t,e){if(t){if(typeof t=="string")return yw(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 yw(t,e)}}function gne(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function yne(t){if(Array.isArray(t))return yw(t)}function yw(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 pP(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 ie(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?pP(Object(r),!0).forEach(function(n){ze(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):pP(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function ze(t,e,r){return e=gM(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function gM(t){var e=vne(t,"string");return ul(e)=="symbol"?e:e+""}function vne(t,e){if(ul(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(ul(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var bne={xAxis:["bottom","top"],yAxis:["left","right"]},xne={width:"100%",height:"100%"},yM={x:0,y:0};function Sf(t){return t}var wne=function(e,r){return r==="horizontal"?e.x:r==="vertical"?e.y:r==="centric"?e.angle:e.radius},_ne=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 o=a.coordinate,l=i.radius;return ie(ie(ie({},i),_r(i.cx,i.cy,l,o)),{},{angle:o,radius:l})}var u=a.coordinate,d=i.angle;return ie(ie(ie({},i),_r(i.cx,i.cy,u,d)),{},{angle:d,radius:u})}return yM},Np=function(e,r){var n=r.graphicalItems,i=r.dataStartIndex,a=r.dataEndIndex,o=(n??[]).reduce(function(l,u){var d=u.props.data;return d&&d.length?[].concat(dl(l),dl(d)):l},[]);return o.length>0?o:e&&e.length&&ge(i)&&ge(a)?e.slice(i,a+1):[]};function vM(t){return t==="number"?[0,"auto"]:void 0}var vw=function(e,r,n,i){var a=e.graphicalItems,o=e.tooltipAxis,l=Np(r,e);return n<0||!a||!a.length||n>=l.length?null:a.reduce(function(u,d){var p,f=(p=d.props.data)!==null&&p!==void 0?p:r;f&&e.dataStartIndex+e.dataEndIndex!==0&&e.dataEndIndex-e.dataStartIndex>=n&&(f=f.slice(e.dataStartIndex,e.dataEndIndex+1));var g;if(o.dataKey&&!o.allowDuplicatedCategory){var v=f===void 0?l:f;g=Ff(v,o.dataKey,i)}else g=f&&f[n]||l[n];return g?[].concat(dl(u),[v$(d,g)]):u},[])},mP=function(e,r,n,i){var a=i||{x:e.chartX,y:e.chartY},o=wne(a,n),l=e.orderedTooltipTicks,u=e.tooltipAxis,d=e.tooltipTicks,p=NX(o,l,d,u);if(p>=0&&d){var f=d[p]&&d[p].value,g=vw(e,r,p,f),v=_ne(n,l,p,a);return{activeTooltipIndex:p,activeLabel:f,activePayload:g,activeCoordinate:v}}return null},Sne=function(e,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,o=r.axisIdKey,l=r.stackGroups,u=r.dataStartIndex,d=r.dataEndIndex,p=e.layout,f=e.children,g=e.stackOffset,v=m$(p,a);return n.reduce(function(x,_){var b,k=_.type.defaultProps!==void 0?ie(ie({},_.type.defaultProps),_.props):_.props,A=k.type,O=k.dataKey,C=k.allowDataOverflow,E=k.allowDuplicatedCategory,T=k.scale,P=k.ticks,N=k.includeHidden,I=k[o];if(x[I])return x;var Y=Np(e.data,{graphicalItems:i.filter(function(L){var Z,se=o in L.props?L.props[o]:(Z=L.type.defaultProps)===null||Z===void 0?void 0:Z[o];return se===I}),dataStartIndex:u,dataEndIndex:d}),W=Y.length,B,X,K;Xre(k.domain,C,A)&&(B=$x(k.domain,null,C),v&&(A==="number"||T!=="auto")&&(K=Ic(Y,O,"category")));var U=vM(A);if(!B||B.length===0){var G,J=(G=k.domain)!==null&&G!==void 0?G:U;if(O){if(B=Ic(Y,O,A),A==="category"&&v){var F=S9(B);E&&F?(X=B,B=Th(0,W)):E||(B=CC(J,B,_).reduce(function(L,Z){return L.indexOf(Z)>=0?L:[].concat(dl(L),[Z])},[]))}else if(A==="category")E?B=B.filter(function(L){return L!==""&&!Qe(L)}):B=CC(J,B,_).reduce(function(L,Z){return L.indexOf(Z)>=0||Z===""||Qe(Z)?L:[].concat(dl(L),[Z])},[]);else if(A==="number"){var te=LX(Y,i.filter(function(L){var Z,se,le=o in L.props?L.props[o]:(Z=L.type.defaultProps)===null||Z===void 0?void 0:Z[o],ve="hide"in L.props?L.props.hide:(se=L.type.defaultProps)===null||se===void 0?void 0:se.hide;return le===I&&(N||!ve)}),O,a,p);te&&(B=te)}v&&(A==="number"||T!=="auto")&&(K=Ic(Y,O,"category"))}else v?B=Th(0,W):l&&l[I]&&l[I].hasStack&&A==="number"?B=g==="expand"?[0,1]:y$(l[I].stackGroups,u,d):B=p$(Y,i.filter(function(L){var Z=o in L.props?L.props[o]:L.type.defaultProps[o],se="hide"in L.props?L.props.hide:L.type.defaultProps.hide;return Z===I&&(N||!se)}),A,p,!0);if(A==="number")B=mw(f,B,I,a,P),J&&(B=$x(J,B,C));else if(A==="category"&&J){var q=J,z=B.every(function(L){return q.indexOf(L)>=0});z&&(B=q)}}return ie(ie({},x),{},ze({},I,ie(ie({},k),{},{axisType:a,domain:B,categoricalDomain:K,duplicateDomain:X,originalDomain:(b=k.domain)!==null&&b!==void 0?b:U,isCategorical:v,layout:p})))},{})},kne=function(e,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,o=r.axisIdKey,l=r.stackGroups,u=r.dataStartIndex,d=r.dataEndIndex,p=e.layout,f=e.children,g=Np(e.data,{graphicalItems:n,dataStartIndex:u,dataEndIndex:d}),v=g.length,x=m$(p,a),_=-1;return n.reduce(function(b,k){var A=k.type.defaultProps!==void 0?ie(ie({},k.type.defaultProps),k.props):k.props,O=A[o],C=vM("number");if(!b[O]){_++;var E;return x?E=Th(0,v):l&&l[O]&&l[O].hasStack?(E=y$(l[O].stackGroups,u,d),E=mw(f,E,O,a)):(E=$x(C,p$(g,n.filter(function(T){var P,N,I=o in T.props?T.props[o]:(P=T.type.defaultProps)===null||P===void 0?void 0:P[o],Y="hide"in T.props?T.props.hide:(N=T.type.defaultProps)===null||N===void 0?void 0:N.hide;return I===O&&!Y}),"number",p),i.defaultProps.allowDataOverflow),E=mw(f,E,O,a)),ie(ie({},b),{},ze({},O,ie(ie({axisType:a},i.defaultProps),{},{hide:!0,orientation:Tn(bne,"".concat(a,".").concat(_%2),null),domain:E,originalDomain:C,isCategorical:x,layout:p})))}return b},{})},Ene=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,o=r.graphicalItems,l=r.stackGroups,u=r.dataStartIndex,d=r.dataEndIndex,p=e.children,f="".concat(i,"Id"),g=Cn(p,a),v={};return g&&g.length?v=Sne(e,{axes:g,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:u,dataEndIndex:d}):o&&o.length&&(v=kne(e,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:u,dataEndIndex:d})),v},One=function(e){var r=Na(e),n=Hi(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:p1(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:vh(r,n)}},gP=function(e){var r=e.children,n=e.defaultShowTooltip,i=sn(r,tl),a=0,o=0;return e.data&&e.data.length!==0&&(o=e.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(o=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!n}},Ane=function(e){return!e||!e.length?!1:e.some(function(r){var n=Gi(r&&r.type);return n&&n.indexOf("Bar")>=0})},yP=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"}},Tne=function(e,r){var n=e.props,i=e.graphicalItems,a=e.xAxisMap,o=a===void 0?{}:a,l=e.yAxisMap,u=l===void 0?{}:l,d=n.width,p=n.height,f=n.children,g=n.margin||{},v=sn(f,tl),x=sn(f,Bs),_=Object.keys(u).reduce(function(E,T){var P=u[T],N=P.orientation;return!P.mirror&&!P.hide?ie(ie({},E),{},ze({},N,E[N]+P.width)):E},{left:g.left||0,right:g.right||0}),b=Object.keys(o).reduce(function(E,T){var P=o[T],N=P.orientation;return!P.mirror&&!P.hide?ie(ie({},E),{},ze({},N,Tn(E,"".concat(N))+P.height)):E},{top:g.top||0,bottom:g.bottom||0}),k=ie(ie({},b),_),A=k.bottom;v&&(k.bottom+=v.props.height||tl.defaultProps.height),x&&r&&(k=$X(k,i,n,r));var O=d-k.left-k.right,C=p-k.top-k.bottom;return ie(ie({brushBottom:A},k),{},{width:Math.max(O,0),height:Math.max(C,0)})},Cne=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},bM=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,a=i===void 0?"axis":i,o=e.validateTooltipEventTypes,l=o===void 0?["axis"]:o,u=e.axisComponents,d=e.legendContent,p=e.formatAxisMap,f=e.defaultProps,g=function(k,A){var O=A.graphicalItems,C=A.stackGroups,E=A.offset,T=A.updateId,P=A.dataStartIndex,N=A.dataEndIndex,I=k.barSize,Y=k.layout,W=k.barGap,B=k.barCategoryGap,X=k.maxBarSize,K=yP(Y),U=K.numericAxisName,G=K.cateAxisName,J=Ane(O),F=[];return O.forEach(function(te,q){var z=Np(k.data,{graphicalItems:[te],dataStartIndex:P,dataEndIndex:N}),L=te.type.defaultProps!==void 0?ie(ie({},te.type.defaultProps),te.props):te.props,Z=L.dataKey,se=L.maxBarSize,le=L["".concat(U,"Id")],ve=L["".concat(G,"Id")],qe={},xe=u.reduce(function(lr,_t){var kr=A["".concat(_t.axisType,"Map")],Ir=L["".concat(_t.axisType,"Id")];kr&&kr[Ir]||_t.axisType==="zAxis"||$o();var ni=kr[Ir];return ie(ie({},lr),{},ze(ze({},_t.axisType,ni),"".concat(_t.axisType,"Ticks"),Hi(ni)))},qe),ae=xe[G],Se=xe["".concat(G,"Ticks")],Me=C&&C[le]&&C[le].hasStack&&XX(te,C[le].stackGroups),oe=Gi(te.type).indexOf("Bar")>=0,tt=vh(ae,Se),Fe=[],kt=J&&RX({barSize:I,stackGroups:C,totalSize:Cne(xe,G)});if(oe){var wt,Et,Sr=Qe(se)?X:se,Bt=(wt=(Et=vh(ae,Se,!0))!==null&&Et!==void 0?Et:Sr)!==null&&wt!==void 0?wt:0;Fe=IX({barGap:W,barCategoryGap:B,bandSize:Bt!==tt?Bt:tt,sizeList:kt[ve],maxBarSize:Sr}),Bt!==tt&&(Fe=Fe.map(function(lr){return ie(ie({},lr),{},{position:ie(ie({},lr.position),{},{offset:lr.position.offset-Bt/2})})}))}var Rr=te&&te.type&&te.type.getComposedData;Rr&&F.push({props:ie(ie({},Rr(ie(ie({},xe),{},{displayedData:z,props:k,dataKey:Z,item:te,bandSize:tt,barPosition:Fe,offset:E,stackedData:Me,layout:Y,dataStartIndex:P,dataEndIndex:N}))),{},ze(ze(ze({key:te.key||"item-".concat(q)},U,xe[U]),G,xe[G]),"animationId",T)),childIndex:M9(te,k.children),item:te})}),F},v=function(k,A){var O=k.props,C=k.dataStartIndex,E=k.dataEndIndex,T=k.updateId;if(!FO({props:O}))return null;var P=O.children,N=O.layout,I=O.stackOffset,Y=O.data,W=O.reverseStackOrder,B=yP(N),X=B.numericAxisName,K=B.cateAxisName,U=Cn(P,n),G=GX(Y,U,"".concat(X,"Id"),"".concat(K,"Id"),I,W),J=u.reduce(function(L,Z){var se="".concat(Z.axisType,"Map");return ie(ie({},L),{},ze({},se,Ene(O,ie(ie({},Z),{},{graphicalItems:U,stackGroups:Z.axisType===X&&G,dataStartIndex:C,dataEndIndex:E}))))},{}),F=Tne(ie(ie({},J),{},{props:O,graphicalItems:U}),A==null?void 0:A.legendBBox);Object.keys(J).forEach(function(L){J[L]=p(O,J[L],F,L.replace("Map",""),r)});var te=J["".concat(K,"Map")],q=One(te),z=g(O,ie(ie({},J),{},{dataStartIndex:C,dataEndIndex:E,updateId:T,graphicalItems:U,stackGroups:G,offset:F}));return ie(ie({formattedGraphicalItems:z,graphicalItems:U,offset:F,stackGroups:G},q),J)},x=(function(b){function k(A){var O,C,E;return lne(this,k),E=dne(this,k,[A]),ze(E,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),ze(E,"accessibilityManager",new Vre),ze(E,"handleLegendBBoxUpdate",function(T){if(T){var P=E.state,N=P.dataStartIndex,I=P.dataEndIndex,Y=P.updateId;E.setState(ie({legendBBox:T},v({props:E.props,dataStartIndex:N,dataEndIndex:I,updateId:Y},ie(ie({},E.state),{},{legendBBox:T}))))}}),ze(E,"handleReceiveSyncEvent",function(T,P,N){if(E.props.syncId===T){if(N===E.eventEmitterSymbol&&typeof E.props.syncMethod!="function")return;E.applySyncEvent(P)}}),ze(E,"handleBrushChange",function(T){var P=T.startIndex,N=T.endIndex;if(P!==E.state.dataStartIndex||N!==E.state.dataEndIndex){var I=E.state.updateId;E.setState(function(){return ie({dataStartIndex:P,dataEndIndex:N},v({props:E.props,dataStartIndex:P,dataEndIndex:N,updateId:I},E.state))}),E.triggerSyncEvent({dataStartIndex:P,dataEndIndex:N})}}),ze(E,"handleMouseEnter",function(T){var P=E.getMouseInfo(T);if(P){var N=ie(ie({},P),{},{isTooltipActive:!0});E.setState(N),E.triggerSyncEvent(N);var I=E.props.onMouseEnter;Ye(I)&&I(N,T)}}),ze(E,"triggeredAfterMouseMove",function(T){var P=E.getMouseInfo(T),N=P?ie(ie({},P),{},{isTooltipActive:!0}):{isTooltipActive:!1};E.setState(N),E.triggerSyncEvent(N);var I=E.props.onMouseMove;Ye(I)&&I(N,T)}),ze(E,"handleItemMouseEnter",function(T){E.setState(function(){return{isTooltipActive:!0,activeItem:T,activePayload:T.tooltipPayload,activeCoordinate:T.tooltipPosition||{x:T.cx,y:T.cy}}})}),ze(E,"handleItemMouseLeave",function(){E.setState(function(){return{isTooltipActive:!1}})}),ze(E,"handleMouseMove",function(T){T.persist(),E.throttleTriggeredAfterMouseMove(T)}),ze(E,"handleMouseLeave",function(T){E.throttleTriggeredAfterMouseMove.cancel();var P={isTooltipActive:!1};E.setState(P),E.triggerSyncEvent(P);var N=E.props.onMouseLeave;Ye(N)&&N(P,T)}),ze(E,"handleOuterEvent",function(T){var P=$9(T),N=Tn(E.props,"".concat(P));if(P&&Ye(N)){var I,Y;/.*touch.*/i.test(P)?Y=E.getMouseInfo(T.changedTouches[0]):Y=E.getMouseInfo(T),N((I=Y)!==null&&I!==void 0?I:{},T)}}),ze(E,"handleClick",function(T){var P=E.getMouseInfo(T);if(P){var N=ie(ie({},P),{},{isTooltipActive:!0});E.setState(N),E.triggerSyncEvent(N);var I=E.props.onClick;Ye(I)&&I(N,T)}}),ze(E,"handleMouseDown",function(T){var P=E.props.onMouseDown;if(Ye(P)){var N=E.getMouseInfo(T);P(N,T)}}),ze(E,"handleMouseUp",function(T){var P=E.props.onMouseUp;if(Ye(P)){var N=E.getMouseInfo(T);P(N,T)}}),ze(E,"handleTouchMove",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&E.throttleTriggeredAfterMouseMove(T.changedTouches[0])}),ze(E,"handleTouchStart",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&E.handleMouseDown(T.changedTouches[0])}),ze(E,"handleTouchEnd",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&E.handleMouseUp(T.changedTouches[0])}),ze(E,"handleDoubleClick",function(T){var P=E.props.onDoubleClick;if(Ye(P)){var N=E.getMouseInfo(T);P(N,T)}}),ze(E,"handleContextMenu",function(T){var P=E.props.onContextMenu;if(Ye(P)){var N=E.getMouseInfo(T);P(N,T)}}),ze(E,"triggerSyncEvent",function(T){E.props.syncId!==void 0&&Ab.emit(Tb,E.props.syncId,T,E.eventEmitterSymbol)}),ze(E,"applySyncEvent",function(T){var P=E.props,N=P.layout,I=P.syncMethod,Y=E.state.updateId,W=T.dataStartIndex,B=T.dataEndIndex;if(T.dataStartIndex!==void 0||T.dataEndIndex!==void 0)E.setState(ie({dataStartIndex:W,dataEndIndex:B},v({props:E.props,dataStartIndex:W,dataEndIndex:B,updateId:Y},E.state)));else if(T.activeTooltipIndex!==void 0){var X=T.chartX,K=T.chartY,U=T.activeTooltipIndex,G=E.state,J=G.offset,F=G.tooltipTicks;if(!J)return;if(typeof I=="function")U=I(F,T);else if(I==="value"){U=-1;for(var te=0;te<F.length;te++)if(F[te].value===T.activeLabel){U=te;break}}var q=ie(ie({},J),{},{x:J.left,y:J.top}),z=Math.min(X,q.x+q.width),L=Math.min(K,q.y+q.height),Z=F[U]&&F[U].value,se=vw(E.state,E.props.data,U),le=F[U]?{x:N==="horizontal"?F[U].coordinate:z,y:N==="horizontal"?L:F[U].coordinate}:yM;E.setState(ie(ie({},T),{},{activeLabel:Z,activeCoordinate:le,activePayload:se,activeTooltipIndex:U}))}else E.setState(T)}),ze(E,"renderCursor",function(T){var P,N=E.state,I=N.isTooltipActive,Y=N.activeCoordinate,W=N.activePayload,B=N.offset,X=N.activeTooltipIndex,K=N.tooltipAxisBandSize,U=E.getTooltipEventType(),G=(P=T.props.active)!==null&&P!==void 0?P:I,J=E.props.layout,F=T.key||"_recharts-cursor";return $.createElement(tne,{key:F,activeCoordinate:Y,activePayload:W,activeTooltipIndex:X,chartName:r,element:T,isActive:G,layout:J,offset:B,tooltipAxisBandSize:K,tooltipEventType:U})}),ze(E,"renderPolarAxis",function(T,P,N){var I=Tn(T,"type.axisType"),Y=Tn(E.state,"".concat(I,"Map")),W=T.type.defaultProps,B=W!==void 0?ie(ie({},W),T.props):T.props,X=Y&&Y[B["".concat(I,"Id")]];return R.cloneElement(T,ie(ie({},X),{},{className:at(I,X.className),key:T.key||"".concat(P,"-").concat(N),ticks:Hi(X,!0)}))}),ze(E,"renderPolarGrid",function(T){var P=T.props,N=P.radialLines,I=P.polarAngles,Y=P.polarRadius,W=E.state,B=W.radiusAxisMap,X=W.angleAxisMap,K=Na(B),U=Na(X),G=U.cx,J=U.cy,F=U.innerRadius,te=U.outerRadius;return R.cloneElement(T,{polarAngles:Array.isArray(I)?I:Hi(U,!0).map(function(q){return q.coordinate}),polarRadius:Array.isArray(Y)?Y:Hi(K,!0).map(function(q){return q.coordinate}),cx:G,cy:J,innerRadius:F,outerRadius:te,key:T.key||"polar-grid",radialLines:N})}),ze(E,"renderLegend",function(){var T=E.state.formattedGraphicalItems,P=E.props,N=P.children,I=P.width,Y=P.height,W=E.props.margin||{},B=I-(W.left||0)-(W.right||0),X=f$({children:N,formattedGraphicalItems:T,legendWidth:B,legendContent:d});if(!X)return null;var K=X.item,U=hP(X,rne);return R.cloneElement(K,ie(ie({},U),{},{chartWidth:I,chartHeight:Y,margin:W,onBBoxUpdate:E.handleLegendBBoxUpdate}))}),ze(E,"renderTooltip",function(){var T,P=E.props,N=P.children,I=P.accessibilityLayer,Y=sn(N,ln);if(!Y)return null;var W=E.state,B=W.isTooltipActive,X=W.activeCoordinate,K=W.activePayload,U=W.activeLabel,G=W.offset,J=(T=Y.props.active)!==null&&T!==void 0?T:B;return R.cloneElement(Y,{viewBox:ie(ie({},G),{},{x:G.left,y:G.top}),active:J,label:U,payload:J?K:[],coordinate:X,accessibilityLayer:I})}),ze(E,"renderBrush",function(T){var P=E.props,N=P.margin,I=P.data,Y=E.state,W=Y.offset,B=Y.dataStartIndex,X=Y.dataEndIndex,K=Y.updateId;return R.cloneElement(T,{key:T.key||"_recharts-brush",onChange:vf(E.handleBrushChange,T.props.onChange),data:I,x:ge(T.props.x)?T.props.x:W.left,y:ge(T.props.y)?T.props.y:W.top+W.height+W.brushBottom-(N.bottom||0),width:ge(T.props.width)?T.props.width:W.width,startIndex:B,endIndex:X,updateId:"brush-".concat(K)})}),ze(E,"renderReferenceElement",function(T,P,N){if(!T)return null;var I=E,Y=I.clipPathId,W=E.state,B=W.xAxisMap,X=W.yAxisMap,K=W.offset,U=T.type.defaultProps||{},G=T.props,J=G.xAxisId,F=J===void 0?U.xAxisId:J,te=G.yAxisId,q=te===void 0?U.yAxisId:te;return R.cloneElement(T,{key:T.key||"".concat(P,"-").concat(N),xAxis:B[F],yAxis:X[q],viewBox:{x:K.left,y:K.top,width:K.width,height:K.height},clipPathId:Y})}),ze(E,"renderActivePoints",function(T){var P=T.item,N=T.activePoint,I=T.basePoint,Y=T.childIndex,W=T.isRange,B=[],X=P.props.key,K=P.item.type.defaultProps!==void 0?ie(ie({},P.item.type.defaultProps),P.item.props):P.item.props,U=K.activeDot,G=K.dataKey,J=ie(ie({index:Y,dataKey:G,cx:N.x,cy:N.y,r:4,fill:B1(P.item),strokeWidth:2,stroke:"#fff",payload:N.payload,value:N.value},it(U,!1)),Hf(U));return B.push(k.renderActiveDot(U,J,"".concat(X,"-activePoint-").concat(Y))),I?B.push(k.renderActiveDot(U,ie(ie({},J),{},{cx:I.x,cy:I.y}),"".concat(X,"-basePoint-").concat(Y))):W&&B.push(null),B}),ze(E,"renderGraphicChild",function(T,P,N){var I=E.filterFormatItem(T,P,N);if(!I)return null;var Y=E.getTooltipEventType(),W=E.state,B=W.isTooltipActive,X=W.tooltipAxis,K=W.activeTooltipIndex,U=W.activeLabel,G=E.props.children,J=sn(G,ln),F=I.props,te=F.points,q=F.isRange,z=F.baseLine,L=I.item.type.defaultProps!==void 0?ie(ie({},I.item.type.defaultProps),I.item.props):I.item.props,Z=L.activeDot,se=L.hide,le=L.activeBar,ve=L.activeShape,qe=!!(!se&&B&&J&&(Z||le||ve)),xe={};Y!=="axis"&&J&&J.props.trigger==="click"?xe={onClick:vf(E.handleItemMouseEnter,T.props.onClick)}:Y!=="axis"&&(xe={onMouseLeave:vf(E.handleItemMouseLeave,T.props.onMouseLeave),onMouseEnter:vf(E.handleItemMouseEnter,T.props.onMouseEnter)});var ae=R.cloneElement(T,ie(ie({},I.props),xe));function Se(_t){return typeof X.dataKey=="function"?X.dataKey(_t.payload):null}if(qe)if(K>=0){var Me,oe;if(X.dataKey&&!X.allowDuplicatedCategory){var tt=typeof X.dataKey=="function"?Se:"payload.".concat(X.dataKey.toString());Me=Ff(te,tt,U),oe=q&&z&&Ff(z,tt,U)}else Me=te==null?void 0:te[K],oe=q&&z&&z[K];if(ve||le){var Fe=T.props.activeIndex!==void 0?T.props.activeIndex:K;return[R.cloneElement(T,ie(ie(ie({},I.props),xe),{},{activeIndex:Fe})),null,null]}if(!Qe(Me))return[ae].concat(dl(E.renderActivePoints({item:I,activePoint:Me,basePoint:oe,childIndex:K,isRange:q})))}else{var kt,wt=(kt=E.getItemByXY(E.state.activeCoordinate))!==null&&kt!==void 0?kt:{graphicalItem:ae},Et=wt.graphicalItem,Sr=Et.item,Bt=Sr===void 0?T:Sr,Rr=Et.childIndex,lr=ie(ie(ie({},I.props),xe),{},{activeIndex:Rr});return[R.cloneElement(Bt,lr),null,null]}return q?[ae,null,null]:[ae,null]}),ze(E,"renderCustomized",function(T,P,N){return R.cloneElement(T,ie(ie({key:"recharts-customized-".concat(N)},E.props),E.state))}),ze(E,"renderMap",{CartesianGrid:{handler:Sf,once:!0},ReferenceArea:{handler:E.renderReferenceElement},ReferenceLine:{handler:Sf},ReferenceDot:{handler:E.renderReferenceElement},XAxis:{handler:Sf},YAxis:{handler:Sf},Brush:{handler:E.renderBrush,once:!0},Bar:{handler:E.renderGraphicChild},Line:{handler:E.renderGraphicChild},Area:{handler:E.renderGraphicChild},Radar:{handler:E.renderGraphicChild},RadialBar:{handler:E.renderGraphicChild},Scatter:{handler:E.renderGraphicChild},Pie:{handler:E.renderGraphicChild},Funnel:{handler:E.renderGraphicChild},Tooltip:{handler:E.renderCursor,once:!0},PolarGrid:{handler:E.renderPolarGrid,once:!0},PolarAngleAxis:{handler:E.renderPolarAxis},PolarRadiusAxis:{handler:E.renderPolarAxis},Customized:{handler:E.renderCustomized}}),E.clipPathId="".concat((O=A.id)!==null&&O!==void 0?O:Iu("recharts"),"-clip"),E.throttleTriggeredAfterMouseMove=fI(E.triggeredAfterMouseMove,(C=A.throttleDelay)!==null&&C!==void 0?C:1e3/60),E.state={},E}return pne(k,b),une(k,[{key:"componentDidMount",value:function(){var O,C;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(O=this.props.margin.left)!==null&&O!==void 0?O:0,top:(C=this.props.margin.top)!==null&&C!==void 0?C:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var O=this.props,C=O.children,E=O.data,T=O.height,P=O.layout,N=sn(C,ln);if(N){var I=N.props.defaultIndex;if(!(typeof I!="number"||I<0||I>this.state.tooltipTicks.length-1)){var Y=this.state.tooltipTicks[I]&&this.state.tooltipTicks[I].value,W=vw(this.state,E,I,Y),B=this.state.tooltipTicks[I].coordinate,X=(this.state.offset.top+T)/2,K=P==="horizontal",U=K?{x:B,y:X}:{y:B,x:X},G=this.state.formattedGraphicalItems.find(function(F){var te=F.item;return te.type.name==="Scatter"});G&&(U=ie(ie({},U),G.props.points[I].tooltipPosition),W=G.props.points[I].tooltipPayload);var J={activeTooltipIndex:I,isTooltipActive:!0,activeLabel:Y,activePayload:W,activeCoordinate:U};this.setState(J),this.renderCursor(N),this.accessibilityManager.setIndex(I)}}}},{key:"getSnapshotBeforeUpdate",value:function(O,C){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==C.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==O.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==O.margin){var E,T;this.accessibilityManager.setDetails({offset:{left:(E=this.props.margin.left)!==null&&E!==void 0?E:0,top:(T=this.props.margin.top)!==null&&T!==void 0?T:0}})}return null}},{key:"componentDidUpdate",value:function(O){nx([sn(O.children,ln)],[sn(this.props.children,ln)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var O=sn(this.props.children,ln);if(O&&typeof O.props.shared=="boolean"){var C=O.props.shared?"axis":"item";return l.indexOf(C)>=0?C:a}return a}},{key:"getMouseInfo",value:function(O){if(!this.container)return null;var C=this.container,E=C.getBoundingClientRect(),T=_W(E),P={chartX:Math.round(O.pageX-T.left),chartY:Math.round(O.pageY-T.top)},N=E.width/C.offsetWidth||1,I=this.inRange(P.chartX,P.chartY,N);if(!I)return null;var Y=this.state,W=Y.xAxisMap,B=Y.yAxisMap,X=this.getTooltipEventType(),K=mP(this.state,this.props.data,this.props.layout,I);if(X!=="axis"&&W&&B){var U=Na(W).scale,G=Na(B).scale,J=U&&U.invert?U.invert(P.chartX):null,F=G&&G.invert?G.invert(P.chartY):null;return ie(ie({},P),{},{xValue:J,yValue:F},K)}return K?ie(ie({},P),K):null}},{key:"inRange",value:function(O,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,T=this.props.layout,P=O/E,N=C/E;if(T==="horizontal"||T==="vertical"){var I=this.state.offset,Y=P>=I.left&&P<=I.left+I.width&&N>=I.top&&N<=I.top+I.height;return Y?{x:P,y:N}:null}var W=this.state,B=W.angleAxisMap,X=W.radiusAxisMap;if(B&&X){var K=Na(B);return NC({x:P,y:N},K)}return null}},{key:"parseEventsOfWrapper",value:function(){var O=this.props.children,C=this.getTooltipEventType(),E=sn(O,ln),T={};E&&C==="axis"&&(E.props.trigger==="click"?T={onClick:this.handleClick}:T={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 P=Hf(this.props,this.handleOuterEvent);return ie(ie({},P),T)}},{key:"addListener",value:function(){Ab.on(Tb,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Ab.removeListener(Tb,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(O,C,E){for(var T=this.state.formattedGraphicalItems,P=0,N=T.length;P<N;P++){var I=T[P];if(I.item===O||I.props.key===O.key||C===Gi(I.item.type)&&E===I.childIndex)return I}return null}},{key:"renderClipPath",value:function(){var O=this.clipPathId,C=this.state.offset,E=C.left,T=C.top,P=C.height,N=C.width;return $.createElement("defs",null,$.createElement("clipPath",{id:O},$.createElement("rect",{x:E,y:T,height:P,width:N})))}},{key:"getXScales",value:function(){var O=this.state.xAxisMap;return O?Object.entries(O).reduce(function(C,E){var T=fP(E,2),P=T[0],N=T[1];return ie(ie({},C),{},ze({},P,N.scale))},{}):null}},{key:"getYScales",value:function(){var O=this.state.yAxisMap;return O?Object.entries(O).reduce(function(C,E){var T=fP(E,2),P=T[0],N=T[1];return ie(ie({},C),{},ze({},P,N.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(O){var C;return(C=this.state.xAxisMap)===null||C===void 0||(C=C[O])===null||C===void 0?void 0:C.scale}},{key:"getYScaleByAxisId",value:function(O){var C;return(C=this.state.yAxisMap)===null||C===void 0||(C=C[O])===null||C===void 0?void 0:C.scale}},{key:"getItemByXY",value:function(O){var C=this.state,E=C.formattedGraphicalItems,T=C.activeItem;if(E&&E.length)for(var P=0,N=E.length;P<N;P++){var I=E[P],Y=I.props,W=I.item,B=W.type.defaultProps!==void 0?ie(ie({},W.type.defaultProps),W.props):W.props,X=Gi(W.type);if(X==="Bar"){var K=(Y.data||[]).find(function(F){return FZ(O,F)});if(K)return{graphicalItem:I,payload:K}}else if(X==="RadialBar"){var U=(Y.data||[]).find(function(F){return NC(O,F)});if(U)return{graphicalItem:I,payload:U}}else if(Ep(I,T)||Op(I,T)||vu(I,T)){var G=RQ({graphicalItem:I,activeTooltipItem:T,itemData:B.data}),J=B.activeIndex===void 0?G:B.activeIndex;return{graphicalItem:ie(ie({},I),{},{childIndex:J}),payload:vu(I,T)?B.data[G]:I.props.data[G]}}}return null}},{key:"render",value:function(){var O=this;if(!FO(this))return null;var C=this.props,E=C.children,T=C.className,P=C.width,N=C.height,I=C.style,Y=C.compact,W=C.title,B=C.desc,X=hP(C,nne),K=it(X,!1);if(Y)return $.createElement(Kj,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},$.createElement(ax,$s({},K,{width:P,height:N,title:W,desc:B}),this.renderClipPath(),WO(E,this.renderMap)));if(this.props.accessibilityLayer){var U,G;K.tabIndex=(U=this.props.tabIndex)!==null&&U!==void 0?U:0,K.role=(G=this.props.role)!==null&&G!==void 0?G:"application",K.onKeyDown=function(F){O.accessibilityManager.keyboardEvent(F)},K.onFocus=function(){O.accessibilityManager.focus()}}var J=this.parseEventsOfWrapper();return $.createElement(Kj,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},$.createElement("div",$s({className:at("recharts-wrapper",T),style:ie({position:"relative",cursor:"default",width:P,height:N},I)},J,{ref:function(te){O.container=te}}),$.createElement(ax,$s({},K,{width:P,height:N,title:W,desc:B,style:xne}),this.renderClipPath(),WO(E,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])})(R.Component);ze(x,"displayName",r),ze(x,"defaultProps",ie({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},f)),ze(x,"getDerivedStateFromProps",function(b,k){var A=b.dataKey,O=b.data,C=b.children,E=b.width,T=b.height,P=b.layout,N=b.stackOffset,I=b.margin,Y=k.dataStartIndex,W=k.dataEndIndex;if(k.updateId===void 0){var B=gP(b);return ie(ie(ie({},B),{},{updateId:0},v(ie(ie({props:b},B),{},{updateId:0}),k)),{},{prevDataKey:A,prevData:O,prevWidth:E,prevHeight:T,prevLayout:P,prevStackOffset:N,prevMargin:I,prevChildren:C})}if(A!==k.prevDataKey||O!==k.prevData||E!==k.prevWidth||T!==k.prevHeight||P!==k.prevLayout||N!==k.prevStackOffset||!zs(I,k.prevMargin)){var X=gP(b),K={chartX:k.chartX,chartY:k.chartY,isTooltipActive:k.isTooltipActive},U=ie(ie({},mP(k,O,P)),{},{updateId:k.updateId+1}),G=ie(ie(ie({},X),K),U);return ie(ie(ie({},G),v(ie({props:b},G),k)),{},{prevDataKey:A,prevData:O,prevWidth:E,prevHeight:T,prevLayout:P,prevStackOffset:N,prevMargin:I,prevChildren:C})}if(!nx(C,k.prevChildren)){var J,F,te,q,z=sn(C,tl),L=z&&(J=(F=z.props)===null||F===void 0?void 0:F.startIndex)!==null&&J!==void 0?J:Y,Z=z&&(te=(q=z.props)===null||q===void 0?void 0:q.endIndex)!==null&&te!==void 0?te:W,se=L!==Y||Z!==W,le=!Qe(O),ve=le&&!se?k.updateId:k.updateId+1;return ie(ie({updateId:ve},v(ie(ie({props:b},k),{},{updateId:ve,dataStartIndex:L,dataEndIndex:Z}),k)),{},{prevChildren:C,dataStartIndex:L,dataEndIndex:Z})}return null}),ze(x,"renderActiveDot",function(b,k,A){var O;return R.isValidElement(b)?O=R.cloneElement(b,k):Ye(b)?O=b(k):O=$.createElement(q1,k),$.createElement(Xt,{className:"recharts-active-dot",key:A},O)});var _=R.forwardRef(function(k,A){return $.createElement(x,$s({},k,{ref:A}))});return _.displayName=x.displayName,_},jne=bM({chartName:"LineChart",GraphicalChild:Uu,axisComponents:[{axisType:"xAxis",AxisComp:za},{axisType:"yAxis",AxisComp:Ba}],formatAxisMap:D$}),bw=bM({chartName:"BarChart",GraphicalChild:ea,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:za},{axisType:"yAxis",AxisComp:Ba}],formatAxisMap:D$});const qh={backgroundColor:"#1e1e1e",border:"1px solid rgba(255,255,255,0.08)",borderRadius:"12px",color:"#e4e0dc",fontSize:"11px",fontFamily:"JetBrains Mono, monospace"};function Rt(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(Math.round(t))}function Zn(t){return`$${t.toFixed(2)}`}function $a({label:t,value:e,sub:r,accent:n}){return y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-5 py-4",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-600 mb-1",children:t}),y.jsx("p",{className:`text-xl font-mono font-medium ${n?"text-[#E43A9C]":"text-zinc-100"}`,children:e}),r&&y.jsx("p",{className:"text-[10px] font-mono text-zinc-600 mt-0.5",children:r})]})}const Pne={summary:"Summary","by squad":"By Squad","by agent":"By Agent",io:"IO",timeline:"Timeline"};function Nne({tabs:t,active:e,onChange:r}){return y.jsx("div",{className:"flex gap-0 border-b border-white/[0.06] mb-5",children:t.map(n=>y.jsx("button",{type:"button",onClick:()=>r(n),className:`px-4 py-2 text-[11px] font-mono transition-colors border-b-2 -mb-px cursor-pointer ${e===n?"text-[#E43A9C] border-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 border-transparent"}`,children:Pne[n]??n},n))})}function Rne({records:t,totals:e}){const r=e.totalInputTokens+e.totalOutputTokens,n=new Map;for(const o of t){const l=o.squadId??"__io__",u=o.squadName??(o.squadId?`${o.squadId.slice(0,8)} (deleted)`:"IO Orchestrator"),d=n.get(l)??{name:u,inputTokens:0,outputTokens:0,calls:0,cost:0};d.inputTokens+=o.inputTokens,d.outputTokens+=o.outputTokens,d.calls+=1,d.cost+=o.estimatedCostUsd??0,n.set(l,d)}const i=Array.from(n.values()).sort((o,l)=>l.cost-o.cost),a=i.map(o=>({name:o.name.length>12?`${o.name.slice(0,12)}…`:o.name,cost:Number.parseFloat(o.cost.toFixed(2)),tokens:Math.round((o.inputTokens+o.outputTokens)/1e3)}));return y.jsxs("div",{className:"space-y-5",children:[y.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[y.jsx($a,{label:"Total Tokens",value:Rt(r),sub:`${Rt(e.totalInputTokens)} in · ${Rt(e.totalOutputTokens)} out`}),y.jsx($a,{label:"Total Cost",value:Zn(e.totalCostUsd),accent:!0}),y.jsx($a,{label:"API Calls",value:Rt(e.callCount),sub:"across all entities"}),y.jsx($a,{label:"Avg Cost / Call",value:e.callCount>0?Zn(e.totalCostUsd/e.callCount):"$0.00",sub:`over ${e.callCount} calls`})]}),y.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Cost by entity"}),a.length>0?y.jsx(th,{width:"100%",height:180,children:y.jsxs(bw,{data:a,barCategoryGap:"35%",children:[y.jsx(Su,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(za,{dataKey:"name",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ba,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:o=>`$${o}`,width:40}),y.jsx(ln,{contentStyle:qh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:o=>[`$${o.toFixed(2)}`,"Cost"]}),y.jsx(ea,{dataKey:"cost",fill:"url(#costGrad)",radius:[6,6,0,0]}),y.jsx("defs",{children:y.jsxs("linearGradient",{id:"costGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[y.jsx("stop",{offset:"0%",stopColor:"#E43A9C"}),y.jsx("stop",{offset:"100%",stopColor:"#D83333",stopOpacity:.7})]})})]})}):y.jsx("div",{className:"h-[180px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Tokens by entity (k)"}),a.length>0?y.jsx(th,{width:"100%",height:180,children:y.jsxs(bw,{data:a,barCategoryGap:"35%",children:[y.jsx(Su,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(za,{dataKey:"name",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ba,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:o=>`${o}k`,width:40}),y.jsx(ln,{contentStyle:qh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:o=>[`${o}k`,"Tokens"]}),y.jsx(ea,{dataKey:"tokens",fill:"url(#tokenGrad)",radius:[6,6,0,0]}),y.jsx("defs",{children:y.jsxs("linearGradient",{id:"tokenGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[y.jsx("stop",{offset:"0%",stopColor:"#818cf8"}),y.jsx("stop",{offset:"100%",stopColor:"#6366f1",stopOpacity:.7})]})})]})}):y.jsx("div",{className:"h-[180px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]})]}),y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Entity","Input","Output","Calls","Cost"].map(o=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${o==="Cost"?"text-right":""}`,children:o},o))})}),y.jsxs("tbody",{children:[i.map(o=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:o.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(o.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(o.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:o.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(o.cost)})]},o.name)),y.jsxs("tr",{className:"bg-[#1a1a1a]",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-200 font-medium",children:"Total"}),y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:Rt(e.totalInputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:Rt(e.totalOutputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:e.callCount}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C] font-medium",children:Zn(e.totalCostUsd)})]})]})]})})]})}function Ine({records:t}){const[e,r]=R.useState([]),[n,i]=R.useState("cost"),[a,o]=R.useState("desc");function l(f){f===n?o(g=>g==="asc"?"desc":"asc"):(i(f),o("desc"))}const u=R.useMemo(()=>{const f=new Map;for(const v of t){if(!v.squadId)continue;const x=f.get(v.squadId)??{id:v.squadId,name:v.squadName??`${v.squadId.slice(0,8)} (deleted)`,agents:new Map,inputTokens:0,outputTokens:0,calls:0,cost:0};x.inputTokens+=v.inputTokens,x.outputTokens+=v.outputTokens,x.calls+=1,x.cost+=v.estimatedCostUsd??0;const _=`${v.agentRole??"unknown"}:${v.model}`,b=x.agents.get(_)??{role:v.agentRole??"unknown",model:v.model,inputTokens:0,outputTokens:0,calls:0,cost:0};b.inputTokens+=v.inputTokens,b.outputTokens+=v.outputTokens,b.calls+=1,b.cost+=v.estimatedCostUsd??0,x.agents.set(_,b),f.set(v.squadId,x)}return[...Array.from(f.values())].sort((v,x)=>{const _=v[n],b=x[n],k=typeof _=="string"?_.localeCompare(b):_-b;return a==="desc"?-k:k})},[t,n,a]),d=f=>r(g=>g.includes(f)?g.filter(v=>v!==f):[...g,f]),p=[{key:"name",label:"Squad"},{key:"inputTokens",label:"In"},{key:"outputTokens",label:"Out"},{key:"calls",label:"Calls"},{key:"cost",label:"Cost"}];return u.length===0?y.jsx("div",{className:"text-center py-12 text-zinc-700 text-[11px] font-mono",children:"No squad usage data"}):y.jsxs("div",{className:"space-y-2",children:[y.jsxs("div",{className:"flex items-center gap-1 px-1 mb-1",children:[y.jsx("span",{className:"text-[10px] font-mono text-zinc-700 mr-1",children:"sort by"}),p.map(f=>y.jsxs("button",{type:"button",onClick:()=>l(f.key),className:`flex items-center gap-0.5 px-2 py-1 rounded-lg text-[10px] font-mono transition-colors ${n===f.key?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-400 hover:bg-white/[0.04]"}`,style:n===f.key?{background:"rgba(228,58,156,0.1)"}:void 0,children:[f.label,n===f.key&&y.jsx("span",{className:"text-[9px]",children:a==="desc"?"↓":"↑"})]},f.key))]}),u.map(f=>{const g=e.includes(f.id),v=Array.from(f.agents.values());return y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl overflow-hidden",children:[y.jsxs("button",{type:"button",onClick:()=>d(f.id),className:"w-full flex items-center gap-3 px-4 py-3.5 hover:bg-white/[0.02] transition-colors text-left cursor-pointer",children:[y.jsx("div",{className:`transition-transform ${g?"rotate-90":""}`,children:y.jsx(jw,{className:"w-3.5 h-3.5 text-zinc-600"})}),y.jsx("span",{className:"text-sm font-mono text-zinc-100 flex-1",children:f.name}),y.jsxs("div",{className:"flex items-center gap-6 text-[11px] font-mono",children:[y.jsxs("span",{className:"text-zinc-500 hidden sm:block",children:[y.jsx("span",{className:"text-zinc-700 mr-1",children:"in"}),Rt(f.inputTokens)]}),y.jsxs("span",{className:"text-zinc-500 hidden sm:block",children:[y.jsx("span",{className:"text-zinc-700 mr-1",children:"out"}),Rt(f.outputTokens)]}),y.jsxs("span",{className:"text-zinc-500",children:[y.jsx("span",{className:"text-zinc-700 mr-1",children:"calls"}),f.calls]}),y.jsx("span",{className:"text-[#E43A9C] font-medium w-16 text-right",children:Zn(f.cost)})]})]}),g&&y.jsx("div",{className:"border-t border-white/[0.05]",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"bg-[#191919]",children:["Agent","Model","Input","Output","Calls","Cost"].map(x=>y.jsx("th",{className:`text-left px-4 py-2 text-zinc-700 font-medium ${x==="Cost"?"text-right":""}`,children:x},x))})}),y.jsx("tbody",{children:v.map(x=>y.jsxs("tr",{className:"border-t border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-2.5 text-zinc-300",children:x.role}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-600",children:x.model}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-500",children:Rt(x.inputTokens)}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-500",children:Rt(x.outputTokens)}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-500",children:x.calls}),y.jsx("td",{className:"px-4 py-2.5 text-right text-[#E43A9C]",children:Zn(x.cost)})]},x.role))})]})})]},f.id)})]})}function $ne({records:t}){const e=R.useMemo(()=>{const n=new Map;for(const i of t){const a=`${i.squadId??"io"}:${i.agentRole??"orchestrator"}:${i.model}`,o=n.get(a)??{name:i.agentRole??"orchestrator",squad:i.squadName??(i.squadId?i.squadId.slice(0,8):"IO"),model:i.model,inputTokens:0,outputTokens:0,calls:0,cost:0};o.inputTokens+=i.inputTokens,o.outputTokens+=i.outputTokens,o.calls+=1,o.cost+=i.estimatedCostUsd??0,n.set(a,o)}return Array.from(n.values()).sort((i,a)=>a.cost-i.cost)},[t]),r=e.reduce((n,i)=>n+i.cost,0);return y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Agent","Squad","Model","Input","Output","Calls","Cost","% of total"].map(n=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${n==="Cost"?"text-right":""}`,children:n},n))})}),y.jsx("tbody",{children:e.map(n=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:n.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:n.squad}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:n.model}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(n.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(n.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:n.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(n.cost)}),y.jsx("td",{className:"px-4 py-3",children:y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("div",{className:"w-16 h-1.5 rounded-full bg-[#252525] overflow-hidden",children:y.jsx("div",{className:"h-full bg-[#E43A9C] rounded-full",style:{width:`${r>0?n.cost/r*100:0}%`}})}),y.jsx("span",{className:"text-zinc-600 text-[10px]",children:r>0?`${(n.cost/r*100).toFixed(1)}%`:"0%"})]})})]},`${n.squad}:${n.name}`))})]})})}function Mne({records:t}){const e=R.useMemo(()=>t.filter(o=>!o.squadId),[t]),r=R.useMemo(()=>{const o=new Map;for(const l of e){const u=`${l.agentRole??"orchestrator"}:${l.model}`,d=o.get(u)??{name:l.agentRole??"orchestrator",model:l.model,inputTokens:0,outputTokens:0,calls:0,cost:0};d.inputTokens+=l.inputTokens,d.outputTokens+=l.outputTokens,d.calls+=1,d.cost+=l.estimatedCostUsd??0,o.set(u,d)}return Array.from(o.values()).sort((l,u)=>u.cost-l.cost)},[e]),n=e.reduce((o,l)=>o+l.inputTokens,0),i=e.reduce((o,l)=>o+l.outputTokens,0),a=e.reduce((o,l)=>o+(l.estimatedCostUsd??0),0);return y.jsxs("div",{className:"space-y-5",children:[y.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[y.jsx($a,{label:"IO Tokens",value:Rt(n+i),sub:`${Rt(n)} in · ${Rt(i)} out`}),y.jsx($a,{label:"IO Cost",value:Zn(a),accent:!0}),y.jsx($a,{label:"IO Calls",value:Rt(e.length)}),y.jsx($a,{label:"IO Roles",value:String(r.length)})]}),y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Role","Model","Input","Output","Calls","Cost"].map(o=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${o==="Cost"?"text-right":""}`,children:o},o))})}),y.jsx("tbody",{children:r.map(o=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:o.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:o.model}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(o.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(o.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:o.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(o.cost)})]},o.name))})]})})]})}function Lne({records:t}){const e=ml(),r=R.useMemo(()=>{const i=new Map;for(const a of t){const o=a.timestamp.slice(0,10),l=i.get(o)??{date:o,inputTokens:0,outputTokens:0,cost:0,calls:0};l.inputTokens+=a.inputTokens,l.outputTokens+=a.outputTokens,l.cost+=a.estimatedCostUsd??0,l.calls+=1,i.set(o,l)}return Array.from(i.values()).sort((a,o)=>a.date.localeCompare(o.date))},[t]),n=r.map(i=>({...i,label:Z4(i.date,e),tokens:i.inputTokens+i.outputTokens}));return y.jsxs("div",{className:"space-y-5",children:[y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-5",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Tokens per day"}),n.length>0?y.jsx(th,{width:"100%",height:220,children:y.jsxs(jne,{data:n,children:[y.jsx(Su,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(za,{dataKey:"label",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ba,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:Rt,width:44}),y.jsx(ln,{contentStyle:qh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:i=>[Rt(i),"Tokens"]}),y.jsx(Uu,{type:"monotone",dataKey:"tokens",stroke:"#E43A9C",strokeWidth:2,dot:!1})]})}):y.jsx("div",{className:"h-[220px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-5",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Cost per day"}),n.length>0?y.jsx(th,{width:"100%",height:180,children:y.jsxs(bw,{data:n,barCategoryGap:"20%",children:[y.jsx(Su,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(za,{dataKey:"label",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ba,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:i=>`$${i.toFixed(2)}`,width:44}),y.jsx(ln,{contentStyle:qh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:i=>[Zn(i),"Cost"]}),y.jsx(ea,{dataKey:"cost",fill:"url(#costGradTl)",radius:[4,4,0,0]}),y.jsx("defs",{children:y.jsxs("linearGradient",{id:"costGradTl",x1:"0",y1:"0",x2:"0",y2:"1",children:[y.jsx("stop",{offset:"0%",stopColor:"#E43A9C"}),y.jsx("stop",{offset:"100%",stopColor:"#D83333",stopOpacity:.7})]})})]})}):y.jsx("div",{className:"h-[180px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]}),y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Date","Input","Output","Calls","Cost"].map(i=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${i==="Cost"?"text-right":""}`,children:i},i))})}),y.jsx("tbody",{children:r.map(i=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:i.date}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(i.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:Rt(i.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:i.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(i.cost)})]},i.date))})]})})]})}function Dne(){const[t,e]=R.useState("summary"),[r,n]=R.useState(null),[i,a]=R.useState("14d"),o=["summary","by squad","by agent","io","timeline"];if(R.useEffect(()=>{const u=new Date;i==="7d"?u.setDate(u.getDate()-7):i==="14d"?u.setDate(u.getDate()-14):i==="30d"?u.setDate(u.getDate()-30):u.setDate(u.getDate()-1),et.get(`/usage?since=${u.toISOString()}`).then(n).catch(()=>{})},[i]),!r)return y.jsx("div",{className:"h-full flex items-center justify-center text-zinc-600 font-mono text-[11px]",children:"Loading..."});const l=i==="1d"?"Today":`Last ${i}`;return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[y.jsxs("div",{className:"flex items-start justify-between mb-5 gap-4 flex-wrap",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Usage"}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:l})]}),y.jsx("div",{className:"flex gap-1 p-1 rounded-xl bg-white/[0.03] border border-white/[0.07]",children:["1d","7d","14d","30d"].map(u=>y.jsx("button",{type:"button",onClick:()=>a(u),className:`px-3 py-1.5 rounded-lg text-[11px] font-mono transition-colors cursor-pointer ${i===u?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-400"}`,style:i===u?{background:"rgba(228,58,156,0.12)"}:void 0,children:u},u))})]}),y.jsx(Nne,{tabs:o,active:t,onChange:u=>e(u)}),t==="summary"&&y.jsx(Rne,{records:r.records,totals:r.totals}),t==="by squad"&&y.jsx(Ine,{records:r.records}),t==="by agent"&&y.jsx($ne,{records:r.records}),t==="io"&&y.jsx(Mne,{records:r.records}),t==="timeline"&&y.jsx(Lne,{records:r.records})]})}function xM(t){return[...t].sort((e,r)=>e.isDir!==r.isDir?e.isDir?-1:1:e.name.localeCompare(r.name)).map(e=>({...e,children:xM(e.children)}))}function zne(t){const e=[];for(const r of t){const n=r.path.split("/").filter(Boolean);let i=e,a="";if(r.isDir){for(const o of n){a=a?`${a}/${o}`:o;let l=i.find(u=>u.path===a);l||(l={name:o,path:a,isDir:!0,children:[]},i.push(l)),i=l.children}continue}for(const[o,l]of n.entries()){const u=o===n.length-1;a=a?`${a}/${l}`:l;let d=i.find(p=>p.path===a);d||(d={name:u&&r.name||l,path:a,isDir:!u,children:[]},i.push(d)),i=d.children}}return xM(e)}function wM(t,e){return e?t.flatMap(r=>{const n=r.name.toLowerCase().includes(e)||r.path.toLowerCase().includes(e);if(!r.isDir)return n?[r]:[];if(n)return[r];const i=wM(r.children,e);return i.length?[{...r,children:i}]:[]}):t}function xw(t){const e=new Set;for(const r of t)if(r.isDir){e.add(r.path);for(const n of xw(r.children))e.add(n)}return e}function Bne(t){const e=t.split("/").filter(Boolean),r=[];let n="";for(const i of e.slice(0,-1))n=n?`${n}/${i}`:i,r.push(n);return r}function _M({node:t,depth:e,selectedPage:r,expandedPaths:n,autoExpandedPaths:i,onToggle:a,onSelect:o}){const l=r===t.path,u=t.isDir&&(n.has(t.path)||i.has(t.path)),d=12+e*16;return t.isDir?y.jsxs("div",{children:[y.jsxs("button",{type:"button",onClick:()=>a(t.path),className:"flex w-full items-center gap-2 rounded-lg py-2 pr-3 text-left text-[11px] font-mono text-zinc-400 transition-colors hover:bg-white/[0.04] hover:text-zinc-200",style:{paddingLeft:d},children:[y.jsx(jw,{size:14,className:`shrink-0 transition-transform ${u?"rotate-90":""}`}),u?y.jsx(i4,{size:14,className:"shrink-0 text-zinc-500"}):y.jsx(o4,{size:14,className:"shrink-0 text-zinc-500"}),y.jsx("span",{className:"truncate",children:t.name})]}),u&&y.jsx("div",{children:t.children.map(p=>y.jsx(_M,{node:p,depth:e+1,selectedPage:r,expandedPaths:n,autoExpandedPaths:i,onToggle:a,onSelect:o},p.path))})]}):y.jsxs("button",{type:"button",onClick:()=>o(t.path),className:`flex w-full items-center gap-2 rounded-lg py-2 pr-3 text-left text-[11px] font-mono transition-colors ${l?"border-l-2 border-[#E43A9C] bg-[#E43A9C]/10 text-[#E43A9C]":"text-zinc-500 hover:bg-white/[0.04] hover:text-zinc-300"}`,style:{paddingLeft:d},children:[y.jsx(r4,{size:14,className:"shrink-0"}),y.jsx("span",{className:"truncate",children:t.name})]})}function Une(){const[t,e]=R.useState([]),[r,n]=R.useState(null),[i,a]=R.useState(""),[o,l]=R.useState(!1),[u,d]=R.useState(""),[p,f]=R.useState(""),[g,v]=R.useState(""),[x,_]=R.useState(new Set),[b,k]=R.useState(!1);R.useEffect(()=>{N()},[]);const A=R.useMemo(()=>zne(t),[t]),O=g.trim().toLowerCase(),C=R.useMemo(()=>wM(A,O),[A,O]),E=R.useMemo(()=>{const U=O?xw(C):new Set;if(r)for(const G of Bne(r))U.add(G);return U},[C,O,r]),T=r?(function U(G){for(const J of G){if(J.path===r)return J;const F=U(J.children);if(F)return F}return null})(C):null,P=(T==null?void 0:T.name)??(r?r.split("/").pop()??"":"");R.useEffect(()=>{const U=xw(A);_(G=>new Set([...G,...U]))},[A]);async function N(){try{const U=await et.get("/wiki/all");e(U.pages)}catch{e([])}}function I(U){if(U.startsWith("squads/")){const G=U.split("/"),J=G[1]??"",F=G.slice(2).join("/");return{scope:J,relativePath:F}}return U.startsWith("io/")?{scope:"io",relativePath:U.slice(3)}:U.startsWith("shared/")?{scope:"shared",relativePath:U.slice(7)}:{scope:"shared",relativePath:U}}async function Y(U){try{const{scope:G,relativePath:J}=I(U),F=await et.get(`/wiki/${G}/${J}`);a(F.content),d(F.content),n(U),l(!1)}catch{ft.error("Failed to load page")}}async function W(){if(r)try{const{scope:U,relativePath:G}=I(r);await et.put(`/wiki/${U}/${G}`,{content:u}),a(u),l(!1),ft.success("Page saved")}catch{ft.error("Failed to save page")}}async function B(){if(r)try{const{scope:U,relativePath:G}=I(r);await et.delete(`/wiki/${U}/${G}`),ft.success("Page deleted"),n(null),a(""),d(""),l(!1),N()}catch{ft.error("Failed to delete page")}}async function X(){let U=p.trim().replace(/^\/+|\/+$/g,"");if(!U)return;U=U.replace(/\.md$/i,"");const G=U.startsWith("io/")||U.startsWith("shared/")||U.startsWith("squads/")?U:`shared/${U}`;k(!0);try{const{scope:J,relativePath:F}=I(G),te=F.split("/").slice(-1)[0]??F;await et.put(`/wiki/${J}/${F}`,{content:`# ${te}
503
503
 
504
504
  `}),ft.success("Page created"),f(""),await N(),await Y(G)}catch{ft.error("Failed to create page")}finally{k(!1)}}function K(U){_(G=>{const J=new Set(G);return J.has(U)?J.delete(U):J.add(U),J})}return y.jsxs("div",{className:"flex h-full",children:[y.jsxs("div",{className:"flex h-full w-64 flex-col border-r border-white/[0.07] bg-[#181818]",children:[y.jsx("div",{className:"border-b border-white/[0.07] p-3",children:y.jsxs("div",{className:"relative",children:[y.jsx(VP,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-zinc-600"}),y.jsx("input",{type:"text",value:g,onChange:U=>v(U.target.value),placeholder:"Search pages...",className:"w-full rounded-lg border border-white/[0.07] bg-white/[0.04] py-2 pl-8 pr-3 text-[11px] font-mono text-zinc-300 outline-none placeholder:text-zinc-700 focus:border-[#E43A9C]/50"})]})}),y.jsx("div",{className:"flex-1 overflow-y-auto px-2 py-3",children:C.length>0?C.map(U=>y.jsx(_M,{node:U,depth:0,selectedPage:r,expandedPaths:x,autoExpandedPaths:E,onToggle:K,onSelect:Y},U.path)):y.jsx("p",{className:"py-4 text-center font-mono text-[11px] text-zinc-700",children:"No pages found"})}),y.jsx("div",{className:"border-t border-white/[0.07] p-3",children:y.jsxs("div",{className:"space-y-2",children:[y.jsx("input",{type:"text",value:p,onChange:U=>f(U.target.value),onKeyDown:U=>{U.key==="Enter"&&X(),U.key==="Escape"&&f("")},placeholder:"folder/new-page",className:"w-full rounded-lg border border-white/[0.07] bg-white/[0.04] px-3 py-2 text-[11px] font-mono text-zinc-300 outline-none placeholder:text-zinc-700 focus:border-[#E43A9C]/50"}),y.jsx(Da,{onClick:X,disabled:!p.trim()||b,className:"w-full justify-center px-3 py-2",children:b?y.jsxs(y.Fragment,{children:[y.jsx(As,{size:13,className:"animate-spin"})," Creating..."]}):y.jsxs(y.Fragment,{children:[y.jsx(KP,{size:13})," Add Page"]})})]})})]}),y.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:r?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex h-14 shrink-0 items-center justify-between border-b border-white/[0.07] px-6",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("h3",{className:"truncate font-mono text-sm text-zinc-100",children:P}),y.jsxs("p",{className:"truncate font-mono text-[11px] text-zinc-500",children:[r,".md"]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[o?y.jsxs(y.Fragment,{children:[y.jsxs(Da,{onClick:W,className:"px-3 py-1.5",children:[y.jsx(Pw,{size:12})," Save"]}),y.jsx(Wi,{onClick:()=>{l(!1),d(i)},className:"px-3 py-1.5",children:"Cancel"})]}):y.jsxs(Wi,{onClick:()=>{l(!0),d(i)},className:"px-3 py-1.5",children:[y.jsx($b,{size:12})," Edit"]}),y.jsxs(Hw,{onClick:B,className:"px-3 py-1.5",children:[y.jsx(Ms,{size:12})," Delete"]})]})]}),y.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:o?y.jsx("textarea",{value:u,onChange:U=>d(U.target.value),className:"h-full min-h-[320px] w-full resize-none rounded-xl border border-white/[0.07] bg-[#181818] p-4 font-mono text-sm text-zinc-300 outline-none focus:border-[#E43A9C]/50"}):y.jsx("div",{className:"mx-auto max-w-4xl",children:y.jsx("div",{className:"prose-io text-sm text-zinc-300",dangerouslySetInnerHTML:{__html:nt.parse(i)}})})})]}):y.jsx("div",{className:"flex h-full items-center justify-center",children:y.jsxs("div",{className:"text-center",children:[y.jsx(BP,{size:48,className:"mx-auto mb-3 text-zinc-800"}),y.jsx("p",{className:"font-mono text-[11px] text-zinc-700",children:"Select a page to view"})]})})})]})}function qne({children:t}){const{session:e,supabase:r,loading:n}=tp();return n?y.jsx("div",{className:"min-h-screen flex items-center justify-center text-[var(--color-muted-foreground)]",children:"Loading..."}):r?e?y.jsx(y.Fragment,{children:t}):y.jsx(gq,{}):y.jsx(y.Fragment,{children:t})}function Fne(){const{pathname:t}=ti(),e=t==="/"||t==="/chat"||t.startsWith("/chat/");return y.jsxs(y.Fragment,{children:[y.jsx(fD,{children:y.jsxs(nn,{element:y.jsx(KU,{}),children:[y.jsx(nn,{index:!0,element:y.jsx(VU,{})}),y.jsx(nn,{path:"squads",element:y.jsx(Cg,{})}),y.jsx(nn,{path:"squads/:name",element:y.jsx(Cg,{})}),y.jsx(nn,{path:"squads/:name/instances/:instanceId",element:y.jsx(Cg,{})}),y.jsx(nn,{path:"feed",element:y.jsx(mq,{})}),y.jsx(nn,{path:"skills",element:y.jsx(Aq,{})}),y.jsx(nn,{path:"schedules",element:y.jsx(bq,{})}),y.jsx(nn,{path:"wiki",element:y.jsx(Une,{})}),y.jsx(nn,{path:"settings",element:y.jsx(Sq,{})}),y.jsx(nn,{path:"usage",element:y.jsx(Dne,{})}),y.jsx(nn,{path:"*",element:y.jsx(cD,{to:"/",replace:!0})})]})}),!e&&y.jsx(Xz,{})]})}function Hne(){return y.jsx(HU,{children:y.jsx(qne,{children:y.jsx(Y4,{children:y.jsx(sz,{children:y.jsx(Fne,{})})})})})}cL.createRoot(document.getElementById("root")).render(y.jsx(R.StrictMode,{children:y.jsxs(MD,{children:[y.jsx(Hne,{}),y.jsx(b5,{theme:"dark",position:"bottom-right"})]})}));
505
- //# sourceMappingURL=index-CecuFaTR.js.map
505
+ //# sourceMappingURL=index-DJ_U2HHr.js.map