var Ds=r=>{throw TypeError(r)};var Gt=(r,e,t)=>e.has(r)||Ds("Cannot "+t);var h=(r,e,t)=>(Gt(r,e,"read from private field"),t?t.call(r):e.get(r)),b=(r,e,t)=>e.has(r)?Ds("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),_=(r,e,t,s)=>(Gt(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t),E=(r,e,t)=>(Gt(r,e,"access private method"),t);var At=(r,e,t,s)=>({set _(i){_(r,e,i,t)},get _(){return h(r,e,s)}});import{r as M,g as oi,c as Y}from"./react-vendor-Dai7d0mP.js";var mr={exports:{}},Nt={};/** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var ai=M,li=Symbol.for("react.element"),ui=Symbol.for("react.fragment"),ci=Object.prototype.hasOwnProperty,hi=ai.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,di={key:!0,ref:!0,__self:!0,__source:!0};function br(r,e,t){var s,i={},n=null,o=null;t!==void 0&&(n=""+t),e.key!==void 0&&(n=""+e.key),e.ref!==void 0&&(o=e.ref);for(s in e)ci.call(e,s)&&!di.hasOwnProperty(s)&&(i[s]=e[s]);if(r&&r.defaultProps)for(s in e=r.defaultProps,e)i[s]===void 0&&(i[s]=e[s]);return{$$typeof:li,type:r,key:n,ref:o,props:i,_owner:hi.current}}Nt.Fragment=ui;Nt.jsx=br;Nt.jsxs=br;mr.exports=Nt;var fi=mr.exports;const pi="modulepreload",gi=function(r){return"/"+r},Ls={},Tt=function(e,t,s){let i=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");i=Promise.allSettled(t.map(l=>{if(l=gi(l),l in Ls)return;Ls[l]=!0;const u=l.endsWith(".css"),c=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${c}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":pi,u||(d.as="script"),d.crossOrigin="",d.href=l,a&&d.setAttribute("nonce",a),document.head.appendChild(d),u)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${l}`)))})}))}function n(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})};var ct=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(r){return this.listeners.add(r),this.onSubscribe(),()=>{this.listeners.delete(r),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},qe=typeof window>"u"||"Deno"in globalThis;function W(){}function vi(r,e){return typeof r=="function"?r(e):r}function rs(r){return typeof r=="number"&&r>=0&&r!==1/0}function Sr(r,e){return Math.max(r+(e||0)-Date.now(),0)}function Oe(r,e){return typeof r=="function"?r(e):r}function V(r,e){return typeof r=="function"?r(e):r}function Fs(r,e){const{type:t="all",exact:s,fetchStatus:i,predicate:n,queryKey:o,stale:a}=r;if(o){if(s){if(e.queryHash!==Ps(o,e.options))return!1}else if(!mt(e.queryKey,o))return!1}if(t!=="all"){const l=e.isActive();if(t==="active"&&!l||t==="inactive"&&l)return!1}return!(typeof a=="boolean"&&e.isStale()!==a||i&&i!==e.state.fetchStatus||n&&!n(e))}function Ms(r,e){const{exact:t,status:s,predicate:i,mutationKey:n}=r;if(n){if(!e.options.mutationKey)return!1;if(t){if(Ne(e.options.mutationKey)!==Ne(n))return!1}else if(!mt(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}function Ps(r,e){return(e?.queryKeyHashFn||Ne)(r)}function Ne(r){return JSON.stringify(r,(e,t)=>is(t)?Object.keys(t).sort().reduce((s,i)=>(s[i]=t[i],s),{}):t)}function mt(r,e){return r===e?!0:typeof r!=typeof e?!1:r&&e&&typeof r=="object"&&typeof e=="object"?Object.keys(e).every(t=>mt(r[t],e[t])):!1}function kr(r,e){if(r===e)return r;const t=qs(r)&&qs(e);if(t||is(r)&&is(e)){const s=t?r:Object.keys(r),i=s.length,n=t?e:Object.keys(e),o=n.length,a=t?[]:{},l=new Set(s);let u=0;for(let c=0;c{setTimeout(e,r)})}function ns(r,e,t){return typeof t.structuralSharing=="function"?t.structuralSharing(r,e):t.structuralSharing!==!1?kr(r,e):e}function wi(r,e,t=0){const s=[...r,e];return t&&s.length>t?s.slice(1):s}function _i(r,e,t=0){const s=[e,...r];return t&&s.length>t?s.slice(0,-1):s}var Cs=Symbol();function Er(r,e){return!r.queryFn&&e?.initialPromise?()=>e.initialPromise:!r.queryFn||r.queryFn===Cs?()=>Promise.reject(new Error(`Missing queryFn: '${r.queryHash}'`)):r.queryFn}function Or(r,e){return typeof r=="function"?r(...e):!!r}var Ae,ge,Ye,cr,mi=(cr=class extends ct{constructor(){super();b(this,Ae);b(this,ge);b(this,Ye);_(this,Ye,e=>{if(!qe&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}})}onSubscribe(){h(this,ge)||this.setEventListener(h(this,Ye))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,ge))==null||e.call(this),_(this,ge,void 0))}setEventListener(e){var t;_(this,Ye,e),(t=h(this,ge))==null||t.call(this),_(this,ge,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){h(this,Ae)!==e&&(_(this,Ae,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof h(this,Ae)=="boolean"?h(this,Ae):globalThis.document?.visibilityState!=="hidden"}},Ae=new WeakMap,ge=new WeakMap,Ye=new WeakMap,cr),js=new mi,Xe,ve,Ze,hr,bi=(hr=class extends ct{constructor(){super();b(this,Xe,!0);b(this,ve);b(this,Ze);_(this,Ze,e=>{if(!qe&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}})}onSubscribe(){h(this,ve)||this.setEventListener(h(this,Ze))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,ve))==null||e.call(this),_(this,ve,void 0))}setEventListener(e){var t;_(this,Ze,e),(t=h(this,ve))==null||t.call(this),_(this,ve,e(this.setOnline.bind(this)))}setOnline(e){h(this,Xe)!==e&&(_(this,Xe,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return h(this,Xe)}},Xe=new WeakMap,ve=new WeakMap,Ze=new WeakMap,hr),Ft=new bi;function os(){let r,e;const t=new Promise((i,n)=>{r=i,e=n});t.status="pending",t.catch(()=>{});function s(i){Object.assign(t,i),delete t.resolve,delete t.reject}return t.resolve=i=>{s({status:"fulfilled",value:i}),r(i)},t.reject=i=>{s({status:"rejected",reason:i}),e(i)},t}function Si(r){return Math.min(1e3*2**r,3e4)}function Tr(r){return(r??"online")==="online"?Ft.isOnline():!0}var Pr=class extends Error{constructor(r){super("CancelledError"),this.revert=r?.revert,this.silent=r?.silent}};function zt(r){return r instanceof Pr}function Cr(r){let e=!1,t=0,s=!1,i;const n=os(),o=v=>{s||(f(new Pr(v)),r.abort?.())},a=()=>{e=!0},l=()=>{e=!1},u=()=>js.isFocused()&&(r.networkMode==="always"||Ft.isOnline())&&r.canRun(),c=()=>Tr(r.networkMode)&&r.canRun(),d=v=>{s||(s=!0,r.onSuccess?.(v),i?.(),n.resolve(v))},f=v=>{s||(s=!0,r.onError?.(v),i?.(),n.reject(v))},p=()=>new Promise(v=>{i=g=>{(s||u())&&v(g)},r.onPause?.()}).then(()=>{i=void 0,s||r.onContinue?.()}),y=()=>{if(s)return;let v;const g=t===0?r.initialPromise:void 0;try{v=g??r.fn()}catch(S){v=Promise.reject(S)}Promise.resolve(v).then(d).catch(S=>{if(s)return;const m=r.retry??(qe?0:3),w=r.retryDelay??Si,O=typeof w=="function"?w(t,S):w,A=m===!0||typeof m=="number"&&tu()?void 0:p()).then(()=>{e?f(S):y()})})};return{promise:n,cancel:o,continue:()=>(i?.(),n),cancelRetry:a,continueRetry:l,canStart:c,start:()=>(c()?y():p().then(y),n)}}var ki=r=>setTimeout(r,0);function Ei(){let r=[],e=0,t=a=>{a()},s=a=>{a()},i=ki;const n=a=>{e?r.push(a):i(()=>{t(a)})},o=()=>{const a=r;r=[],a.length&&i(()=>{s(()=>{a.forEach(l=>{t(l)})})})};return{batch:a=>{let l;e++;try{l=a()}finally{e--,e||o()}return l},batchCalls:a=>(...l)=>{n(()=>{a(...l)})},schedule:n,setNotifyFunction:a=>{t=a},setBatchNotifyFunction:a=>{s=a},setScheduler:a=>{i=a}}}var F=Ei(),Ie,dr,jr=(dr=class{constructor(){b(this,Ie)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),rs(this.gcTime)&&_(this,Ie,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(r){this.gcTime=Math.max(this.gcTime||0,r??(qe?1/0:5*60*1e3))}clearGcTimeout(){h(this,Ie)&&(clearTimeout(h(this,Ie)),_(this,Ie,void 0))}},Ie=new WeakMap,dr),et,$e,J,xe,q,St,Ue,X,oe,fr,Oi=(fr=class extends jr{constructor(e){super();b(this,X);b(this,et);b(this,$e);b(this,J);b(this,xe);b(this,q);b(this,St);b(this,Ue);_(this,Ue,!1),_(this,St,e.defaultOptions),this.setOptions(e.options),this.observers=[],_(this,xe,e.client),_(this,J,h(this,xe).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,_(this,et,Ti(this.options)),this.state=e.state??h(this,et),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return h(this,q)?.promise}setOptions(e){this.options={...h(this,St),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&h(this,J).remove(this)}setData(e,t){const s=ns(this.state.data,e,this.options);return E(this,X,oe).call(this,{data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e,t){E(this,X,oe).call(this,{type:"setState",state:e,setStateOptions:t})}cancel(e){const t=h(this,q)?.promise;return h(this,q)?.cancel(e),t?t.then(W).catch(W):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(h(this,et))}isActive(){return this.observers.some(e=>V(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Cs||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Oe(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Sr(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),h(this,q)?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),h(this,q)?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),h(this,J).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(h(this,q)&&(h(this,Ue)?h(this,q).cancel({revert:!0}):h(this,q).cancelRetry()),this.scheduleGc()),h(this,J).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||E(this,X,oe).call(this,{type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(h(this,q))return h(this,q).continueRetry(),h(this,q).promise}if(e&&this.setOptions(e),!this.options.queryFn){const u=this.observers.find(c=>c.options.queryFn);u&&this.setOptions(u.options)}const s=new AbortController,i=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(_(this,Ue,!0),s.signal)})},n=()=>{const u=Er(this.options,t),d=(()=>{const f={client:h(this,xe),queryKey:this.queryKey,meta:this.meta};return i(f),f})();return _(this,Ue,!1),this.options.persister?this.options.persister(u,d,this):u(d)},a=(()=>{const u={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:h(this,xe),state:this.state,fetchFn:n};return i(u),u})();this.options.behavior?.onFetch(a,this),_(this,$e,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&E(this,X,oe).call(this,{type:"fetch",meta:a.fetchOptions?.meta});const l=u=>{zt(u)&&u.silent||E(this,X,oe).call(this,{type:"error",error:u}),zt(u)||(h(this,J).config.onError?.(u,this),h(this,J).config.onSettled?.(this.state.data,u,this)),this.scheduleGc()};return _(this,q,Cr({initialPromise:t?.initialPromise,fn:a.fetchFn,abort:s.abort.bind(s),onSuccess:u=>{if(u===void 0){l(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(u)}catch(c){l(c);return}h(this,J).config.onSuccess?.(u,this),h(this,J).config.onSettled?.(u,this.state.error,this),this.scheduleGc()},onError:l,onFail:(u,c)=>{E(this,X,oe).call(this,{type:"failed",failureCount:u,error:c})},onPause:()=>{E(this,X,oe).call(this,{type:"pause"})},onContinue:()=>{E(this,X,oe).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),h(this,q).start()}},et=new WeakMap,$e=new WeakMap,J=new WeakMap,xe=new WeakMap,q=new WeakMap,St=new WeakMap,Ue=new WeakMap,X=new WeakSet,oe=function(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Rr(s.data,this.options),fetchMeta:e.meta??null};case"success":return _(this,$e,void 0),{...s,data:e.data,dataUpdateCount:s.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const i=e.error;return zt(i)&&i.revert&&h(this,$e)?{...h(this,$e),fetchStatus:"idle"}:{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error"};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),F.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),h(this,J).notify({query:this,type:"updated",action:e})})},fr);function Rr(r,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Tr(e.networkMode)?"fetching":"paused",...r===void 0&&{error:null,status:"pending"}}}function Ti(r){const e=typeof r.initialData=="function"?r.initialData():r.initialData,t=e!==void 0,s=t?typeof r.initialDataUpdatedAt=="function"?r.initialDataUpdatedAt():r.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:t?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:t?"success":"pending",fetchStatus:"idle"}}var re,pr,Pi=(pr=class extends ct{constructor(e={}){super();b(this,re);this.config=e,_(this,re,new Map)}build(e,t,s){const i=t.queryKey,n=t.queryHash??Ps(i,t);let o=this.get(n);return o||(o=new Oi({client:e,queryKey:i,queryHash:n,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(i)}),this.add(o)),o}add(e){h(this,re).has(e.queryHash)||(h(this,re).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=h(this,re).get(e.queryHash);t&&(e.destroy(),t===e&&h(this,re).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){F.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return h(this,re).get(e)}getAll(){return[...h(this,re).values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Fs(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Fs(e,s)):t}notify(e){F.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){F.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){F.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},re=new WeakMap,pr),ie,N,De,ne,de,gr,Ci=(gr=class extends jr{constructor(e){super();b(this,ne);b(this,ie);b(this,N);b(this,De);this.mutationId=e.mutationId,_(this,N,e.mutationCache),_(this,ie,[]),this.state=e.state||Ar(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){h(this,ie).includes(e)||(h(this,ie).push(e),this.clearGcTimeout(),h(this,N).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){_(this,ie,h(this,ie).filter(t=>t!==e)),this.scheduleGc(),h(this,N).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){h(this,ie).length||(this.state.status==="pending"?this.scheduleGc():h(this,N).remove(this))}continue(){return h(this,De)?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{E(this,ne,de).call(this,{type:"continue"})};_(this,De,Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(n,o)=>{E(this,ne,de).call(this,{type:"failed",failureCount:n,error:o})},onPause:()=>{E(this,ne,de).call(this,{type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>h(this,N).canRun(this)}));const s=this.state.status==="pending",i=!h(this,De).canStart();try{if(s)t();else{E(this,ne,de).call(this,{type:"pending",variables:e,isPaused:i}),await h(this,N).config.onMutate?.(e,this);const o=await this.options.onMutate?.(e);o!==this.state.context&&E(this,ne,de).call(this,{type:"pending",context:o,variables:e,isPaused:i})}const n=await h(this,De).start();return await h(this,N).config.onSuccess?.(n,e,this.state.context,this),await this.options.onSuccess?.(n,e,this.state.context),await h(this,N).config.onSettled?.(n,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(n,null,e,this.state.context),E(this,ne,de).call(this,{type:"success",data:n}),n}catch(n){try{throw await h(this,N).config.onError?.(n,e,this.state.context,this),await this.options.onError?.(n,e,this.state.context),await h(this,N).config.onSettled?.(void 0,n,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,n,e,this.state.context),n}finally{E(this,ne,de).call(this,{type:"error",error:n})}}finally{h(this,N).runNext(this)}}},ie=new WeakMap,N=new WeakMap,De=new WeakMap,ne=new WeakSet,de=function(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),F.batch(()=>{h(this,ie).forEach(s=>{s.onMutationUpdate(e)}),h(this,N).notify({mutation:this,type:"updated",action:e})})},gr);function Ar(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var le,Z,kt,vr,ji=(vr=class extends ct{constructor(e={}){super();b(this,le);b(this,Z);b(this,kt);this.config=e,_(this,le,new Set),_(this,Z,new Map),_(this,kt,0)}build(e,t,s){const i=new Ci({mutationCache:this,mutationId:++At(this,kt)._,options:e.defaultMutationOptions(t),state:s});return this.add(i),i}add(e){h(this,le).add(e);const t=It(e);if(typeof t=="string"){const s=h(this,Z).get(t);s?s.push(e):h(this,Z).set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(h(this,le).delete(e)){const t=It(e);if(typeof t=="string"){const s=h(this,Z).get(t);if(s)if(s.length>1){const i=s.indexOf(e);i!==-1&&s.splice(i,1)}else s[0]===e&&h(this,Z).delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=It(e);if(typeof t=="string"){const i=h(this,Z).get(t)?.find(n=>n.state.status==="pending");return!i||i===e}else return!0}runNext(e){const t=It(e);return typeof t=="string"?h(this,Z).get(t)?.find(i=>i!==e&&i.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){F.batch(()=>{h(this,le).forEach(e=>{this.notify({type:"removed",mutation:e})}),h(this,le).clear(),h(this,Z).clear()})}getAll(){return Array.from(h(this,le))}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Ms(t,s))}findAll(e={}){return this.getAll().filter(t=>Ms(e,t))}notify(e){F.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return F.batch(()=>Promise.all(e.map(t=>t.continue().catch(W))))}},le=new WeakMap,Z=new WeakMap,kt=new WeakMap,vr);function It(r){return r.options.scope?.id}function Bs(r){return{onFetch:(e,t)=>{const s=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],o=e.state.data?.pageParams||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let c=!1;const d=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(e.signal.aborted?c=!0:e.signal.addEventListener("abort",()=>{c=!0}),e.signal)})},f=Er(e.options,e.fetchOptions),p=async(y,v,g)=>{if(c)return Promise.reject();if(v==null&&y.pages.length)return Promise.resolve(y);const m=(()=>{const C={client:e.client,queryKey:e.queryKey,pageParam:v,direction:g?"backward":"forward",meta:e.options.meta};return d(C),C})(),w=await f(m),{maxPages:O}=e.options,A=g?_i:wi;return{pages:A(y.pages,w,O),pageParams:A(y.pageParams,v,O)}};if(i&&n.length){const y=i==="backward",v=y?Ri:Ws,g={pages:n,pageParams:o},S=v(s,g);a=await p(g,S,y)}else{const y=r??n.length;do{const v=l===0?o[0]??s.initialPageParam:Ws(s,a);if(l>0&&v==null)break;a=await p(a,v),l++}while(le.options.persister?.(u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},t):e.fetchFn=u}}}function Ws(r,{pages:e,pageParams:t}){const s=e.length-1;return e.length>0?r.getNextPageParam(e[s],e,t[s],t):void 0}function Ri(r,{pages:e,pageParams:t}){return e.length>0?r.getPreviousPageParam?.(e[0],e,t[0],t):void 0}var $,ye,we,tt,st,_e,rt,it,yr,pa=(yr=class{constructor(r={}){b(this,$);b(this,ye);b(this,we);b(this,tt);b(this,st);b(this,_e);b(this,rt);b(this,it);_(this,$,r.queryCache||new Pi),_(this,ye,r.mutationCache||new ji),_(this,we,r.defaultOptions||{}),_(this,tt,new Map),_(this,st,new Map),_(this,_e,0)}mount(){At(this,_e)._++,h(this,_e)===1&&(_(this,rt,js.subscribe(async r=>{r&&(await this.resumePausedMutations(),h(this,$).onFocus())})),_(this,it,Ft.subscribe(async r=>{r&&(await this.resumePausedMutations(),h(this,$).onOnline())})))}unmount(){var r,e;At(this,_e)._--,h(this,_e)===0&&((r=h(this,rt))==null||r.call(this),_(this,rt,void 0),(e=h(this,it))==null||e.call(this),_(this,it,void 0))}isFetching(r){return h(this,$).findAll({...r,fetchStatus:"fetching"}).length}isMutating(r){return h(this,ye).findAll({...r,status:"pending"}).length}getQueryData(r){const e=this.defaultQueryOptions({queryKey:r});return h(this,$).get(e.queryHash)?.state.data}ensureQueryData(r){const e=this.defaultQueryOptions(r),t=h(this,$).build(this,e),s=t.state.data;return s===void 0?this.fetchQuery(r):(r.revalidateIfStale&&t.isStaleByTime(Oe(e.staleTime,t))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(r){return h(this,$).findAll(r).map(({queryKey:e,state:t})=>{const s=t.data;return[e,s]})}setQueryData(r,e,t){const s=this.defaultQueryOptions({queryKey:r}),n=h(this,$).get(s.queryHash)?.state.data,o=vi(e,n);if(o!==void 0)return h(this,$).build(this,s).setData(o,{...t,manual:!0})}setQueriesData(r,e,t){return F.batch(()=>h(this,$).findAll(r).map(({queryKey:s})=>[s,this.setQueryData(s,e,t)]))}getQueryState(r){const e=this.defaultQueryOptions({queryKey:r});return h(this,$).get(e.queryHash)?.state}removeQueries(r){const e=h(this,$);F.batch(()=>{e.findAll(r).forEach(t=>{e.remove(t)})})}resetQueries(r,e){const t=h(this,$);return F.batch(()=>(t.findAll(r).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...r},e)))}cancelQueries(r,e={}){const t={revert:!0,...e},s=F.batch(()=>h(this,$).findAll(r).map(i=>i.cancel(t)));return Promise.all(s).then(W).catch(W)}invalidateQueries(r,e={}){return F.batch(()=>(h(this,$).findAll(r).forEach(t=>{t.invalidate()}),r?.refetchType==="none"?Promise.resolve():this.refetchQueries({...r,type:r?.refetchType??r?.type??"active"},e)))}refetchQueries(r,e={}){const t={...e,cancelRefetch:e.cancelRefetch??!0},s=F.batch(()=>h(this,$).findAll(r).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,t);return t.throwOnError||(n=n.catch(W)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(W)}fetchQuery(r){const e=this.defaultQueryOptions(r);e.retry===void 0&&(e.retry=!1);const t=h(this,$).build(this,e);return t.isStaleByTime(Oe(e.staleTime,t))?t.fetch(e):Promise.resolve(t.state.data)}prefetchQuery(r){return this.fetchQuery(r).then(W).catch(W)}fetchInfiniteQuery(r){return r.behavior=Bs(r.pages),this.fetchQuery(r)}prefetchInfiniteQuery(r){return this.fetchInfiniteQuery(r).then(W).catch(W)}ensureInfiniteQueryData(r){return r.behavior=Bs(r.pages),this.ensureQueryData(r)}resumePausedMutations(){return Ft.isOnline()?h(this,ye).resumePausedMutations():Promise.resolve()}getQueryCache(){return h(this,$)}getMutationCache(){return h(this,ye)}getDefaultOptions(){return h(this,we)}setDefaultOptions(r){_(this,we,r)}setQueryDefaults(r,e){h(this,tt).set(Ne(r),{queryKey:r,defaultOptions:e})}getQueryDefaults(r){const e=[...h(this,tt).values()],t={};return e.forEach(s=>{mt(r,s.queryKey)&&Object.assign(t,s.defaultOptions)}),t}setMutationDefaults(r,e){h(this,st).set(Ne(r),{mutationKey:r,defaultOptions:e})}getMutationDefaults(r){const e=[...h(this,st).values()],t={};return e.forEach(s=>{mt(r,s.mutationKey)&&Object.assign(t,s.defaultOptions)}),t}defaultQueryOptions(r){if(r._defaulted)return r;const e={...h(this,we).queries,...this.getQueryDefaults(r.queryKey),...r,_defaulted:!0};return e.queryHash||(e.queryHash=Ps(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===Cs&&(e.enabled=!1),e}defaultMutationOptions(r){return r?._defaulted?r:{...h(this,we).mutations,...r?.mutationKey&&this.getMutationDefaults(r.mutationKey),...r,_defaulted:!0}}clear(){h(this,$).clear(),h(this,ye).clear()}},$=new WeakMap,ye=new WeakMap,we=new WeakMap,tt=new WeakMap,st=new WeakMap,_e=new WeakMap,rt=new WeakMap,it=new WeakMap,yr),H,P,Et,B,Le,nt,me,be,Ot,ot,at,Fe,Me,Se,lt,j,gt,as,ls,us,cs,hs,ds,fs,Ir,wr,Ai=(wr=class extends ct{constructor(e,t){super();b(this,j);b(this,H);b(this,P);b(this,Et);b(this,B);b(this,Le);b(this,nt);b(this,me);b(this,be);b(this,Ot);b(this,ot);b(this,at);b(this,Fe);b(this,Me);b(this,Se);b(this,lt,new Set);this.options=t,_(this,H,e),_(this,be,null),_(this,me,os()),this.options.experimental_prefetchInRender||h(this,me).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(h(this,P).addObserver(this),Ks(h(this,P),this.options)?E(this,j,gt).call(this):this.updateResult(),E(this,j,cs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ps(h(this,P),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ps(h(this,P),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,E(this,j,hs).call(this),E(this,j,ds).call(this),h(this,P).removeObserver(this)}setOptions(e){const t=this.options,s=h(this,P);if(this.options=h(this,H).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof V(this.options.enabled,h(this,P))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");E(this,j,fs).call(this),h(this,P).setOptions(this.options),t._defaulted&&!Lt(this.options,t)&&h(this,H).getQueryCache().notify({type:"observerOptionsUpdated",query:h(this,P),observer:this});const i=this.hasListeners();i&&Hs(h(this,P),s,this.options,t)&&E(this,j,gt).call(this),this.updateResult(),i&&(h(this,P)!==s||V(this.options.enabled,h(this,P))!==V(t.enabled,h(this,P))||Oe(this.options.staleTime,h(this,P))!==Oe(t.staleTime,h(this,P)))&&E(this,j,as).call(this);const n=E(this,j,ls).call(this);i&&(h(this,P)!==s||V(this.options.enabled,h(this,P))!==V(t.enabled,h(this,P))||n!==h(this,Se))&&E(this,j,us).call(this,n)}getOptimisticResult(e){const t=h(this,H).getQueryCache().build(h(this,H),e),s=this.createResult(t,e);return $i(this,s)&&(_(this,B,s),_(this,nt,this.options),_(this,Le,h(this,P).state)),s}getCurrentResult(){return h(this,B)}trackResult(e,t){return new Proxy(e,{get:(s,i)=>(this.trackProp(i),t?.(i),Reflect.get(s,i))})}trackProp(e){h(this,lt).add(e)}getCurrentQuery(){return h(this,P)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=h(this,H).defaultQueryOptions(e),s=h(this,H).getQueryCache().build(h(this,H),t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return E(this,j,gt).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),h(this,B)))}createResult(e,t){const s=h(this,P),i=this.options,n=h(this,B),o=h(this,Le),a=h(this,nt),u=e!==s?e.state:h(this,Et),{state:c}=e;let d={...c},f=!1,p;if(t._optimisticResults){const I=this.hasListeners(),jt=!I&&Ks(e,t),We=I&&Hs(e,s,t,i);(jt||We)&&(d={...d,...Rr(c.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:y,errorUpdatedAt:v,status:g}=d;p=d.data;let S=!1;if(t.placeholderData!==void 0&&p===void 0&&g==="pending"){let I;n?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(I=n.data,S=!0):I=typeof t.placeholderData=="function"?t.placeholderData(h(this,at)?.state.data,h(this,at)):t.placeholderData,I!==void 0&&(g="success",p=ns(n?.data,I,t),f=!0)}if(t.select&&p!==void 0&&!S)if(n&&p===o?.data&&t.select===h(this,Ot))p=h(this,ot);else try{_(this,Ot,t.select),p=t.select(p),p=ns(n?.data,p,t),_(this,ot,p),_(this,be,null)}catch(I){_(this,be,I)}h(this,be)&&(y=h(this,be),p=h(this,ot),v=Date.now(),g="error");const m=d.fetchStatus==="fetching",w=g==="pending",O=g==="error",A=w&&m,C=p!==void 0,D={status:g,fetchStatus:d.fetchStatus,isPending:w,isSuccess:g==="success",isError:O,isInitialLoading:A,isLoading:A,data:p,dataUpdatedAt:d.dataUpdatedAt,error:y,errorUpdatedAt:v,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:d.dataUpdateCount>0||d.errorUpdateCount>0,isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:m,isRefetching:m&&!w,isLoadingError:O&&!C,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:O&&C,isStale:Rs(e,t),refetch:this.refetch,promise:h(this,me),isEnabled:V(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const I=Rt=>{D.status==="error"?Rt.reject(D.error):D.data!==void 0&&Rt.resolve(D.data)},jt=()=>{const Rt=_(this,me,D.promise=os());I(Rt)},We=h(this,me);switch(We.status){case"pending":e.queryHash===s.queryHash&&I(We);break;case"fulfilled":(D.status==="error"||D.data!==We.value)&&jt();break;case"rejected":(D.status!=="error"||D.error!==We.reason)&&jt();break}}return D}updateResult(){const e=h(this,B),t=this.createResult(h(this,P),this.options);if(_(this,Le,h(this,P).state),_(this,nt,this.options),h(this,Le).data!==void 0&&_(this,at,h(this,P)),Lt(t,e))return;_(this,B,t);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,n=typeof i=="function"?i():i;if(n==="all"||!n&&!h(this,lt).size)return!0;const o=new Set(n??h(this,lt));return this.options.throwOnError&&o.add("error"),Object.keys(h(this,B)).some(a=>{const l=a;return h(this,B)[l]!==e[l]&&o.has(l)})};E(this,j,Ir).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&E(this,j,cs).call(this)}},H=new WeakMap,P=new WeakMap,Et=new WeakMap,B=new WeakMap,Le=new WeakMap,nt=new WeakMap,me=new WeakMap,be=new WeakMap,Ot=new WeakMap,ot=new WeakMap,at=new WeakMap,Fe=new WeakMap,Me=new WeakMap,Se=new WeakMap,lt=new WeakMap,j=new WeakSet,gt=function(e){E(this,j,fs).call(this);let t=h(this,P).fetch(this.options,e);return e?.throwOnError||(t=t.catch(W)),t},as=function(){E(this,j,hs).call(this);const e=Oe(this.options.staleTime,h(this,P));if(qe||h(this,B).isStale||!rs(e))return;const s=Sr(h(this,B).dataUpdatedAt,e)+1;_(this,Fe,setTimeout(()=>{h(this,B).isStale||this.updateResult()},s))},ls=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(h(this,P)):this.options.refetchInterval)??!1},us=function(e){E(this,j,ds).call(this),_(this,Se,e),!(qe||V(this.options.enabled,h(this,P))===!1||!rs(h(this,Se))||h(this,Se)===0)&&_(this,Me,setInterval(()=>{(this.options.refetchIntervalInBackground||js.isFocused())&&E(this,j,gt).call(this)},h(this,Se)))},cs=function(){E(this,j,as).call(this),E(this,j,us).call(this,E(this,j,ls).call(this))},hs=function(){h(this,Fe)&&(clearTimeout(h(this,Fe)),_(this,Fe,void 0))},ds=function(){h(this,Me)&&(clearInterval(h(this,Me)),_(this,Me,void 0))},fs=function(){const e=h(this,H).getQueryCache().build(h(this,H),this.options);if(e===h(this,P))return;const t=h(this,P);_(this,P,e),_(this,Et,e.state),this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))},Ir=function(e){F.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(h(this,B))}),h(this,H).getQueryCache().notify({query:h(this,P),type:"observerResultsUpdated"})})},wr);function Ii(r,e){return V(e.enabled,r)!==!1&&r.state.data===void 0&&!(r.state.status==="error"&&e.retryOnMount===!1)}function Ks(r,e){return Ii(r,e)||r.state.data!==void 0&&ps(r,e,e.refetchOnMount)}function ps(r,e,t){if(V(e.enabled,r)!==!1&&Oe(e.staleTime,r)!=="static"){const s=typeof t=="function"?t(r):t;return s==="always"||s!==!1&&Rs(r,e)}return!1}function Hs(r,e,t,s){return(r!==e||V(s.enabled,r)===!1)&&(!t.suspense||r.state.status!=="error")&&Rs(r,t)}function Rs(r,e){return V(e.enabled,r)!==!1&&r.isStaleByTime(Oe(e.staleTime,r))}function $i(r,e){return!Lt(r.getCurrentResult(),e)}var ke,Ee,Q,ue,ce,Dt,gs,_r,xi=(_r=class extends ct{constructor(e,t){super();b(this,ce);b(this,ke);b(this,Ee);b(this,Q);b(this,ue);_(this,ke,e),this.setOptions(t),this.bindMethods(),E(this,ce,Dt).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=h(this,ke).defaultMutationOptions(e),Lt(this.options,t)||h(this,ke).getMutationCache().notify({type:"observerOptionsUpdated",mutation:h(this,Q),observer:this}),t?.mutationKey&&this.options.mutationKey&&Ne(t.mutationKey)!==Ne(this.options.mutationKey)?this.reset():h(this,Q)?.state.status==="pending"&&h(this,Q).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||h(this,Q)?.removeObserver(this)}onMutationUpdate(e){E(this,ce,Dt).call(this),E(this,ce,gs).call(this,e)}getCurrentResult(){return h(this,Ee)}reset(){h(this,Q)?.removeObserver(this),_(this,Q,void 0),E(this,ce,Dt).call(this),E(this,ce,gs).call(this)}mutate(e,t){return _(this,ue,t),h(this,Q)?.removeObserver(this),_(this,Q,h(this,ke).getMutationCache().build(h(this,ke),this.options)),h(this,Q).addObserver(this),h(this,Q).execute(e)}},ke=new WeakMap,Ee=new WeakMap,Q=new WeakMap,ue=new WeakMap,ce=new WeakSet,Dt=function(){const e=h(this,Q)?.state??Ar();_(this,Ee,{...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset})},gs=function(e){F.batch(()=>{if(h(this,ue)&&this.hasListeners()){const t=h(this,Ee).variables,s=h(this,Ee).context;e?.type==="success"?(h(this,ue).onSuccess?.(e.data,t,s),h(this,ue).onSettled?.(e.data,null,t,s)):e?.type==="error"&&(h(this,ue).onError?.(e.error,t,s),h(this,ue).onSettled?.(void 0,e.error,t,s))}this.listeners.forEach(t=>{t(h(this,Ee))})})},_r),$r=M.createContext(void 0),xr=r=>{const e=M.useContext($r);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},ga=({client:r,children:e})=>(M.useEffect(()=>(r.mount(),()=>{r.unmount()}),[r]),fi.jsx($r.Provider,{value:r,children:e})),Ur=M.createContext(!1),Ui=()=>M.useContext(Ur);Ur.Provider;function Di(){let r=!1;return{clearReset:()=>{r=!1},reset:()=>{r=!0},isReset:()=>r}}var Li=M.createContext(Di()),Fi=()=>M.useContext(Li),Mi=(r,e)=>{(r.suspense||r.throwOnError||r.experimental_prefetchInRender)&&(e.isReset()||(r.retryOnMount=!1))},qi=r=>{M.useEffect(()=>{r.clearReset()},[r])},Ni=({result:r,errorResetBoundary:e,throwOnError:t,query:s,suspense:i})=>r.isError&&!e.isReset()&&!r.isFetching&&s&&(i&&r.data===void 0||Or(t,[r.error,s])),Bi=r=>{if(r.suspense){const e=s=>s==="static"?s:Math.max(s??1e3,1e3),t=r.staleTime;r.staleTime=typeof t=="function"?(...s)=>e(t(...s)):e(t),typeof r.gcTime=="number"&&(r.gcTime=Math.max(r.gcTime,1e3))}},Wi=(r,e)=>r.isLoading&&r.isFetching&&!e,Ki=(r,e)=>r?.suspense&&e.isPending,Qs=(r,e,t)=>e.fetchOptimistic(r).catch(()=>{t.clearReset()});function Hi(r,e,t){const s=Ui(),i=Fi(),n=xr(),o=n.defaultQueryOptions(r);n.getDefaultOptions().queries?._experimental_beforeQuery?.(o),o._optimisticResults=s?"isRestoring":"optimistic",Bi(o),Mi(o,i),qi(i);const a=!n.getQueryCache().get(o.queryHash),[l]=M.useState(()=>new e(n,o)),u=l.getOptimisticResult(o),c=!s&&r.subscribed!==!1;if(M.useSyncExternalStore(M.useCallback(d=>{const f=c?l.subscribe(F.batchCalls(d)):W;return l.updateResult(),f},[l,c]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),M.useEffect(()=>{l.setOptions(o)},[o,l]),Ki(o,u))throw Qs(o,l,i);if(Ni({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:n.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw u.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!qe&&Wi(u,s)&&(a?Qs(o,l,i):n.getQueryCache().get(o.queryHash)?.promise)?.catch(W).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function va(r,e){return Hi(r,Ai)}function ya(r,e){const t=xr(),[s]=M.useState(()=>new xi(t,r));M.useEffect(()=>{s.setOptions(r)},[s,r]);const i=M.useSyncExternalStore(M.useCallback(o=>s.subscribe(F.batchCalls(o)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),n=M.useCallback((o,a)=>{s.mutate(o,a).catch(W)},[s]);if(i.error&&Or(s.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}const Qi=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Tt(async()=>{const{default:s}=await Promise.resolve().then(()=>ht);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};class As extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class Gs extends As{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class zs extends As{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Js extends As{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var vs;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(vs||(vs={}));var Gi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};class zi{constructor(e,{headers:t={},customFetch:s,region:i=vs.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Qi(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Gi(this,void 0,void 0,function*(){try{const{headers:i,method:n,body:o,signal:a}=t;let l={},{region:u}=t;u||(u=this.region);const c=new URL(`${this.url}/${e}`);u&&u!=="any"&&(l["x-region"]=u,c.searchParams.set("forceFunctionRegion",u));let d;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",d=o):typeof o=="string"?(l["Content-Type"]="text/plain",d=o):typeof FormData<"u"&&o instanceof FormData?d=o:(l["Content-Type"]="application/json",d=JSON.stringify(o)));const f=yield this.fetch(c.toString(),{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:d,signal:a}).catch(g=>{throw g.name==="AbortError"?g:new Gs(g)}),p=f.headers.get("x-relay-error");if(p&&p==="true")throw new zs(f);if(!f.ok)throw new Js(f);let y=((s=f.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),v;return y==="application/json"?v=yield f.json():y==="application/octet-stream"?v=yield f.blob():y==="text/event-stream"?v=f:y==="multipart/form-data"?v=yield f.formData():v=yield f.text(),{data:v,error:null,response:f}}catch(i){return i instanceof Error&&i.name==="AbortError"?{data:null,error:new Gs(i)}:{data:null,error:i,response:i instanceof Js||i instanceof zs?i.context:void 0}}})}}var G={},Is={},Bt={},Pt={},Wt={},Kt={},Ji=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ut=Ji();const Vi=ut.fetch,Dr=ut.fetch.bind(ut),Lr=ut.Headers,Yi=ut.Request,Xi=ut.Response,ht=Object.freeze(Object.defineProperty({__proto__:null,Headers:Lr,Request:Yi,Response:Xi,default:Dr,fetch:Vi},Symbol.toStringTag,{value:"Module"})),Zi=oi(ht);var Ht={};Object.defineProperty(Ht,"__esModule",{value:!0});let en=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ht.default=en;var Fr=Y&&Y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Kt,"__esModule",{value:!0});const tn=Fr(Zi),sn=Fr(Ht);let rn=class{constructor(e){var t,s;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(s=e.isMaybeSingle)!==null&&s!==void 0?s:!1,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=tn.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l,u;let c=null,d=null,f=null,p=n.status,y=n.statusText;if(n.ok){if(this.method!=="HEAD"){const m=await n.text();m===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((o=this.headers.get("Accept"))===null||o===void 0)&&o.includes("application/vnd.pgrst.plan+text"))?d=m:d=JSON.parse(m))}const g=(a=this.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),S=(l=n.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");g&&S&&S.length>1&&(f=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(c={code:"PGRST116",details:`Results contain ${d.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},d=null,f=null,p=406,y="Not Acceptable"):d.length===1?d=d[0]:d=null)}else{const g=await n.text();try{c=JSON.parse(g),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,y="OK")}catch{n.status===404&&g===""?(p=204,y="No Content"):c={message:g}}if(c&&this.isMaybeSingle&&(!((u=c?.details)===null||u===void 0)&&u.includes("0 rows"))&&(c=null,p=200,y="OK"),c&&this.shouldThrowOnError)throw new sn.default(c)}return{error:c,data:d,count:f,status:p,statusText:y}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}returns(){return this}overrideTypes(){return this}};Kt.default=rn;var nn=Y&&Y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Wt,"__esModule",{value:!0});const on=nn(Kt);let an=class extends on.default{select(e){let t=!1;const s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:i,referencedTable:n=i}={}){const o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){const n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;const l=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${u}"; options=${l};`),o==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};Wt.default=an;var ln=Y&&Y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Pt,"__esModule",{value:!0});const un=ln(Wt);let cn=class extends un.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");const o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){const i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};Pt.default=cn;var hn=Y&&Y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Bt,"__esModule",{value:!0});const ft=hn(Pt);let dn=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=new Headers(t),this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){const i=t?"HEAD":"GET";let n=!1;const o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&this.headers.append("Prefer",`count=${s}`),new ft.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:s=!0}={}){var i;const n="POST";if(t&&this.headers.append("Prefer",`count=${t}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){const a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new ft.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){var o;const a="POST";if(this.headers.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&this.url.searchParams.set("on_conflict",t),i&&this.headers.append("Prefer",`count=${i}`),n||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(l.length>0){const u=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new ft.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}update(e,{count:t}={}){var s;const i="PATCH";return t&&this.headers.append("Prefer",`count=${t}`),new ft.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}delete({count:e}={}){var t;const s="DELETE";return e&&this.headers.append("Prefer",`count=${e}`),new ft.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch})}};Bt.default=dn;var Mr=Y&&Y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Is,"__esModule",{value:!0});const fn=Mr(Bt),pn=Mr(Pt);let gn=class qr{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.fetch=i}from(e){const t=new URL(`${this.url}/${e}`);return new fn.default(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new qr(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){var o;let a;const l=new URL(`${this.url}/rpc/${e}`);let u;s||i?(a=s?"HEAD":"GET",Object.entries(t).filter(([d,f])=>f!==void 0).map(([d,f])=>[d,Array.isArray(f)?`{${f.join(",")}}`:`${f}`]).forEach(([d,f])=>{l.searchParams.append(d,f)})):(a="POST",u=t);const c=new Headers(this.headers);return n&&c.set("Prefer",`count=${n}`),new pn.default({method:a,url:l,headers:c,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}};Is.default=gn;var dt=Y&&Y.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(G,"__esModule",{value:!0});G.PostgrestError=G.PostgrestBuilder=G.PostgrestTransformBuilder=G.PostgrestFilterBuilder=G.PostgrestQueryBuilder=G.PostgrestClient=void 0;const Nr=dt(Is);G.PostgrestClient=Nr.default;const Br=dt(Bt);G.PostgrestQueryBuilder=Br.default;const Wr=dt(Pt);G.PostgrestFilterBuilder=Wr.default;const Kr=dt(Wt);G.PostgrestTransformBuilder=Kr.default;const Hr=dt(Kt);G.PostgrestBuilder=Hr.default;const Qr=dt(Ht);G.PostgrestError=Qr.default;var vn=G.default={PostgrestClient:Nr.default,PostgrestQueryBuilder:Br.default,PostgrestFilterBuilder:Wr.default,PostgrestTransformBuilder:Kr.default,PostgrestBuilder:Hr.default,PostgrestError:Qr.default};const{PostgrestClient:yn,PostgrestQueryBuilder:ka,PostgrestFilterBuilder:Ea,PostgrestTransformBuilder:Oa,PostgrestBuilder:Ta,PostgrestError:Pa}=vn;class wn{static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"){const t=process.versions;if(t&&t.node){const s=t.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=` Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const s=this.getWebSocketConstructor();return new s(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const _n="2.15.5",mn=`realtime-js/${_n}`,bn="1.0.0",ys=1e4,Sn=1e3,kn=100;var yt;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(yt||(yt={}));var L;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(L||(L={}));var ee;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(ee||(ee={}));var ws;(function(r){r.websocket="websocket"})(ws||(ws={}));var Re;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(Re||(Re={}));class En{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const i=t.getUint8(1),n=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=s.decode(e.slice(o,o+i));o=o+i;const l=s.decode(e.slice(o,o+n));o=o+n;const u=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:u}}}class Gr{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var R;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(R||(R={}));const Vs=(r,e,t={})=>{var s;const i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=On(o,r,e,i),n),{})},On=(r,e,t,s)=>{const i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?zr(n,o):_s(o)},zr=(r,e)=>{if(r.charAt(0)==="_"){const t=r.slice(1,r.length);return jn(e,t)}switch(r){case R.bool:return Tn(e);case R.float4:case R.float8:case R.int2:case R.int4:case R.int8:case R.numeric:case R.oid:return Pn(e);case R.json:case R.jsonb:return Cn(e);case R.timestamp:return Rn(e);case R.abstime:case R.date:case R.daterange:case R.int4range:case R.int8range:case R.money:case R.reltime:case R.text:case R.time:case R.timestamptz:case R.timetz:case R.tsrange:case R.tstzrange:return _s(e);default:return _s(e)}},_s=r=>r,Tn=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Pn=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Cn=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},jn=(r,e)=>{if(typeof r!="string")return r;const t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n;const o=r.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>zr(e,a))}return r},Rn=r=>typeof r=="string"?r.replace(" ","T"):r,Jr=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class Jt{constructor(e,t,s={},i=ys){this.channel=e,this.event=t,this.payload=s,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Ys;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(Ys||(Ys={}));class wt{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=wt.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=wt.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=wt.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,i){const n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(u,c)=>{o[u]||(l[u]=c)}),this.map(o,(u,c)=>{const d=n[u];if(d){const f=c.map(g=>g.presence_ref),p=d.map(g=>g.presence_ref),y=c.filter(g=>p.indexOf(g.presence_ref)<0),v=d.filter(g=>f.indexOf(g.presence_ref)<0);y.length>0&&(a[u]=y),v.length>0&&(l[u]=v)}else a[u]=c}),this.syncDiff(n,{joins:a,leaves:l},s,i)}static syncDiff(e,t,s,i){const{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var u;const c=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(l),c.length>0){const d=e[a].map(p=>p.presence_ref),f=c.filter(p=>d.indexOf(p.presence_ref)<0);e[a].unshift(...f)}s(a,c,l)}),this.map(o,(a,l)=>{let u=e[a];if(!u)return;const c=l.map(d=>d.presence_ref);u=u.filter(d=>c.indexOf(d.presence_ref)<0),e[a]=u,i(a,u,l),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Xs;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(Xs||(Xs={}));var _t;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(_t||(_t={}));var ae;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(ae||(ae={}));class $s{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=L.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Jt(this,ee.join,this.params,this.timeout),this.rejoinTimer=new Gr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=L.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=L.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=L.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=L.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=L.errored,this.rejoinTimer.scheduleTimeout())}),this._on(ee.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new wt(this),this.broadcastEndpointURL=Jr(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,i,n;if(this.socket.isConnected()||this.socket.connect(),this.state==L.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,u=(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(p=>p.filter))!==null&&i!==void 0?i:[],c=!!this.bindings[_t.PRESENCE]&&this.bindings[_t.PRESENCE].length>0||((n=this.params.config.presence)===null||n===void 0?void 0:n.enabled)===!0,d={},f={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(p=>e?.(ae.CHANNEL_ERROR,p)),this._onClose(()=>e?.(ae.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:p})=>{var y;if(this.socket.setAuth(),p===void 0){e?.(ae.SUBSCRIBED);return}else{const v=this.bindings.postgres_changes,g=(y=v?.length)!==null&&y!==void 0?y:0,S=[];for(let m=0;m{this.state=L.errored,e?.(ae.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e?.(ae.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===L.joined&&e===_t.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){const{event:n,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=u.body)===null||i===void 0?void 0:i.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;const u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=L.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(ee.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(i=>{s=new Jt(this,ee.leave,{},e),s.receive("ok",()=>{t(),i("ok")}).receive("timeout",()=>{t(),i("timed out")}).receive("error",()=>{i("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=L.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const i=new AbortController,n=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Jt(this,e,t,s);return this._canPush()?i.send():this._addToPushBuffer(i),i}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>kn){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:u,join:c}=ee;if(s&&[a,l,u,c].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,t,s);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(p=>{var y,v,g;return((y=p.filter)===null||y===void 0?void 0:y.event)==="*"||((g=(v=p.filter)===null||v===void 0?void 0:v.event)===null||g===void 0?void 0:g.toLocaleLowerCase())===o}).map(p=>p.callback(f,s)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var y,v,g,S,m,w;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){const O=p.id,A=(y=p.filter)===null||y===void 0?void 0:y.event;return O&&((v=t.ids)===null||v===void 0?void 0:v.includes(O))&&(A==="*"||A?.toLocaleLowerCase()===((g=t.data)===null||g===void 0?void 0:g.type.toLocaleLowerCase()))}else{const O=(m=(S=p?.filter)===null||S===void 0?void 0:S.event)===null||m===void 0?void 0:m.toLocaleLowerCase();return O==="*"||O===((w=t?.event)===null||w===void 0?void 0:w.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){const y=f.data,{schema:v,table:g,commit_timestamp:S,type:m,errors:w}=y;f=Object.assign(Object.assign({},{schema:v,table:g,commit_timestamp:S,eventType:m,new:{},old:{},errors:w}),this._getPayloadRecords(y))}p.callback(f,s)})}_isClosed(){return this.state===L.closed}_isJoined(){return this.state===L.joined}_isJoining(){return this.state===L.joining}_isLeaving(){return this.state===L.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&$s.isEqual(i.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(ee.close,{},e)}_onError(e){this._on(ee.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=L.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Vs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Vs(e.columns,e.old_record)),t}}const Vt=()=>{},$t={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},An=[1e3,2e3,5e3,1e4],In=1e4,$n=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class xn{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=ys,this.transport=null,this.heartbeatIntervalMs=$t.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Vt,this.ref=0,this.reconnectTimer=null,this.logger=Vt,this.conn=null,this.sendBuffer=[],this.serializer=new En,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=i=>{let n;return i?n=i:typeof fetch>"u"?n=(...o)=>Tt(async()=>{const{default:a}=await Promise.resolve().then(()=>ht);return{default:a}},void 0).then(({default:a})=>a(...o)).catch(a=>{throw new Error(`Failed to load @supabase/node-fetch: ${a.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):n=fetch,(...o)=>n(...o)},!(!((s=t?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${ws.websocket}`,this.httpEndpoint=Jr(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=wn.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:bn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},e?this.conn.close(e,t??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case yt.connecting:return Re.Connecting;case yt.open:return Re.Open;case yt.closing:return Re.Closing;default:return Re.Closed}}isConnected(){return this.connectionState()===Re.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const s=`realtime:${e}`,i=this.getChannels().find(n=>n.topic===s);if(i)return i;{const n=new $s(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:s,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(Sn,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},$t.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(u){this.log("error","error in heartbeat callback",u)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:s,event:i,payload:n,ref:o}=t,a=o?`(${o})`:"",l=n.status||"";this.log("receive",`${l} ${s} ${i} ${a}`.trim(),n),this.channels.filter(u=>u._isMember(s)).forEach(u=>u._trigger(i,n,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(ee.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${i}`}_workerObjectUrl(e){let t;if(e)t=e;else{const s=new Blob([$n],{type:"application/javascript"});t=URL.createObjectURL(s)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;e?t=e:this.accessToken?t=await this.accessToken():t=this.accessTokenValue,this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(s=>{const i={access_token:t,version:mn};t&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(ee.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new Gr(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},$t.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,i,n,o,a,l,u,c;if(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e?.timeout)!==null&&s!==void 0?s:ys,this.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:$t.HEARTBEAT_INTERVAL,this.worker=(n=e?.worker)!==null&&n!==void 0?n:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:Vt,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=e?.reconnectAfterMs)!==null&&l!==void 0?l:d=>An[d-1]||In,this.encode=(u=e?.encode)!==null&&u!==void 0?u:(d,f)=>f(JSON.stringify(d)),this.decode=(c=e?.decode)!==null&&c!==void 0?c:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}}class xs extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function U(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}class Un extends xs{constructor(e,t,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class ms extends xs{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var Dn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};const Vr=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Tt(async()=>{const{default:s}=await Promise.resolve().then(()=>ht);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Ln=()=>Dn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Tt(()=>Promise.resolve().then(()=>ht),void 0)).Response:Response}),bs=r=>{if(Array.isArray(r))return r.map(t=>bs(t));if(typeof r=="function"||r!==Object(r))return r;const e={};return Object.entries(r).forEach(([t,s])=>{const i=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[i]=bs(s)}),e},Fn=r=>{if(typeof r!="object"||r===null)return!1;const e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)};var Be=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};const Yt=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Mn=(r,e,t)=>Be(void 0,void 0,void 0,function*(){const s=yield Ln();r instanceof s&&!t?.noResolveJson?r.json().then(i=>{const n=r.status||500,o=i?.statusCode||n+"";e(new Un(Yt(i),n,o))}).catch(i=>{e(new ms(Yt(i),i))}):e(new ms(Yt(r),r))}),qn=(r,e,t,s)=>{const i={method:r,headers:e?.headers||{}};return r==="GET"||!s?i:(Fn(s)?(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(s)):i.body=s,e?.duplex&&(i.duplex=e.duplex),Object.assign(Object.assign({},i),t))};function Ct(r,e,t,s,i,n){return Be(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,qn(e,s,i,n)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Mn(l,a,s))})})}function Mt(r,e,t,s){return Be(this,void 0,void 0,function*(){return Ct(r,"GET",e,t,s)})}function se(r,e,t,s,i){return Be(this,void 0,void 0,function*(){return Ct(r,"POST",e,s,i,t)})}function Ss(r,e,t,s,i){return Be(this,void 0,void 0,function*(){return Ct(r,"PUT",e,s,i,t)})}function Nn(r,e,t,s){return Be(this,void 0,void 0,function*(){return Ct(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function Yr(r,e,t,s,i){return Be(this,void 0,void 0,function*(){return Ct(r,"DELETE",e,s,i,t)})}var Bn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};class Wn{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return Bn(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(U(e))return{data:null,error:e};throw e}})}}var Kn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};class Hn{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}asStream(){return new Wn(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.execute().then(e,t)}execute(){return Kn(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(U(e))return{data:null,error:e};throw e}})}}var K=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};const Qn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Zs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Gn{constructor(e,t={},s,i){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=s,this.fetch=Vr(i)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,i){return K(this,void 0,void 0,function*(){try{let n;const o=Object.assign(Object.assign({},Zs),i);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l)),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l))):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),i?.headers&&(a=Object.assign(Object.assign({},a),i.headers));const u=this._removeEmptyFolders(t),c=this._getFinalPath(u),d=yield(e=="PUT"?Ss:se)(this.fetch,`${this.url}/object/${c}`,n,Object.assign({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{data:{path:u,id:d.Id,fullPath:d.Key},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(U(n))return{data:null,error:n};throw n}})}upload(e,t,s){return K(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return K(this,void 0,void 0,function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const u=Object.assign({upsert:Zs.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",u.cacheControl)):(l=s,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType);const d=yield Ss(this.fetch,a.toString(),l,{headers:c});return{data:{path:n,fullPath:d.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(U(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return K(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");const n=yield se(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new xs("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(U(s))return{data:null,error:s};throw s}})}update(e,t,s){return K(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return K(this,void 0,void 0,function*(){try{return{data:yield se(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(U(i))return{data:null,error:i};throw i}})}copy(e,t,s){return K(this,void 0,void 0,function*(){try{return{data:{path:(yield se(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(U(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return K(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield se(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers});const o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(U(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return K(this,void 0,void 0,function*(){try{const i=yield se(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(U(i))return{data:null,error:i};throw i}})}download(e,t){const i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"",a=this._getFinalPath(e),l=()=>Mt(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0});return new Hn(l,this.shouldThrowOnError)}info(e){return K(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield Mt(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:bs(s),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(U(s))return{data:null,error:s};throw s}})}exists(e){return K(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield Nn(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(U(s)&&s instanceof ms){const i=s.originalError;if([400,404].includes(i?.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);const a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${u}`)}}}remove(e){return K(this,void 0,void 0,function*(){try{return{data:yield Yr(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}list(e,t,s){return K(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},Qn),t),{prefix:e||""});return{data:yield se(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(U(i))return{data:null,error:i};throw i}})}listV2(e,t){return K(this,void 0,void 0,function*(){try{const s=Object.assign({},e);return{data:yield se(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(U(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const zn="2.12.2",Jn={"X-Client-Info":`storage-js/${zn}`};var Ke=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};class Vn{constructor(e,t={},s,i){this.shouldThrowOnError=!1;const n=new URL(e);i?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href,this.headers=Object.assign(Object.assign({},Jn),t),this.fetch=Vr(s)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return Ke(this,void 0,void 0,function*(){try{return{data:yield Mt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(U(e))return{data:null,error:e};throw e}})}getBucket(e){return Ke(this,void 0,void 0,function*(){try{return{data:yield Mt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Ke(this,void 0,void 0,function*(){try{return{data:yield se(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(U(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Ke(this,void 0,void 0,function*(){try{return{data:yield Ss(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(U(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Ke(this,void 0,void 0,function*(){try{return{data:yield se(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Ke(this,void 0,void 0,function*(){try{return{data:yield Yr(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}}class Yn extends Vn{constructor(e,t={},s,i){super(e,t,s,i)}from(e){return new Gn(this.url,this.headers,e,this.fetch)}}const Xn="2.58.0";let vt="";typeof Deno<"u"?vt="deno":typeof document<"u"?vt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?vt="react-native":vt="node";const Zn={"X-Client-Info":`supabase-js-${vt}/${Xn}`},eo={headers:Zn},to={schema:"public"},so={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ro={};var io=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};const no=r=>{let e;return r?e=r:typeof fetch>"u"?e=Dr:e=fetch,(...t)=>e(...t)},oo=()=>typeof Headers>"u"?Lr:Headers,ao=(r,e,t)=>{const s=no(t),i=oo();return(n,o)=>io(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:r;let u=new i(o?.headers);return u.has("apikey")||u.set("apikey",r),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),s(n,Object.assign(Object.assign({},o),{headers:u}))})};var lo=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};function uo(r){return r.endsWith("/")?r:r+"/"}function co(r,e){var t,s;const{db:i,auth:n,realtime:o,global:a}=r,{db:l,auth:u,realtime:c,global:d}=e,f={db:Object.assign(Object.assign({},l),i),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},c),o),storage:{},global:Object.assign(Object.assign(Object.assign({},d),a),{headers:Object.assign(Object.assign({},(t=d?.headers)!==null&&t!==void 0?t:{}),(s=a?.headers)!==null&&s!==void 0?s:{})}),accessToken:()=>lo(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}function ho(r){const e=r?.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(uo(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const Xr="2.72.0",Je=30*1e3,ks=3,Xt=ks*Je,fo="http://localhost:9999",po="supabase.auth.token",go={"X-Client-Info":`gotrue-js/${Xr}`},Es="X-Supabase-Api-Version",Zr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},vo=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,yo=10*60*1e3;class Us extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function k(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}class wo extends Us{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function _o(r){return k(r)&&r.name==="AuthApiError"}class ei extends Us{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Te extends Us{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}}class fe extends Te{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function mo(r){return k(r)&&r.name==="AuthSessionMissingError"}class pt extends Te{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class xt extends Te{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Ut extends Te{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function bo(r){return k(r)&&r.name==="AuthImplicitGrantRedirectError"}class er extends Te{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Os extends Te{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Zt(r){return k(r)&&r.name==="AuthRetryableFetchError"}class tr extends Te{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Ts extends Te{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const qt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),sr=` \r=`.split(""),So=(()=>{const r=new Array(128);for(let e=0;e=6;){const s=e.queue>>e.queuedBits-6&63;t(qt[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(qt[s]),e.queuedBits-=6}}function ti(r,e,t){const s=So[r];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function ir(r){const e=[],t=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=o=>{Oo(o,s,t)};for(let o=0;o>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function Eo(r,e){for(let t=0;t55295&&s<=56319){const i=(s-55296)*1024&65535;s=(r.charCodeAt(t+1)-56320&65535|i)+65536,t+=1}ko(s,e)}}function Oo(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let s=1;s<6;s+=1)if(!(r>>7-s&1)){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function To(r){const e=[],t={queue:0,queuedBits:0},s=i=>{e.push(i)};for(let i=0;ie.push(t)),new Uint8Array(e)}function Co(r){const e=[],t={queue:0,queuedBits:0},s=i=>{e.push(i)};return r.forEach(i=>rr(i,t,s)),rr(null,t,s),e.join("")}function jo(r){return Math.round(Date.now()/1e3)+r}function Ro(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){const e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}const z=()=>typeof window<"u"&&typeof document<"u",Pe={tested:!1,writable:!1},si=()=>{if(!z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Pe.tested)return Pe.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Pe.tested=!0,Pe.writable=!0}catch{Pe.tested=!0,Pe.writable=!1}return Pe.writable};function Ao(r){const e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}const ri=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Tt(async()=>{const{default:s}=await Promise.resolve().then(()=>ht);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Io=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Ve=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Ce=async(r,e)=>{const t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},he=async(r,e)=>{await r.removeItem(e)};class Qt{constructor(){this.promise=new Qt.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Qt.promiseConstructor=Promise;function es(r){const e=r.split(".");if(e.length!==3)throw new Ts("Invalid JWT structure");for(let s=0;s{setTimeout(()=>e(null),r)})}function xo(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{const o=await r(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Uo(r){return("0"+r.toString(16)).substr(-2)}function Do(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,Uo).join("")}async function Lo(r){const t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}async function Fo(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;const t=await Lo(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function He(r,e,t=!1){const s=Do();let i=s;t&&(i+="/PASSWORD_RECOVERY"),await Ve(r,`${e}-code-verifier`,i);const n=await Fo(s);return[n,s===n?"plain":"s256"]}const Mo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function qo(r){const e=r.headers.get(Es);if(!e||!e.match(Mo))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function No(r){if(!r)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function Bo(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Wo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Qe(r){if(!Wo.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ts(){const r={};return new Proxy(r,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const s=t.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function nr(r){return JSON.parse(JSON.stringify(r))}var Ko=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);ir.msg||r.message||r.error_description||r.error||JSON.stringify(r),Ho=[502,503,504];async function or(r){var e;if(!Io(r))throw new Os(je(r),0);if(Ho.includes(r.status))throw new Os(je(r),r.status);let t;try{t=await r.json()}catch(n){throw new ei(je(n),n)}let s;const i=qo(r);if(i&&i.getTime()>=Zr["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new tr(je(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new fe}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new tr(je(t),r.status,t.weak_password.reasons);throw new wo(je(t),r.status||500,s)}const Qo=(r,e,t,s)=>{const i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function T(r,e,t,s){var i;const n=Object.assign({},s?.headers);n[Es]||(n[Es]=Zr["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);const o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Go(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Go(r,e,t,s,i,n){const o=Qo(e,s,i,n);let a;try{a=await r(t,Object.assign({},o))}catch(l){throw console.error(l),new Os(je(l),0)}if(a.ok||await or(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await or(l)}}function te(r){var e;let t=null;Yo(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=jo(r.expires_in)));const s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function ar(r){const e=te(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function pe(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function zo(r){return{data:r,error:null}}function Jo(r){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Ko(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Vo(r){return r}function Yo(r){return r.access_token&&r.refresh_token&&r.expires_in}const ss=["global","local","others"];var Xo=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i0&&(p.forEach(y=>{const v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(y.split(";")[1].split("=")[1]);u[`${g}Page`]=v}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Qe(e);try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:pe})}catch(t){if(k(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Qe(e);try{return await T(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:pe})}catch(s){if(k(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){Qe(e);try{return await T(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:pe})}catch(s){if(k(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Qe(e.userId);try{const{data:t,error:s}=await T(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(k(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Qe(e.userId),Qe(e.id);try{return{data:await T(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}}}function lr(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function ea(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const Ge={debug:!!(globalThis&&si()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ii extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ta extends ii{}async function sa(r,e,t){Ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Ge.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){Ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Ge.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new ta(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Ge.debug)try{const n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}function ni(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}" is invalid.`);return r.toLowerCase()}function ra(r){return parseInt(r,16)}function ia(r){const e=new TextEncoder().encode(r);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function na(r){var e;const{chainId:t,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:o,notBefore:a,requestId:l,resources:u,scheme:c,uri:d,version:f}=r;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=r.statement)===null||e===void 0)&&e.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}const p=ni(r.address),y=c?`${c}://${s}`:s,v=r.statement?`${r.statement} `:"",g=`${y} wants you to sign in with your Ethereum account: ${p} ${v}`;let S=`URI: ${d} Version: ${f} Chain ID: ${t}${o?` Nonce: ${o}`:""} Issued At: ${n.toISOString()}`;if(i&&(S+=` Expiration Time: ${i.toISOString()}`),a&&(S+=` Not Before: ${a.toISOString()}`),l&&(S+=` Request ID: ${l}`),u){let m=` Resources:`;for(const w of u){if(!w||typeof w!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${w}`);m+=` - ${w}`}S+=m}return`${g} ${S}`}ea();const oa={url:fo,storageKey:po,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:go,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function ur(r,e,t){return await t()}const ze={};class bt{constructor(e){var t,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=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,this.instanceID=bt.nextInstanceID,bt.nextInstanceID+=1,this.instanceID>0&&z()&&console.warn("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.");const i=Object.assign(Object.assign({},oa),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Zo({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ri(i.fetch),this.lock=i.lock||ur,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:z()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=sa:this.lock=ur,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)},this.persistSession?(i.storage?this.storage=i.storage:si()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=lr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=lr(this.memoryStorage)),z()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}get jwks(){var e,t;return(t=(e=ze[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){ze[this.storageKey]=Object.assign(Object.assign({},ze[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=ze[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ze[this.storageKey]=Object.assign(Object.assign({},ze[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Xr}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const t=Ao(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),z()&&this.detectSessionInUrl&&s!=="none"){const{data:i,error:n}=await this._getSessionFromURL(t,s);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),bo(n)){const l=(e=n.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:n}}return await this._removeSession(),{error:n}}const{session:o,redirectType:a}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return k(t)?{error:t}:{error:new ei("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{const n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:te}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:u,session:l},error:null}}catch(n){if(k(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){const{email:c,password:d,options:f}=e;let p=null,y=null;this.flowType==="pkce"&&([p,y]=await He(this.storage,this.storageKey)),n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:y},xform:te})}else if("phone"in e){const{phone:c,password:d,options:f}=e;n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(i=f?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:te})}else throw new xt("You must provide either an email or phone number and a password");const{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:u,session:l},error:null}}catch(n){if(k(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ar})}else if("phone"in e){const{phone:n,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ar})}else throw new xt("You must provide either an email or phone number and a password");const{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new pt}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(k(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,s,i,n,o,a,l,u,c,d,f;let p,y;if("message"in e)p=e.message,y=e.signature;else{const{chain:v,wallet:g,statement:S,options:m}=e;let w;if(z())if(typeof g=="object")w=g;else{const I=window;if("ethereum"in I&&typeof I.ethereum=="object"&&"request"in I.ethereum&&typeof I.ethereum.request=="function")w=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 g!="object"||!m?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=g}const O=new URL((t=m?.url)!==null&&t!==void 0?t:window.location.href),A=await w.request({method:"eth_requestAccounts"}).then(I=>I).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!A||A.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const C=ni(A[0]);let x=(s=m?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!x){const I=await w.request({method:"eth_chainId"});x=ra(I)}const D={domain:O.host,address:C,statement:S,uri:O.href,version:"1",chainId:x,nonce:(i=m?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(n=m?.signInWithEthereum)===null||n===void 0?void 0:n.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=m?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=m?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=m?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=m?.signInWithEthereum)===null||c===void 0?void 0:c.resources};p=na(D),y=await w.request({method:"personal_sign",params:[ia(p),C]})}try{const{data:v,error:g}=await T(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:y},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:te});if(g)throw g;return!v||!v.session||!v.user?{data:{user:null,session:null},error:new pt}:(v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),{data:Object.assign({},v),error:g})}catch(v){if(k(v))return{data:{user:null,session:null},error:v};throw v}}async signInWithSolana(e){var t,s,i,n,o,a,l,u,c,d,f,p;let y,v;if("message"in e)y=e.message,v=e.signature;else{const{chain:g,wallet:S,statement:m,options:w}=e;let O;if(z())if(typeof S=="object")O=S;else{const C=window;if("solana"in C&&typeof C.solana=="object"&&("signIn"in C.solana&&typeof C.solana.signIn=="function"||"signMessage"in C.solana&&typeof C.solana.signMessage=="function"))O=C.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof S!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=S}const A=new URL((t=w?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in O&&O.signIn){const C=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w?.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),m?{statement:m}:null));let x;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")x=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)x=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in x&&"signature"in x&&(typeof x.signedMessage=="string"||x.signedMessage instanceof Uint8Array)&&x.signature instanceof Uint8Array)y=typeof x.signedMessage=="string"?x.signedMessage:new TextDecoder().decode(x.signedMessage),v=x.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in O)||typeof O.signMessage!="function"||!("publicKey"in O)||typeof O!="object"||!O.publicKey||!("toBase58"in O.publicKey)||typeof O.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${A.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(i=(s=w?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((n=w?.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((o=w?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((a=w?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((l=w?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((u=w?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((d=(c=w?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",...w.signInWithSolana.resources.map(x=>`- ${x}`)]:[]].join(` `);const C=await O.signMessage(new TextEncoder().encode(y),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=C}}try{const{data:g,error:S}=await T(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:Co(v)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:te});if(S)throw S;return!g||!g.session||!g.user?{data:{user:null,session:null},error:new pt}:(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),{data:Object.assign({},g),error:S})}catch(g){if(k(g))return{data:{user:null,session:null},error:g};throw g}}async _exchangeCodeForSession(e){const t=await Ce(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/");try{const{data:n,error:o}=await T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:te});if(await he(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new pt}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}catch(n){if(k(n))return{data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{const{options:t,provider:s,token:i,access_token:n,nonce:o}=e,a=await T(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:te}),{data:l,error:u}=a;return u?{data:{user:null,session:null},error:u}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new pt}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:u})}catch(t){if(k(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){const{email:a,options:l}=e;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await He(this.storage,this.storageKey));const{error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){const{phone:a,options:l}=e,{data:u,error:c}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:c}}throw new xt("You must provide either an email or phone number.")}catch(a){if(k(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:te});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,u=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:u,session:l},error:null}}catch(i){if(k(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await He(this.storage,this.storageKey)),await T(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:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:zo})}catch(n){if(k(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new fe;const{error:i}=await T(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(k(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:i,options:n}=e,{error:o}=await T(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:s,type:i,options:n}=e,{data:o,error:a}=await T(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new xt("You must provide either an email or phone number and a type")}catch(t){if(k(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await t()))();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 s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}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 t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await Ce(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,u,c))})}return{data:{session:e},error:null}}const{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:pe}):await this._useSession(async t=>{var s,i,n;const{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new fe}:await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:pe})})}catch(t){if(k(t))return mo(t)&&(await this._removeSession(),await he(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new fe;const o=i.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await He(this.storage,this.storageKey));const{data:u,error:c}=await T(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:pe});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(k(s))return{data:{user:null},error:s};throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new fe;const t=Date.now()/1e3;let s=t,i=!0,n=null;const{payload:o}=es(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){const{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(k(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new fe;const{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(k(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!z())throw new Ut("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ut(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new er("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ut("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new er("No code detected.");const{data:m,error:w}=await this._exchangeCodeForSession(e.code);if(w)throw w;const O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:m.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:u}=e;if(!n||!a||!o||!u)throw new Ut("No session defined in URL");const c=Math.round(Date.now()/1e3),d=parseInt(a);let f=c+d;l&&(f=parseInt(l));const p=f-c;p*1e3<=Je&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);const y=f-d;c-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,f,c):c-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,f,c);const{data:v,error:g}=await this._getUser(n);if(g)throw g;const S={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:o,token_type:u,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:S,redirectType:e.type},error:null}}catch(s){if(k(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await Ce(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;const{data:i,error:n}=t;if(n)return{error:n};const o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(_o(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await he(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=Ro(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{const{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){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",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await He(this.storage,this.storageKey,!0));try{return await T(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(k(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{const{data:s,error:i}=await this._useSession(async n=>{var o,a,l,u,c;const{data:d,error:f}=n;if(f)throw f;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",p,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(i)throw i;return z()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(k(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;const{data:n,error:o}=t;if(o)throw o;return await T(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(k(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await xo(async i=>(i>0&&await $o(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:te})),(i,n)=>{const o=200*Math.pow(2,i);return n&&Zt(n)&&Date.now()+o-s{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;athis._autoRefreshTokenTick(),Je);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}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 t=>{const{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((s.expires_at*1e3-e)/Je);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Je}ms, refresh threshold is ${ks} ticks`),i<=ks&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ii)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!z()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"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,t,s){const i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[n,o]=await He(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){const n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(k(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;const{data:n,error:o}=t;if(o)return{data:null,error:o};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:l,error:u}=await T(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return u?{data:null,error:u}:(e.factorType==="totp"&&(!((i=l?.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(k(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:i,error:n}=t;if(n)return{data:null,error:n};const{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(k(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(k(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const s=e?.factors||[],i=s.filter(o=>o.factor_type==="totp"&&o.status==="verified"),n=s.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:s,totp:i,phone:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=es(i.access_token);let a=null;o.aal&&(a=o.aal);let l=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");const c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(a=>a.kid===e);if(s)return s;const i=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+yo>i)return s;const{data:n,error:o}=await T(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!n.keys||n.keys.length===0||(this.jwks=n,this.jwks_cached_at=i,s=n.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,t={}){try{let s=e;if(!s){const{data:p,error:y}=await this.getSession();if(y||!p.session)return{data:null,error:y};s=p.session.access_token}const{header:i,payload:n,signature:o,raw:{header:a,payload:l}}=es(s);t?.allowExpired||No(n.exp);const u=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){const{error:p}=await this.getUser(s);if(p)throw p;return{data:{claims:n,header:i,signature:o},error:null}}const c=Bo(i.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,o,Po(`${a}.${l}`)))throw new Ts("Invalid JWT signature");return{data:{claims:n,header:i,signature:o},error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}}}bt.nextInstanceID=0;const aa=bt;class la extends aa{constructor(e){super(e)}}var ua=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{u(s.next(c))}catch(d){o(d)}}function l(c){try{u(s.throw(c))}catch(d){o(d)}}function u(c){c.done?n(c.value):i(c.value).then(a,l)}u((s=s.apply(r,e||[])).next())})};class ca{constructor(e,t,s){var i,n,o;this.supabaseUrl=e,this.supabaseKey=t;const a=ho(e);if(!t)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 l=`sb-${a.hostname.split(".")[0]}-auth-token`,u={db:to,realtime:ro,auth:Object.assign(Object.assign({},so),{storageKey:l}),global:eo},c=co(s??{},u);this.storageKey=(i=c.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken?(this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=ao(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.rest=new yn(new URL("rest/v1",a).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this.storage=new Yn(this.storageUrl.href,this.headers,this.fetch,s?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new zi(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return ua(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,userStorage:n,storageKey:o,flowType:a,lock:l,debug:u},c,d){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new la({url:this.authUrl.href,headers:Object.assign(Object.assign({},f),c),storageKey:o,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,userStorage:n,flowType:a,lock:l,debug:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new xn(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.changedAccessToken=s,this.realtime.setAuth(s)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Ca=(r,e,t)=>new ca(r,e,t);function ha(){if(typeof window<"u"||typeof process>"u")return!1;const r=process.version;if(r==null)return!1;const e=r.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}ha()&&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");export{pa as Q,Tt as _,ga as a,va as b,Ca as c,ya as d,fi as j,xr as u};