1var vr=s=>{throw TypeError(s)};var gs=(s,e,t)=>e.has(s)||vr("Cannot "+t);var l=(s,e,t)=>(gs(s,e,"read from private field"),t?t.call(s):e.get(s)),b=(s,e,t)=>e.has(s)?vr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),v=(s,e,t,r)=>(gs(s,e,"write to private field"),r?r.call(s,t):e.set(s,t),t),S=(s,e,t)=>(gs(s,e,"access private method"),t);var Yt=(s,e,t,r)=>({set _(i){v(s,e,i,t)},get _(){return l(s,e,r)}});import{r as Zi,a as I}from"./vendor-react-DtPELkcG.js";function en(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function tn(s){if(Object.prototype.hasOwnProperty.call(s,"__esModule"))return s;var e=s.default;if(typeof e=="function"){var t=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(r){var i=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return s[r]}})}),t}var ys={exports:{}},Ot={};var mr;function sn(){if(mr)return Ot;mr=1;var s=Zi(),e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,i=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n={key:!0,ref:!0,__self:!0,__source:!0};function a(o,c,u){var h,d={},f=null,p=null;u!==void 0&&(f=""+u),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(p=c.ref);for(h in c)r.call(c,h)&&!n.hasOwnProperty(h)&&(d[h]=c[h]);if(o&&o.defaultProps)for(h in c=o.defaultProps,c)d[h]===void 0&&(d[h]=c[h]);return{$$typeof:e,type:o,key:f,ref:p,props:d,_owner:i.current}}return Ot.Fragment=t,Ot.jsx=a,Ot.jsxs=a,Ot}var br;function rn(){return br||(br=1,ys.exports=sn()),ys.exports}var nn=rn();const an="modulepreload",on=function(s){return"/"+s},wr={},ir=function(e,t,r){let i=Promise.resolve();if(t&&t.length>0){let c=function(u){return Promise.all(u.map(h=>Promise.resolve(h).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),o=a?.nonce||a?.getAttribute("nonce");i=c(t.map(u=>{if(u=on(u),u in wr)return;wr[u]=!0;const h=u.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const f=document.createElement("link");if(f.rel=h?"stylesheet":an,h||(f.as="script"),f.crossOrigin="",f.href=u,o&&f.setAttribute("nonce",o),document.head.appendChild(f),h)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function n(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&n(o.reason);return e().catch(n)})},cn=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>ir(async()=>{const{default:r}=await Promise.resolve().then(()=>ls);return{default:r}},void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};class nr extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class un extends nr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class _r extends nr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Sr extends nr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Es;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Es||(Es={}));var ln=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(h){try{u(r.next(h))}catch(d){a(d)}}function c(h){try{u(r.throw(h))}catch(d){a(d)}}function u(h){h.done?n(h.value):i(h.value).then(o,c)}u((r=r.apply(s,e||[])).next())})};class hn{constructor(e,{headers:t={},customFetch:r,region:i=Es.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=cn(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return ln(this,void 0,void 0,function*(){try{const{headers:i,method:n,body:a}=t;let o={},{region:c}=t;c||(c=this.region);const u=new URL(`${this.url}/${e}`);c&&c!=="any"&&(o["x-region"]=c,u.searchParams.set("forceFunctionRegion",c));let h;a&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&a
1instanceof Blob||a instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",h=a):typeof a=="string"?(o["Content-Type"]="text/plain",h=a):typeof FormData<"u"&&a instanceof FormData?h=a:(o["Content-Type"]="application/json",h=JSON.stringify(a)));const d=yield this.fetch(u.toString(),{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),i),body:h}).catch(y=>{throw new un(y)}),f=d.headers.get("x-relay-error");if(f&&f==="true")throw new _r(d);if(!d.ok)throw new Sr(d);let p=((r=d.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),g;return p==="application/json"?g=yield d.json():p==="application/octet-stream"?g=yield d.blob():p==="text/event-stream"?g=d:p==="multipart/form-data"?g=yield d.formData():g=yield d.text(),{data:g,error:null,response:d}}catch(i){return{data:null,error:i,response:i instanceof Sr||i instanceof _r?i.context:void 0}}})}}var B={},ze={},Ge={},Je={},Xe={},Ye={},dn=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof globalThis<"u")return globalThis;throw new Error("unable to locate global object")},_t=dn();const fn=_t.fetch,pi=_t.fetch.bind(_t),gi=_t.Headers,pn=_t.Request,gn=_t.Response,ls=Object.freeze(Object.defineProperty({__proto__:null,Headers:gi,Request:pn,Response:gn,default:pi,fetch:fn},Symbol.toStringTag,{value:"Module"})),yn=tn(ls);var Zt={},kr;function yi(){if(kr)return Zt;kr=1,Object.defineProperty(Zt,"__esModule",{value:!0});class s extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
1de=t.code}}return Zt.default=s,Zt}var Or;function vi(){if(Or)return Ye;Or=1;var s=Ye&&Ye.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ye,"__esModule",{value:!0});const e=s(yn),t=s(yi());class r{constructor(n){var a,o;this.shouldThrowOnError=!1,this.method=n.method,this.url=n.url,this.headers=new Headers(n.headers),this.schema=n.schema,this.body=n.body,this.shouldThrowOnError=(a=n.shouldThrowOnError)!==null&&a!==void 0?a:!1,this.signal=n.signal,this.isMaybeSingle=(o=n.isMaybeSingle)!==null&&o!==void 0?o:!1,n.fetch?this.fetch=n.fetch:typeof fetch>"u"?this.fetch=e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(n,a){return this.headers=new Headers(this.headers),this.headers.set(n,a),this}then(n,a){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 o=this.fetch;let c=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async u=>{var h,d,f,p;let g=null,y=null,m=null,_=u.status,O=u.statusText;if(u.ok){if(this.method!=="HEAD"){const C=await u.text();C===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((h=this.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?y=C:y=JSON.parse(C))}const E=(d=this.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),A=(f=u.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");E&&A&&A.length>1&&(m=parseInt(A[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(y)&&(y.length>1?(g={code:"PGRST116",details:`Results contain ${y.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},y=null,m=null,_=406,O="Not Acceptable"):y.length===1?y=y[0]:y=null)}else{const E=await u.text();try{g=JSON.parse(E),Array.isArray(g)&&u.status===404&&(y=[],g=null,_=200,O="OK")}catch{u.status===404&&E===""?(_=204,O="No Content"):g={message:E}}if(g&&this.isMaybeSingle&&(!((p=g?.details)===null||p===void 0)&&p.includes("0 rows"))&&(g=null,_=200,O="OK"),g&&this.shouldThrowOnError)throw new t.default(g)}return{error:g,data:y,count:m,status:_,statusText:O}});return this.shouldThrowOnError||(c=c.catch(u=>{var h,d,f;return{error:{message:`${(h=u?.name)!==null&&h!==void 0?h:"FetchError"}: ${u?.message}`,details:`${(d=u?.stack)!==null&&d!==void 0?d:""}`,hint:"",code:`${(f=u?.code)!==null&&f!==void 0?f:""}`},data:null,count:null,status:0,statusText:""}})),c.then(n,a)}returns(){return this}overrideTypes(){return this}}return Ye.default=r,Ye}var Er;function mi(){if(Er)return Xe;Er=1;var s=Xe&&Xe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xe,"__esModule",{value:!0});const e=s(vi());class t extends e.default{select(i){let n=!1;const a=(i??"*").split("").map(o=>/\s/.test(o)&&!n?"":(o==='"'&&(n=!n),o)).join("");return this.url.searchParams.set("select",a),this.headers.append("Prefer","return=representation"),this}order(i,{ascending:n=!0,nullsFirst:a,foreignTable:o,referencedTable:c=o}={}){const u=c?`${c}.order`:"order",h=this.url.searchParams.get(u);return this.url.searchParams.set(u,`${h?`${h},`:""}${i}.${n?"asc":"desc"}${a===void 0?"":a?".nullsfirst":".nullslast"}`),this}limit(i,{foreignTable:n,referencedTable:a=n}={}){const o=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(o,`${i}`),this}range(i,n,{foreignTable:a,referencedTable:o=a}={}){const c=typeof o>"u"?"offset":`${o}.offset`,u=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(c,`${i}`),this.url.searchParams.set(u,`${n-i+1}`),this}abortSignal(i){return this.signal=i,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}
1explain({analyze:i=!1,verbose:n=!1,settings:a=!1,buffers:o=!1,wal:c=!1,format:u="text"}={}){var h;const d=[i?"analyze":null,n?"verbose":null,a?"settings":null,o?"buffers":null,c?"wal":null].filter(Boolean).join("|"),f=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${u}; for="${f}"; options=${d};`),u==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(i){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${i}`),this}}return Xe.default=t,Xe}var Tr;function ar(){if(Tr)return Je;Tr=1;var s=Je&&Je.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Je,"__esModule",{value:!0});const e=s(mi());class t extends e.default{eq(i,n){return this.url.searchParams.append(i,`eq.${n}`),this}neq(i,n){return this.url.searchParams.append(i,`neq.${n}`),this}gt(i,n){return this.url.searchParams.append(i,`gt.${n}`),this}gte(i,n){return this.url.searchParams.append(i,`gte.${n}`),this}lt(i,n){return this.url.searchParams.append(i,`lt.${n}`),this}lte(i,n){return this.url.searchParams.append(i,`lte.${n}`),this}like(i,n){return this.url.searchParams.append(i,`like.${n}`),this}likeAllOf(i,n){return this.url.searchParams.append(i,`like(all).{${n.join(",")}}`),this}likeAnyOf(i,n){return this.url.searchParams.append(i,`like(any).{${n.join(",")}}`),this}ilike(i,n){return this.url.searchParams.append(i,`ilike.${n}`),this}ilikeAllOf(i,n){return this.url.searchParams.append(i,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(i,n){return this.url.searchParams.append(i,`ilike(any).{${n.join(",")}}`),this}is(i,n){return this.url.searchParams.append(i,`is.${n}`),this}in(i,n){const a=Array.from(new Set(n)).map(o=>typeof o=="string"&&new RegExp("[,()]").test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(i,`in.(${a})`),this}contains(i,n){return typeof n=="string"?this.url.searchParams.append(i,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(i,`cs.{${n.join(",")}}`):this.url.searchParams.append(i,`cs.${JSON.stringify(n)}`),this}containedBy(i,n){return typeof n=="string"?this.url.searchParams.append(i,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(i,`cd.{${n.join(",")}}`):this.url.searchParams.append(i,`cd.${JSON.stringify(n)}`),this}rangeGt(i,n){return this.url.searchParams.append(i,`sr.${n}`),this}rangeGte(i,n){return this.url.searchParams.append(i,`nxl.${n}`),this}rangeLt(i,n){return this.url.searchParams.append(i,`sl.${n}`),this}rangeLte(i,n){return this.url.searchParams.append(i,`nxr.${n}`),this}rangeAdjacent(i,n){return this.url.searchParams.append(i,`adj.${n}`),this}overlaps(i,n){return typeof n=="string"?this.url.searchParams.append(i,`ov.${n}`):this.url.searchParams.append(i,`ov.{${n.join(",")}}`),this}textSearch(i,n,{config:a,type:o}={}){let c="";o==="plain"?c="pl":o==="phrase"?c="ph":o==="websearch"&&(c="w");const u=a===void 0?"":`(${a})`;return this.url.searchParams.append(i,`${c}fts${u}.${n}`),this}match(i){return Object.entries(i).forEach(([n,a])=>{this.url.searchParams.append(n,`eq.${a}`)}),this}not(i,n,a){return this.url.searchParams.append(i,`not.${n}.${a}`),this}or(i,{foreignTable:n,referencedTable:a=n}={}){const o=a?`${a}.or`:"or";return this.url.searchParams.append(o,`(${i})`),this}filter(i,n,a){return this.url.searchParams.append(i,`${n}.${a}`),this}}return Je.default=t,Je}var Pr;function bi(){if(Pr)return Ge;Pr=1;var s=Ge&&Ge.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ge,"__esModule",{value:!0});const e=s(ar());class t{constructor(i,{headers:n={},schema:a,fetch:o}){this.url=i,this.headers=new Headers(n),this.schema=a,this.fetch=o}select(i,{head:n=!1,count:a}={}){const o=n?"HEAD":"GET";let c=!1;const u=(i??"*").split("").map(h=>/\s/.test(h)&&!c?"":(h==='"'&&(c=!c),h)).join("");return this.url.searchParams.set("select",u),a&&this.headers.append("Prefer",`count=${a}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(i,{count:n,defaultToNull:a=!0}={}){var o;const c="POST";if(n&&this.headers.append("Prefer",`count=${n}`),a||this.headers.append("Prefer","missing=default"),Array.isArray(i)){const u=i.reduce((h,d)=>h.concat(Object.keys(d)),[]);if(u.length>0){const h=[...new Set(u)].map(d=>`"${d}"`);this.url.searchParams.set("columns",h.join(","))}}return new e.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}upsert(i,{onConflict:n,ignoreDuplicates:a=!1,count:o,defaultToNull:c=!0}={}){var u;const h="POST";if(this.headers.append("Prefer",`resolution=${a?"ignore":"merge"}-duplicates`),n!==void 0&&this.url.searchParams.set("on_conflict",n),o&&this.headers.append("Prefer",`count=${o}`),c||this.headers.append("Prefer","missing=default"),Array.isArray(i)){const d=i.reduce((f,p)=>f.concat(Object.keys(p)),[]);if(d.length>0){const f=[...new Set(d)].map(p=>`"${p}"`);this.url.searchParams.set("columns",f.join(","))}}return new e.default({method:h,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}update(i,{count:n}={}){var a;const o="PATCH";return n&&this.headers.append("Prefer",`count=${n}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:i,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}delete({count:i}={}){var n;const a="DELETE";return i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch})}}return Ge.default=t,Ge}var Cr;function vn(){if(Cr)return ze;Cr=1;var s=ze&&ze.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};
1Object.defineProperty(ze,"__esModule",{value:!0});const e=s(bi()),t=s(ar());class r{constructor(n,{headers:a={},schema:o,fetch:c}={}){this.url=n,this.headers=new Headers(a),this.schemaName=o,this.fetch=c}from(n){const a=new URL(`${this.url}/${n}`);return new e.default(a,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(n){return new r(this.url,{headers:this.headers,schema:n,fetch:this.fetch})}rpc(n,a={},{head:o=!1,get:c=!1,count:u}={}){var h;let d;const f=new URL(`${this.url}/rpc/${n}`);let p;o||c?(d=o?"HEAD":"GET",Object.entries(a).filter(([y,m])=>m!==void 0).map(([y,m])=>[y,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([y,m])=>{f.searchParams.append(y,m)})):(d="POST",p=a);const g=new Headers(this.headers);return u&&g.set("Prefer",`count=${u}`),new t.default({method:d,url:f,headers:g,schema:this.schemaName,body:p,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch})}}return ze.default=r,ze}var Rr;function mn(){if(Rr)return B;Rr=1;var s=B&&B.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(B,"__esModule",{value:!0}),B.PostgrestError=B.PostgrestBuilder=B.PostgrestTransformBuilder=B.PostgrestFilterBuilder=B.PostgrestQueryBuilder=B.PostgrestClient=void 0;const e=s(vn());B.PostgrestClient=e.default;const t=s(bi());B.PostgrestQueryBuilder=t.default;const r=s(ar());B.PostgrestFilterBuilder=r.default;const i=s(mi());B.PostgrestTransformBuilder=i.default;const n=s(vi());B.PostgrestBuilder=n.default;const a=s(yi());return B.PostgrestError=a.default,B.default={PostgrestClient:e.default,PostgrestQueryBuilder:t.default,PostgrestFilterBuilder:r.default,PostgrestTransformBuilder:i.default,PostgrestBuilder:n.default,PostgrestError:a.default},B}var bn=mn();const wn=en(bn),{PostgrestClient:_n,PostgrestQueryBuilder:uc,PostgrestFilterBuilder:lc,PostgrestTransformBuilder:hc,PostgrestBuilder:dc,PostgrestError:fc}=wn;class Sn{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 globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.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"&&process.versions&&process.versions.node){const t=parseInt(process.versions.node.split(".")[0]);return t>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${t} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${t} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 2import ws from "ws" 3new 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+=` 4 5Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const r=this.getWebSocketConstructor();return new r(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const kn="2.15.4",On=`realtime-js/${kn}`,En="1.0.0",Ts=1e4,Tn=1e3,Pn=100;var Ct;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(Ct||(Ct={}));var L;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(L||(L={}));var re;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(re||(re={}));var Ps;(function(s){s.websocket="websocket"})(Ps||(Ps={}));var $e;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})($e||($e={}));class Cn{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),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const i=t.getUint8(1),n=t.getUint8(2);let a=this.HEADER_LENGTH+2;const o=r.decode(e.slice(a,a+i));a=a+i;const c=r.decode(e.slice(a,a+n));a=a+n;const u=JSON.parse(r.decode(e.slice(a,e.byteLength)));return{ref:null,topic:o,event:c,payload:u}}}class wi{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 x;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(x||(x={}));const jr=(s,e,t={})=>{var r;const i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,a)=>(n[a]=Rn(a,s,e,i),n),{})},Rn=(s,e,t,r)=>{const i=e.find(o=>o.name===s),n=i?.type,a=t[s];return n&&!r.includes(n)?_i(n,a):Cs(a)},_i=(s,e)=>{if(s.charAt(0)==="_"){const t=s.slice(1,s.length);return In(e,t)}switch(s){case x.bool:return jn(e);case x.float4:case x.float8:case x.int2:case x.int4:case x.int8:case x.numeric:case x.oid:return An(e);case x.json:case x.jsonb:return xn(e);case x.timestamp:return $n(e);case x.abstime:case x.date:case x.daterange:case x.int4range:case x.int8range:case x.money:case x.reltime:case x.text:case x.time:case x.timestamptz:case x.timetz:case x.tsrange:case x.tstzrange:return Cs(e);default:return Cs(e)}},Cs=s=>
vendor: 5,723 bytes, line 5
5s,jn=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},An=s=>{if(typeof s=="string"){const e=parseFloat(s);if(!Number.isNaN(e))return e}return s},xn=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch{return s}return s},In=(s,e)=>{if(typeof s!="string")return s;const t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n;const a=s.slice(1,t);try{n=JSON.parse("["+a+"]")}catch{n=a?a.split(","):[]}return n.map(o=>_i(e,o))}return s},$n=s=>typeof s=="string"?s.replace(" ","T"):s,Si=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class vs{constructor(e,t,r={},i=Ts){this.channel=e,this.event=t,this.payload=r,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 r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.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(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Ar;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Ar||(Ar={}));class Rt{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:n,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Rt.syncState(this.state,i,n,a),this.pendingDiffs.forEach(c=>{this.state=Rt.syncDiff(this.state,c,n,a)}),this.pendingDiffs=[],o()}),this.channel._on(r.diff,{},i=>{const{onJoin:n,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Rt.syncDiff(this.state,i,n,a),o())}),this.onJoin((i,n,a)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:a})}),this.onLeave((i,n,a)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){const n=this.cloneDeep(e),a=this.transformState(t),o={},c={};return this.map(n,(u,h)=>{a[u]||(c[u]=h)}),this.map(a,(u,h)=>{const d=n[u];if(d){const f=h.map(m=>m.presence_ref),p=d.map(m=>m.presence_ref),g=h.filter(m=>p.indexOf(m.presence_ref)<0),y=d.filter(m=>f.indexOf(m.presence_ref)<0);g.length>0&&(o[u]=g),y.length>0&&(c[u]=y)}else o[u]=h}),this.syncDiff(n,{joins:o,leaves:c},r,i)}static syncDiff(e,t,r,i){const{joins:n,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(o,c)=>{var u;const h=(u=e[o])!==null&&u!==void 0?u:[];if(e[o]=this.cloneDeep(c),h.length>0){const d=e[o].map(p=>p.presence_ref),f=h.filter(p=>d.indexOf(p.presence_ref)<0);e[o].unshift(...f)}r(o,h,c)}),this.map(a,(o,c)=>{let u=e[o];if(!u)return;const h=c.map(d=>d.presence_ref);u=u.filter(d=>h.indexOf(d.presence_ref)<0),e[o]=u,i(o,u,c),u.length===0&&delete e[o]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=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 xr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(xr||(xr={}));var jt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(jt||(jt={}));var ue;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(ue||(ue={}));class or{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,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 vs(this,re.join,this.params,this.timeout),this.rejoinTimer=new wi(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=L.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>
5i.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(re.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Rt(this),this.broadcastEndpointURL=Si(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var r,i,n;if(this.socket.isConnected()||this.socket.connect(),this.state==L.closed){const{config:{broadcast:a,presence:o,private:c}}=this.params,u=(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(p=>p.filter))!==null&&i!==void 0?i:[],h=!!this.bindings[jt.PRESENCE]&&this.bindings[jt.PRESENCE].length>0||((n=this.params.config.presence)===null||n===void 0?void 0:n.enabled)===!0,d={},f={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:h}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(p=>e?.(ue.CHANNEL_ERROR,p)),this._onClose(()=>e?.(ue.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:p})=>{var g;if(this.socket.setAuth(),p===void 0){e?.(ue.SUBSCRIBED);return}else{const y=this.bindings.postgres_changes,m=(g=y?.length)!==null&&g!==void 0?g:0,_=[];for(let O=0;O<m;O++){const w=y[O],{filter:{event:E,schema:A,table:C,filter:F}}=w,Q=p&&p[O];if(Q&&Q.event===E&&Q.schema===A&&Q.table===C&&Q.filter===F)_.push(Object.assign(Object.assign({},w),{id:Q.id}));else{this.unsubscribe(),this.state=L.errored,e?.(ue.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e(ue.SUBSCRIBED);return}}).receive("error",p=>{this.state=L.errored,e?.(ue.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e?.(ue.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,r){return this.state===L.joined&&e===jt.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,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){const{event:n,payload:a}=e,c={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:a,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(r=t.timeout)!==null&&r!==void 0?r: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 a,o,c;const u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.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(re.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(i=>{r=new vs(this,re.leave,{},e),r.receive("ok",()=>{t(),i("ok")}).receive("timeout",()=>{t(),i("timed out")}).receive("error",()=>{i("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r?.destroy()})}
5teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=L.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const i=new AbortController,n=setTimeout(()=>i.abort(),r),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),a}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new vs(this,e,t,r);return this._canPush()?i.send():this._addToPushBuffer(i),i}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>Pn){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,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;const a=e.toLocaleLowerCase(),{close:o,error:c,leave:u,join:h}=re;if(r&&[o,c,u,h].indexOf(a)>=0&&r!==this._joinRef())return;let f=this._onMessage(a,t,r);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(p=>{var g,y,m;return((g=p.filter)===null||g===void 0?void 0:g.event)==="*"||((m=(y=p.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===a}).map(p=>p.callback(f,r)):(n=this.bindings[a])===null||n===void 0||n.filter(p=>{var g,y,m,_,O,w;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in p){const E=p.id,A=(g=p.filter)===null||g===void 0?void 0:g.event;return E&&((y=t.ids)===null||y===void 0?void 0:y.includes(E))&&(A==="*"||A?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{const E=(O=(_=p?.filter)===null||_===void 0?void 0:_.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return E==="*"||E===((w=t?.event)===null||w===void 0?void 0:w.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===a}).map(p=>{if(typeof f=="object"&&"ids"in f){const g=f.data,{schema:y,table:m,commit_timestamp:_,type:O,errors:w}=g;f=Object.assign(Object.assign({},{schema:y,table:m,commit_timestamp:_,eventType:O,new:{},old:{},errors:w}),this._getPayloadRecords(g))}p.callback(f,r)})}_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,r){const i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&or.isEqual(i.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(re.close,{},e)}_onError(e){this._on(re.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=jr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=jr(e.columns,e.old_record)),t}}const ms=()=>{},es={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Un=[1e3,2e3,5e3,1e4],Dn=1e4,Ln=` 6 addEventListener("message", (e) => { 7 if (e.data.event === "start") { 8 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 9 } 10 });`;class Nn{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Ts,this.transport=null,this.heartbeatIntervalMs=es.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ms,this.ref=0,this.reconnectTimer=null,this.logger=ms,this.conn=null,this.sendBuffer=[],this.serializer
10=new Cn,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=(...a)=>ir(async()=>{const{default:o}=await Promise.resolve().then(()=>ls);return{default:o}},void 0).then(({default:o})=>o(...a)).catch(o=>{throw new Error(`Failed to load @supabase/node-fetch: ${o.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):n=fetch,(...a)=>n(...a)},!(!((r=t?.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Ps.websocket}`,this.httpEndpoint=Si(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=Sn.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t} 11 12To use Realtime in Node.js, you need to provide a WebSocket implementation: 13 14Option 1: Use Node.js 22+ which has native WebSocket support 15Option 2: Install and provide the "ws" package: 16 17 npm install ws 18 19 import ws from "ws" 20 const client = new RealtimeClient(url, { 21 ...options, 22 transport: ws 23 })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:En}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),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,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Ct.connecting:return $e.Connecting;case Ct.open:return $e.Open;case Ct.closing:return $e.Closing;default:return $e.Closed}}isConnected(){return this.connectionState()===$e.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const r=`realtime:${e}`,i=this.getChannels().find(n=>n.topic===r);if(i)return i;{const n=new or(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:r,payload:i,ref:n}=e,a=()=>{this.encode(e,o=>{var c;(c=this.conn)===null||c===void 0||c.send(o)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?a():this.sendBuffer.push(a)}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(Tn,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},es.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>
230&&(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(r=>r.topic===e&&(r._isJoined()||r._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:r,event:i,payload:n,ref:a}=t,o=a?`(${a})`:"",c=n.status||"";this.log("receive",`${c} ${r} ${i} ${o}`.trim(),n),this.channels.filter(u=>u._isMember(r)).forEach(u=>u._trigger(i,n,a)),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(re.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_workerObjectUrl(e){let t;if(e)t=e;else{const r=new Blob([Ln],{type:"application/javascript"});t=URL.createObjectURL(r)}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(r=>{const i={access_token:t,version:On};t&&r.updateJoinPayload(i),r.joinedOnce&&r._isJoined()&&r._push(re.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(r=>{try{r(t)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new wi(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},es.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,i,n,a,o,c,u,h;if(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(r=e?.timeout)!==null&&r!==void 0?r:Ts,this.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:es.HEARTBEAT_INTERVAL,this.worker=(n=e?.worker)!==null&&n!==void 0?n:!1,this.accessToken=(a=e?.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(o=e?.heartbeatCallback)!==null&&o!==void 0?o:ms,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=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:(d=>Un[d-1]||Dn),this.encode=(u=e?.encode)!==null&&u!==void 0?u:((d,f)=>f(JSON.stringify(d))),this.decode=(h=e?.decode)!==null&&h!==void 0?h: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}}}
vendor: 4,863 bytes, line 23
23var At=class extends Error{constructor(s,e){super(s),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Fn(s,e,t){const r=new URL(e,s);if(t)for(const[i,n]of Object.entries(t))n!==void 0&&r.searchParams.set(i,n);return r.toString()}async function Bn(s){return!s||s.type==="none"?{}:s.type==="bearer"?{Authorization:`Bearer ${s.token}`}:s.type==="header"?{[s.name]:s.value}:s.type==="custom"?await s.getHeaders():{}}function Mn(s){const e=s.fetchImpl??globalThis.fetch;return{async request({method:t,path:r,query:i,body:n,headers:a}){const o=Fn(s.baseUrl,r,i),c=await Bn(s.auth),u=await e(o,{method:t,headers:{...n?{"Content-Type":"application/json"}:{},...c,...a},body:n?JSON.stringify(n):void 0}),h=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),f=d&&h?JSON.parse(h):h;if(!u.ok){const p=d?f:void 0,g=p?.error;throw new At(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:p})}return{status:u.status,headers:u.headers,data:f}}}}function ts(s){return s.join("�")}var qn=class{constructor(s,e=""){this.client=s,this.prefix=e}async listNamespaces(s){const e=s?{parent:ts(s.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(s,e){const t={namespace:s.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:t})).data}async dropNamespace(s){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ts(s.namespace)}`})}async loadNamespaceMetadata(s){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ts(s.namespace)}`})).data.properties}}async namespaceExists(s){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ts(s.namespace)}`}),!0}catch(e){if(e instanceof At&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(s,e){try{return await this.createNamespace(s,e)}catch(t){if(t instanceof At&&t.status===409)return;throw t}}};function Ze(s){return s.join("�")}var Qn=class{constructor(s,e="",t){this.client=s,this.prefix=e,this.accessDelegation=t}async listTables(s){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ze(s.namespace)}/tables`})).data.identifiers}async createTable(s,e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ze(s.namespace)}/tables`,body:e,headers:t})).data.metadata}async updateTable(s,e){const t=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ze(s.namespace)}/tables/${s.name}`,body:e});return{"metadata-location":t.data["metadata-location"],metadata:t.data.metadata}}async dropTable(s,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ze(s.namespace)}/tables/${s.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(s){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ze(s.namespace)}/tables/${s.name}`,headers:e})).data.metadata}async tableExists(s){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ze(s.namespace)}/tables/${s.name}`,headers:e}),!0}catch(t){if(t instanceof At&&t.status===404)return!1;throw t}}async createTableIfNotExists(s,e){try{return await this.createTable(s,e)}catch(t){if(t instanceof At&&t.status===409)return await this.loadTable({namespace:s.namespace,name:e.name});throw t}}},Kn=class{constructor(s){let e="v1";s.catalogName&&(e+=`/${s.catalogName}`);const t=s.baseUrl.endsWith("/")?s.baseUrl:`${s.baseUrl}/`;this.client=Mn({baseUrl:t,auth:s.auth,fetchImpl:s.fetch}),this.accessDelegation=s.accessDelegation?.join(","),this.namespaceOps=new qn(this.client,e),this.tableOps=new Qn(this.client,e,this.accessDelegation)}async listNamespaces(s){return this.namespaceOps.listNamespaces(s)}async createNamespace(s,e){return this.namespaceOps.createNamespace(s,e)}async dropNamespace(s){await this.namespaceOps.dropNamespace(s)}async loadNamespaceMetadata(s){return this.namespaceOps.loadNamespaceMetadata(s)}async listTables(s){return this.tableOps.listTables(s)}
23async createTable(s,e){return this.tableOps.createTable(s,e)}async updateTable(s,e){return this.tableOps.updateTable(s,e)}async dropTable(s,e){await this.tableOps.dropTable(s,e)}async loadTable(s){return this.tableOps.loadTable(s)}async namespaceExists(s){return this.namespaceOps.namespaceExists(s)}async tableExists(s){return this.tableOps.tableExists(s)}async createNamespaceIfNotExists(s,e){return this.namespaceOps.createNamespaceIfNotExists(s,e)}async createTableIfNotExists(s,e){return this.tableOps.createTableIfNotExists(s,e)}};function xt(s){"@babel/helpers - typeof";return xt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},xt(s)}function Hn(s,e){if(xt(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var r=t.call(s,e);if(xt(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function Wn(s){var e=Hn(s,"string");return xt(e)=="symbol"?e:e+""}function Vn(s,e,t){return(e=Wn(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function Ir(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),t.push.apply(t,r)}return t}function k(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ir(Object(t),!0).forEach(function(r){Vn(s,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Ir(Object(t)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(t,r))})}return s}var hs=class extends Error{constructor(s,e="storage",t,r){super(s),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function ds(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Rs=class extends hs{constructor(s,e,t,r="storage"){super(s,r,e,t),this.name=r==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=t}toJSON(){return k({},super.toJSON())}},ki=class extends hs{constructor(s,e,t="storage"){super(s,t),this.name=t==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function os(s,e,t){const r=k({},s),i=e.toLowerCase();for(const n of Object.keys(r))n.toLowerCase()===i&&delete r[n];return r[i]=t,r}function zn(s){const e={};for(const[t,r]of Object.entries(s))e[t.toLowerCase()]=r;return e}const Gn=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),Jn=s=>{if(typeof s!="object"||s===null)return!1;const e=Object.getPrototypeOf(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in s)&&!(Symbol.iterator in s)},js=s=>{if(Array.isArray(s))return s.map(t=>js(t));if(typeof s=="function"||s!==Object(s))return s;const e={};return Object.entries(s).forEach(([t,r])=>{const i=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[i]=js(r)}),e},Xn=s=>!s||typeof s!="string"||s.length===0||s.length>100||s.trim()!==s||s.includes("/")||s.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(s),$r=s=>{if(typeof s=="object"&&s!==null){const e=s;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const t=e.error;if(typeof t.message=="string")return t.message}}return JSON.stringify(s)},Yn=async(s,e,t,r)=>{if(s!==null&&typeof s=="object"&&"json"in s&&typeof s.json=="function"){const i=s;let n=parseInt(String(i.status),10);Number.isFinite(n)||(n=500),i.json().then(a=>{const o=a?.statusCode||a?.code||n+"";e(new Rs($r(a),n,o,r))}).catch(()=>{const a=n+"";e(new Rs(i.statusText||`HTTP ${n}
23 error`,n,a,r))})}else e(new ki($r(s),s,r))},Zn=(s,e,t,r)=>{const i={method:s,headers:e?.headers||{}};if(s==="GET"||s==="HEAD"||!r)return k(k({},i),t);if(Jn(r)){var n;const a=e?.headers||{};let o;for(const[c,u]of Object.entries(a))c.toLowerCase()==="content-type"&&(o=u);i.headers=os(a,"Content-Type",(n=o)!==null&&n!==void 0?n:"application/json"),i.body=JSON.stringify(r)}else i.body=r;return e?.duplex&&(i.duplex=e.duplex),k(k({},i),t)};async function Et(s,e,t,r,i,n,a){return new Promise((o,c)=>{s(t,Zn(e,r,i,n)).then(u=>{if(!u.ok)throw u;if(r?.noResolveJson)return u;if(a==="vectors"){const h=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!h||!h.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>Yn(u,c,r,a))})}function Oi(s="storage"){return{get:async(e,t,r,i)=>Et(e,"GET",t,r,i,void 0,s),post:async(e,t,r,i,n)=>Et(e,"POST",t,i,n,r,s),put:async(e,t,r,i,n)=>Et(e,"PUT",t,i,n,r,s),head:async(e,t,r,i)=>Et(e,"HEAD",t,k(k({},r),{},{noResolveJson:!0}),i,void 0,s),remove:async(e,t,r,i,n)=>Et(e,"DELETE",t,i,n,r,s)}}const ea=Oi("storage"),{get:It,post:te,put:As,head:ta,remove:$t}=ea,X=Oi("vectors");var St=class{constructor(s,e={},t,r="storage"){this.shouldThrowOnError=!1,this.url=s,this.headers=zn(e),this.fetch=Gn(t),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,e){return this.headers=os(this.headers,s,e),this}async handleOperation(s){var e=this;try{return{data:await s(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(ds(t))return{data:null,error:t};throw t}}};let Ei;Ei=Symbol.toStringTag;var sa=class{constructor(s,e){this.downloadFn=s,this.shouldThrowOnError=e,this[Ei]="StreamDownloadBuilder",this.promise=null}then(s,e){return this.getPromise().then(s,e)}catch(s){return this.getPromise().catch(s)}finally(s){return this.getPromise().finally(s)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var s=this;try{return{data:(await s.downloadFn()).body,error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ds(e))return{data:null,error:e};throw e}}};let Ti;Ti=Symbol.toStringTag;var ra=class{constructor(s,e){this.downloadFn=s,this.shouldThrowOnError=e,this[Ti]="BlobDownloadBuilder",this.promise=null}asStream(){return new sa(this.downloadFn,this.shouldThrowOnError)}then(s,e){return this.getPromise().then(s,e)}catch(s){return this.getPromise().catch(s)}finally(s){return this.getPromise().finally(s)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var s=this;try{return{data:await(await s.downloadFn()).blob(),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(ds(e))return{data:null,error:e};throw e}}};const bs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ur={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var ia=class extends St{constructor(s,e={},t,r){super(s,e,r,"storage"),this.bucketId=t}async uploadOrUpdate(s,e,t,r){var i=this;return i.handleOperation(async()=>{let n;const a=k(k({},Ur),r);let o=k(k({},i.headers),s==="POST"&&{"x-upsert":String(a.upsert)});const c=a.metadata;if(typeof Blob<"u"&&t instanceof Blob?(n=new FormData,n.append("cacheControl",a.cacheControl),c&&n.append("metadata",i.encodeMetadata(c)),n.append("",t)):typeof FormData<"u"&&t instanceof FormData?(n=t,n.has("cacheControl")||n.append("cacheControl",a.cacheControl),c&&!n.has("metadata")&&n.append("metadata",i.encodeMetadata(c))):(n=t,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,c&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<"u"&&n instanceof ReadableStream||n&&typeof n=="object"&&"pipe"in n&&typeof n.pipe=="function")&&!a.duplex&&(a.duplex="half")),r?.headers)for(const[f,p]of Object.entries(r.headers))o=os(o,f,p);const u=i._removeEmptyFolders(e),h=i._getFinalPath(u),d=await(s=="PUT"?As:te)(i.fetch,`${i.url}/object/${h}`,n,k({headers:o},a?.duplex?{duplex:a.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(s,e,t){return this.uploadOrUpdate("POST",s,e,t)}async uploadToSignedUrl(s,e,t,r){var i=this;const n=i._removeEmptyFolders(s),a=i._getFinalPath(n),o=new URL(i.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),i.handleOperation(async()=>{let c;const u=k(k({},Ur),r);let h=k(k({},i.headers),{"x-upsert":String(u.upsert)});const d=u.metadata;if(typeof Blob<"u"&&t instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),d&&c.append("metadata",i.encodeMetadata(d)),c.append("",t)):typeof FormData<"u"&&t instanceof FormData?(c=t,c.has("cacheControl")||c.append("cacheControl",u.cacheControl),d&&!c.has("metadata")&&c.append("metadata",i.encodeMetadata(d))):(c=t,h["cache-control"]=`max-age=${u.cacheControl}`,h["content-type"]=u.contentType,d&&(h["x-metadata"]=i.toBase64(i.encodeMetadata(d))),(typeof ReadableStream<"u"&&c instanceof ReadableStream||c&&typeof c=="object"&&"pipe"in c&&typeof c.pipe=="function")&&!u.duplex&&(u.duplex="half")),r?.headers)for(const[f,p]of Object.entries(r.headers))h=os(h,f,p);return{path:n,fullPath:(await As(i.fetch,o.toString(),c,k({headers:h},u?.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(s,e){var t=this;return t.handleOperation(async()=>{let r=t._getFinalPath(s);const i=k({},t.headers);e?.upsert&&(i["x-upsert"]="true");const n=await te(t.fetch,`${t.url}/object/upload/sign/${r}`,{},{headers:i}),a=new URL(t.url+n.url),o=a.searchParams.get("token");if(!o)throw new hs("No token returned by API");return{signedUrl:a.toString(),path:s,token:o}})}async update(s,e,t){return this.uploadOrUpdate("PUT",s,e,t)}async move(s,e,t){var r=this;return r.handleOperation(async()=>await te(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:s,destinationKey:e,destinationBucket:t?.destinationBucket},{headers:r.headers}))}async copy(s,e,t){var r=this;return r.handleOperation(async()=>({path:(await te(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:s,destinationKey:e,destinationBucket:t?.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(s,e,t){var r=this;return r.handleOperation(async()=>{let i=r._getFinalPath(s);const n=typeof t?.transform=="object"&&t.transform!==null&&Object.keys(t.transform).length>0;let a=await te(r.fetch,`${r.url}/object/sign/${i}
23`,k({expiresIn:e},n?{transform:t.transform}:{}),{headers:r.headers});const o=new URLSearchParams;t?.download&&o.set("download",t.download===!0?"":t.download),t?.cacheNonce!=null&&o.set("cacheNonce",String(t.cacheNonce));const c=o.toString();return{signedUrl:encodeURI(`${r.url}${a.signedURL}${c?`&${c}`:""}`)}})}async createSignedUrls(s,e,t){var r=this;return r.handleOperation(async()=>{const i=await te(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:e,paths:s},{headers:r.headers}),n=new URLSearchParams;t?.download&&n.set("download",t.download===!0?"":t.download),t?.cacheNonce!=null&&n.set("cacheNonce",String(t.cacheNonce));const a=n.toString();return i.map(o=>k(k({},o),{},{signedUrl:o.signedURL?encodeURI(`${r.url}${o.signedURL}${a?`&${a}`:""}`):null}))})}download(s,e,t){const r=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(i,e.transform),e?.cacheNonce!=null&&i.set("cacheNonce",String(e.cacheNonce));const n=i.toString(),a=this._getFinalPath(s),o=()=>It(this.fetch,`${this.url}/${r}/${a}${n?`?${n}`:""}`,{headers:this.headers,noResolveJson:!0},t);return new ra(o,this.shouldThrowOnError)}async info(s){var e=this;const t=e._getFinalPath(s);return e.handleOperation(async()=>js(await It(e.fetch,`${e.url}/object/info/${t}`,{headers:e.headers})))}async exists(s){var e=this;const t=e._getFinalPath(s);try{return await ta(e.fetch,`${e.url}/object/${t}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(ds(i)){var r;const n=i instanceof Rs?i.status:i instanceof ki?(r=i.originalError)===null||r===void 0?void 0:r.status:void 0;if(n!==void 0&&[400,404].includes(n))return{data:!1,error:i}}throw i}}getPublicUrl(s,e){const t=this._getFinalPath(s),r=new URLSearchParams;e?.download&&r.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(r,e.transform),e?.cacheNonce!=null&&r.set("cacheNonce",String(e.cacheNonce));const i=r.toString(),n=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${t}`)+(i?`?${i}`:"")}}}async remove(s){var e=this;return e.handleOperation(async()=>await $t(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:s},{headers:e.headers}))}async purgeCache(s,e,t){var r=this;return r.handleOperation(async()=>{const i=r._getFinalPath(s),n=new URLSearchParams;e?.transformations&&n.set("transformations","true");const a=n.toString();return await $t(r.fetch,`${r.url}/cdn/${i}${a?`?${a}`:""}`,{},{headers:r.headers},t)})}async list(s,e,t){var r=this;return r.handleOperation(async()=>{const i=e?.sortBy?k(k({},bs.sortBy),e.sortBy):bs.sortBy,n=k(k(k({},bs),e),{},{sortBy:i,prefix:s||""});return await te(r.fetch,`${r.url}/object/list/${r.bucketId}`,n,{headers:r.headers},t)})}async listV2(s,e){var t=this;return t.handleOperation(async()=>{const r=k({},s);return await te(t.fetch,`${t.url}/object/list-v2/${t.bucketId}`,r,{headers:t.headers},e)})}encodeMetadata(s){return JSON.stringify(s)}toBase64(s){return typeof Buffer<"u"?Buffer.from(s).toString("base64"):btoa(s)}_getFinalPath(s){return`${this.bucketId}/${s.replace(/^\/+/,"")}`}_removeEmptyFolders(s){return s.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(s,e){return e.width&&s.set("width",e.width.toString()),e.height&&s.set("height",e.height.toString()),e.resize&&s.set("resize",e.resize),e.format&&s.set("format",e.format),e.quality&&s.set("quality",e.quality.toString()),s}};const na="2.110.0",zt={"X-Client-Info":`storage-js/${na}`};var aa=class extends St{constructor(s,e={},t,r){const i=new URL(s);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));const n=i.href.replace(/\/$/,""),a=k(k({},zt),e);super(n,a,t,"storage")}async listBuckets(s){var e=this;return e.handleOperation(async()=>{const t=e.listBucketOptionsToQueryString(s);return await It(e.fetch,`${e.url}/bucket${t}`,{headers:e.headers})})}async getBucket(s){var e=this;return e.handleOperation(async()=>await It(e.fetch,`${e.url}/bucket/${s}`,{headers:e.headers}))}async createBucket(s,e={public:!1}){var t=this;return t.handleOperation(async()=>await te(t.fetch,`${t.url}/bucket`,{id:s,name:s,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async updateBucket(s,e){var t=this;return t.handleOperation(async()=>await As(t.fetch,`${t.url}/bucket/${s}`,{id:s,name:s,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async emptyBucket(s){var e=this;return e.handleOperation(async()=>await te(e.fetch,`${e.url}/bucket/${s}/empty`,{},{headers:e.headers}))}async deleteBucket(s){var e=this;return e.handleOperation(async()=>await $t(e.fetch,`${e.url}/bucket/${s}`,{},{headers:e.headers}))}async purgeBucketCache(s,e,t){var r=this;return r.handleOperation(async()=>{const i=new URLSearchParams;e?.transformations&&i.set("transformations","true");const n=i.toString();return await $t(r.fetch,`${r.url}/cdn/${s}${n?`?${n}`:""}`,{},{headers:r.headers},t)})}listBucketOptionsToQueryString(s){const e={};return s&&("limit"in s&&(e.limit=String(s.limit)),"offset"in s&&(e.offset=String(s.offset)),s.search&&(e.search=s.search),s.sortColumn&&(e.sortColumn=s.sortColumn),s.sortOrder&&(e.sortOrder=s.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},oa=class extends St{constructor(s,e={},t){const r=s.replace(/\/$/,""),i=k(k({},zt),e);super(r,i,t,"storage")}async createBucket(s){var e=this;return e.handleOperation(async()=>await te(e.fetch,`${e.url}/bucket`,{name:s},{headers:e.headers}))}async listBuckets(s){var e=this;return e.handleOperation(async()=>{const t=new URLSearchParams;s?.limit!==void 0&&t.set("limit",s.limit.toString()),s?.offset!==void 0&&t.set("offset",s.offset.toString()),s?.sortColumn&&t.set("sortColumn",s.sortColumn),s?.sortOrder&&t.set("sortOrder",s.sortOrder),s?.search&&t.set("search",s.search);const r=t.toString(),i=r?`${e.url}/bucket?${r}`:`${e.url}/bucket`;return await It(e.fetch,i,{headers:e.headers})})}async deleteBucket(s){var e=this;return e.handleOperation(async()=>await $t(e.fetch,`${e.url}/bucket/${s}`,{},{headers:e.headers}))}from(s){var e=this;if(!Xn(s))throw new hs("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const t=new Kn({baseUrl:this.url,catalogName:s,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}
23),r=this.shouldThrowOnError;return new Proxy(t,{get(i,n){const a=i[n];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(i,o),error:null}}catch(c){if(r)throw c;return{data:null,error:c}}}}})}},ca=class extends St{constructor(s,e={},t){const r=s.replace(/\/$/,""),i=k(k({},zt),{},{"Content-Type":"application/json"},e);super(r,i,t,"vectors")}async createIndex(s){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/CreateIndex`,s,{headers:e.headers})||{})}async getIndex(s,e){var t=this;return t.handleOperation(async()=>await X.post(t.fetch,`${t.url}/GetIndex`,{vectorBucketName:s,indexName:e},{headers:t.headers}))}async listIndexes(s){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/ListIndexes`,s,{headers:e.headers}))}async deleteIndex(s,e){var t=this;return t.handleOperation(async()=>await X.post(t.fetch,`${t.url}/DeleteIndex`,{vectorBucketName:s,indexName:e},{headers:t.headers})||{})}},ua=class extends St{constructor(s,e={},t){const r=s.replace(/\/$/,""),i=k(k({},zt),{},{"Content-Type":"application/json"},e);super(r,i,t,"vectors")}async putVectors(s){var e=this;if(s.vectors.length<1||s.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/PutVectors`,s,{headers:e.headers})||{})}async getVectors(s){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/GetVectors`,s,{headers:e.headers}))}async listVectors(s){var e=this;if(s.segmentCount!==void 0){if(s.segmentCount<1||s.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(s.segmentIndex!==void 0&&(s.segmentIndex<0||s.segmentIndex>=s.segmentCount))throw new Error(`segmentIndex must be between 0 and ${s.segmentCount-1}`)}return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/ListVectors`,s,{headers:e.headers}))}async queryVectors(s){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/QueryVectors`,s,{headers:e.headers}))}async deleteVectors(s){var e=this;if(s.keys.length<1||s.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/DeleteVectors`,s,{headers:e.headers})||{})}},la=class extends St{constructor(s,e={},t){const r=s.replace(/\/$/,""),i=k(k({},zt),{},{"Content-Type":"application/json"},e);super(r,i,t,"vectors")}async createBucket(s){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:s},{headers:e.headers})||{})}async getBucket(s){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:s},{headers:e.headers}))}async listBuckets(s={}){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/ListVectorBuckets`,s,{headers:e.headers}))}async deleteBucket(s){var e=this;return e.handleOperation(async()=>await X.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:s},{headers:e.headers})||{})}},ha=class extends la{constructor(s,e={}){super(s,e.headers||{},e.fetch)}from(s){return new da(this.url,this.headers,s,this.fetch)}async createBucket(s){var e=()=>super.createBucket,t=this;return e().call(t,s)}async getBucket(s){var e=()=>super.getBucket,t=this;return e().call(t,s)}async listBuckets(s={}){var e=()=>super.listBuckets,t=this;return e().call(t,s)}async deleteBucket(s){var e=()=>super.deleteBucket,t=this;return e().call(t,s)}},da=class extends ca{constructor(s,e,t,r){super(s,e,r),this.vectorBucketName=t}async createIndex(s){var e=()=>super.createIndex,t=this;return e().call(t,k(k({},s),{},{vectorBucketName:t.vectorBucketName}))}async listIndexes(s={}){var e=()=>super.listIndexes,t=this;return e().call(t,k(k({},s),{},{vectorBucketName:t.vectorBucketName}))}async getIndex(s){var e=()=>super.getIndex,t=this;return e().call(t,t.vectorBucketName,s)}async deleteIndex(s){var e=()=>super.deleteIndex,t=this;return e().call(t,t.vectorBucketName,s)}index(s){return new fa(this.url,this.headers,this.vectorBucketName,s,this.fetch)}},fa=class extends ua{constructor(s,e,t,r,i){super(s,e,i),this.vectorBucketName=t,this.indexName=r}async putVectors(s){var e=()=>super.putVectors,t=this;return e().call(t,k(k({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(s){var e=()=>super.getVectors,t=this;return e().call(t,k(k({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(s={}){var e=()=>super.listVectors,t=this;return e().call(t,k(k({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(s){var e=()=>super.queryVectors,t=this;return e().call(t,k(k({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(s){var e=()=>super.deleteVectors,t=this;return e().call(t,k(k({},s),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},pa=class extends aa{constructor(s,e={},t,r){super(s,e,t,r)}from(s){return new ia(this.url,this.headers,s,this.fetch)}get vectors(){return new ha(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new oa(this.url+"/iceberg",this.headers,this.fetch)}};const ga="2.57.0";let Tt="";typeof Deno<"u"?Tt="deno":typeof document<"u"?Tt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tt="react-native":Tt
23="node";const ya={"X-Client-Info":`supabase-js-${Tt}/${ga}`},va={headers:ya},ma={schema:"public"},ba={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},wa={};var _a=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(h){try{u(r.next(h))}catch(d){a(d)}}function c(h){try{u(r.throw(h))}catch(d){a(d)}}function u(h){h.done?n(h.value):i(h.value).then(o,c)}u((r=r.apply(s,e||[])).next())})};const Sa=s=>{let e;return s?e=s:typeof fetch>"u"?e=pi:e=fetch,(...t)=>e(...t)},ka=()=>typeof Headers>"u"?gi:Headers,Oa=(s,e,t)=>{const r=Sa(t),i=ka();return(n,a)=>_a(void 0,void 0,void 0,function*(){var o;const c=(o=yield e())!==null&&o!==void 0?o:s;let u=new i(a?.headers);return u.has("apikey")||u.set("apikey",s),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},a),{headers:u}))})};var Ea=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(h){try{u(r.next(h))}catch(d){a(d)}}function c(h){try{u(r.throw(h))}catch(d){a(d)}}function u(h){h.done?n(h.value):i(h.value).then(o,c)}u((r=r.apply(s,[])).next())})};function Ta(s){return s.endsWith("/")?s:s+"/"}function Pa(s,e){var t,r;const{db:i,auth:n,realtime:a,global:o}=s,{db:c,auth:u,realtime:h,global:d}=e,f={db:Object.assign(Object.assign({},c),i),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},h),a),storage:{},global:Object.assign(Object.assign(Object.assign({},d),o),{headers:Object.assign(Object.assign({},(t=d?.headers)!==null&&t!==void 0?t:{}),(r=o?.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>Ea(this,void 0,void 0,function*(){return""})};return s.accessToken?f.accessToken=s.accessToken:delete f.accessToken,f}const Pi="2.71.1",it=30*1e3,xs=3,ws=xs*it,Ca="http://localhost:9999",Ra="supabase.auth.token",ja={"X-Client-Info":`gotrue-js/${Pi}`},Is="X-Supabase-Api-Version",Ci={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Aa=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,xa=600*1e3;class cr extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function T(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class Ia extends cr{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function $a(s){return T(s)&&s.name==="AuthApiError"}class Ri extends cr{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}
23class je extends cr{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}}class ye extends je{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Ua(s){return T(s)&&s.name==="AuthSessionMissingError"}class ss extends je{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class rs extends je{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class is extends je{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 Da(s){return T(s)&&s.name==="AuthImplicitGrantRedirectError"}class Dr extends je{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 $s extends je{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function _s(s){return T(s)&&s.name==="AuthRetryableFetchError"}class Lr extends je{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class Us extends je{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const cs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Nr=` 24\r=`.split(""),La=(()=>{const s=new Array(128);for(let e=0;e<s.length;e+=1)s[e]=-1;for(let e=0;e<Nr.length;e+=1)s[Nr[e].charCodeAt(0)]=-2;for(let e=0;e<cs.length;e+=1)s[cs[e].charCodeAt(0)]=e;return s})();function Fr(s,e,t){if(s!==null)for(e.queue=e.queue<<8|s,e.queuedBits+=8;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(cs[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(cs[r]),e.queuedBits-=6}}function ji(s,e,t){const r=La[s];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function Br(s){const e=[],t=a=>{e.push(String.fromCodePoint(a))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=a=>{Ba(a,r,t)};for(let a=0;a<s.length;a+=1)ji(s.charCodeAt(a),i,n);return e.join("")}function Na(s,e){if(s<=127){e(s);return}else if(s<=2047){e(192|s>>6),e(128|s&63);return}else if(s<=65535){e(224|s>>12),e(128|s>>6&63),e(128|s&63);return}else if(s<=1114111){e(240|s>>18),e(128|s>>12&63),e(128|s>>6&63),e(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function Fa(s,e){for(let t=0;t<s.length;t+=1){let r=s.charCodeAt(t);if(r>55295&&r<=56319){const i=(r-55296)*1024&65535;r=(s.charCodeAt(t+1)-56320&65535|i)+65536,t+=1}Na(r,e)}}function Ba(s,e,t){if(e.utf8seq===0){if(s<=127){t(s);return}for(let r=1;r<6;r+=1)if((s>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=s&31;else if(e.utf8seq===3)e.codepoint=s&15;else if(e.utf8seq===4)e.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|s&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function Ma(s){const e=[],t={queue:0,queuedBits:0},r=i=>{e.push(i)};for(let i=0;i<s.length;i+=1)ji(s.charCodeAt(i),t,r);return new Uint8Array(e)}function qa(s){const e=[];return Fa(s,t=>e.push(t)),new Uint8Array(e)}function Qa(s){const e=[],t={queue:0,queuedBits:0},r=i=>{e.push(i)};return s.forEach(i=>Fr(i,t,r)),Fr(null,t,r),e.join("")}function Ka(s){return Math.round(Date.now()/1e3)+s}function Ha(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){const e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}const ee=()=>typeof window<"u"&&typeof document<"u",Ae={tested:!1,writable:!1},Ai=()=>
24{if(!ee())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ae.tested)return Ae.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Ae.tested=!0,Ae.writable=!0}catch{Ae.tested=!0,Ae.writable=!1}return Ae.writable};function Wa(s){const e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}const xi=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>ir(async()=>{const{default:r}=await Promise.resolve().then(()=>ls);return{default:r}},void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Va=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",nt=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},xe=async(s,e)=>{const t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ge=async(s,e)=>{await s.removeItem(e)};class fs{constructor(){this.promise=new fs.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}fs.promiseConstructor=Promise;function Ss(s){const e=s.split(".");if(e.length!==3)throw new Us("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!Aa.test(e[r]))throw new Us("JWT not in base64url format");return{header:JSON.parse(Br(e[0])),payload:JSON.parse(Br(e[1])),signature:Ma(e[2]),raw:{header:e[0],payload:e[1]}}}async function za(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Ga(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{const a=await s(n);if(!e(n,null,a)){r(a);return}}catch(a){if(!e(n,a)){i(a);return}}})()})}function Ja(s){return("0"+s.toString(16)).substr(-2)}function Xa(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length;let i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Ja).join("")}async function Ya(s){const t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}async function Za(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return s;const t=await Ya(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function et(s,e,t=!1){const r=Xa();let i=r;t&&(i+="/PASSWORD_RECOVERY"),await nt(s,`${e}-code-verifier`,i);const n=await Za(r);return[n,r===n?"plain":"s256"]}const eo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function to(s){const e=s.headers.get(Is);if(!e||!e.match(eo))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function so(s){if(!s)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(s<=e)throw new Error("JWT has expired")}function ro(s){switch(s){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 io=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function tt(s){if(!io.test(s))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ks(){const s={};return new Proxy(s,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="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 Mr(s){return JSON.parse(JSON.stringify(s))}var no=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[
vendor: 5,187 bytes, line 24
24i]]);return t};const Ie=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ao=[502,503,504];async function qr(s){var e;if(!Va(s))throw new $s(Ie(s),0);if(ao.includes(s.status))throw new $s(Ie(s),s.status);let t;try{t=await s.json()}catch(n){throw new Ri(Ie(n),n)}let r;const i=to(s);if(i&&i.getTime()>=Ci["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Lr(Ie(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new ye}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,a)=>n&&typeof a=="string",!0))throw new Lr(Ie(t),s.status,t.weak_password.reasons);throw new Ia(Ie(t),s.status||500,r)}const oo=(s,e,t,r)=>{const i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function P(s,e,t,r){var i;const n=Object.assign({},r?.headers);n[Is]||(n[Is]=Ci["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);const a=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(a.redirect_to=r.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await co(s,e,t+o,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function co(s,e,t,r,i,n){const a=oo(e,r,i,n);let o;try{o=await s(t,Object.assign({},a))}catch(c){throw new $s(Ie(c),0)}if(o.ok||await qr(o),r?.noResolveJson)return o;try{return await o.json()}catch(c){await qr(c)}}function oe(s){var e;let t=null;fo(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ka(s.expires_in)));const r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Qr(s){const e=oe(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function me(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function uo(s){return{data:s,error:null}}function lo(s){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,a=no(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},c=Object.assign({},a);return{data:{properties:o,user:c},error:null}}function ho(s){return s}function fo(s){return s.access_token&&s.refresh_token&&s.expires_in}const Os=["global","local","others"];var po=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t};class go{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=xi(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t=Os[0]){if(Os.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Os.join(", ")}`);try{return await P(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await P(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:me})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=po(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await P(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:lo,redirectTo:t?.redirectTo})}catch(t){if(T(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await P(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:me})}catch(t){if(T(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,a,o,c;try{const u={nextPage:null,lastPage:0,total:0},h=await P(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:ho});if(h.error)throw h.error;const d=await h.json(),f=(a=h.headers.get("x-total-count"))!==null&&a!==void 0?a:0,p=(c=(o=h.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return p.length>
240&&(p.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(g.split(";")[1].split("=")[1]);u[`${m}Page`]=y}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){tt(e);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:me})}catch(t){if(T(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){tt(e);try{return await P(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:me})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){tt(e);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:me})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){tt(e.userId);try{const{data:t,error:r}=await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(T(t))return{data:null,error:t};throw t}}async _deleteFactor(e){tt(e.userId),tt(e.id);try{return{data:await P(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(T(t))return{data:null,error:t};throw t}}}function Kr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function yo(){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 st={debug:!!(globalThis&&Ai()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Ii extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class vo extends Ii{}async function mo(s,e,t){st.debug;const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),st.debug},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){st.debug;try{return await t()}finally{st.debug}}else{if(e===0)throw st.debug,new vo(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(st.debug)try{const n=await globalThis.navigator.locks.query()}catch{}return await t()}}))}yo();const bo={url:Ca,storageKey:Ra,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ja,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Hr(s,e,t){return await t()}const rt={};class Ut{constructor(e){var t,r;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=Ut.nextInstanceID,Ut.nextInstanceID+=1,this.instanceID>0&&ee();const i=Object.assign(Object.assign({},bo),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 go({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=xi(i.fetch),this.lock=i.lock||Hr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:ee()&&
24(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=mo:this.lock=Hr,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:Ai()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Kr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Kr(this.memoryStorage)),ee()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch{}(r=this.broadcastChannel)===null||r===void 0||r.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=rt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){rt[this.storageKey]=Object.assign(Object.assign({},rt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=rt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){rt[this.storageKey]=Object.assign(Object.assign({},rt[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Pi}) ${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=Wa(window.location.href);let r="none";if(this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce"),ee()&&this.detectSessionInUrl&&r!=="none"){const{data:i,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),Da(n)){const c=(e=n.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:n}}return await this._removeSession(),{error:n}}const{session:a,redirectType:o}=i;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return T(t)?{error:t}:{error:new Ri("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{const n=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:oe}),{data:a,error:o}=n;if(o||!a)return{data:{user:null,session:null},error:o};const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(T(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){const{email:h,password:d,options:f}=e;let p=null,g=null;this.flowType==="pkce"&&([p,g]=await et(this.storage,this.storageKey)),n=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:h,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:g},xform:oe})}else if("phone"in e){const{phone:h,password:d,options:f}=e;n=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},channel:(i=f?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:oe})}else throw new rs("You must provide either an email or phone number and a password");const{data:a,error:o}=n;
24if(o||!a)return{data:{user:null,session:null},error:o};const c=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(T(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:a,options:o}=e;t=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Qr})}else if("phone"in e){const{phone:n,password:a,options:o}=e;t=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:a,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Qr})}else throw new rs("You must provide either an email or phone number and a password");const{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new ss}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(T(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.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;if(t==="solana")return await this.signInWithSolana(e);throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}async signInWithSolana(e){var t,r,i,n,a,o,c,u,h,d,f,p;let g,y;if("message"in e)g=e.message,y=e.signature;else{const{chain:m,wallet:_,statement:O,options:w}=e;let E;if(ee())if(typeof _=="object")E=_;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"))E=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 _!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=_}const A=new URL((t=w?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in E&&E.signIn){const C=await E.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w?.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),O?{statement:O}:null));let F;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")F=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)F=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in F&&"signature"in F&&(typeof F.signedMessage=="string"||F.signedMessage instanceof Uint8Array)&&F.signature instanceof Uint8Array)g=typeof F.signedMessage=="string"?F.signedMessage:new TextDecoder().decode(F.signedMessage),y=F.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in E)||typeof E.signMessage!="function"||!("publicKey"in E)||typeof E!="object"||!E.publicKey||!("toBase58"in E.publicKey)||typeof E.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${A.host} wants you to sign in with your Solana account:`,E.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(i=(r=w?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((n=w?.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((a=w?.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((o=w?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((c=w?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((u=w?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((d=(h=w?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||d===void 0)&&d.length?["Resources",...w.sign
vendor: 7,470 bytes, lines 24-25
24InWithSolana.resources.map(F=>`- ${F}`)]:[]].join(` 25`);const C=await E.signMessage(new TextEncoder().encode(g),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=C}}try{const{data:m,error:_}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:Qa(y)},!((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:oe});if(_)throw _;return!m||!m.session||!m.user?{data:{user:null,session:null},error:new ss}:(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),{data:Object.assign({},m),error:_})}catch(m){if(T(m))return{data:{user:null,session:null},error:m};throw m}}async _exchangeCodeForSession(e){const t=await xe(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/");try{const{data:n,error:a}=await P(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:oe});if(await ge(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new ss}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:a})}catch(n){if(T(n))return{data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{const{options:t,provider:r,token:i,access_token:n,nonce:a}=e,o=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:oe}),{data:c,error:u}=o;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new ss}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(T(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,a;try{if("email"in e){const{email:o,options:c}=e;let u=null,h=null;this.flowType==="pkce"&&([u,h]=await et(this.storage,this.storageKey));const{error:d}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:u,code_challenge_method:h},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){const{phone:o,options:c}=e,{data:u,error:h}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(a=c?.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:h}}throw new rs("You must provide either an email or phone number.")}catch(o){if(T(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:a,error:o}=await P(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:oe});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const c=a.session,u=a.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(T(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,a=null;return this.flowType==="pkce"&&([n,a]=await et(this.storage,this.storageKey)),await P(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:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r: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:a}),headers:this.headers,xform:uo})}catch(n){if(T(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:r}=e;if(r)throw r;if(!t)throw new ye;const{error:i}=await P(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(T(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:r,type:i,options:n}=e,{error:a}=await P(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if("phone"in e){const{phone:r,type:i,options:n}=e,{data:a,error:o}=await P(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:a?.message_id},error:o}}throw new rs("You must provide either an email or phone number and a type")}catch(t){if(T(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 r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,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 r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}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 xe(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 val
25id"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()<ws:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const a=await xe(this.userStorage,this.storageKey+"-user");a?.user?e.user=a.user:e.user=ks()}if(this.storage.isServer&&e.user){let a=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,u,h)=>(!a&&u==="user"&&(a=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,h))})}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 P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:me}):await this._useSession(async t=>{var r,i,n;const{data:a,error:o}=t;if(o)throw o;return!(!((r=a.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ye}:await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=a.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:me})})}catch(t){if(T(t))return Ua(t)&&(await this._removeSession(),await ge(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 r=>{const{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new ye;const a=i.session;let o=null,c=null;this.flowType==="pkce"&&e.email!=null&&([o,c]=await et(this.storage,this.storageKey));const{data:u,error:h}=await P(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:c}),jwt:a.access_token,xform:me});if(h)throw h;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}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 ye;const t=Date.now()/1e3;let r=t,i=!0,n=null;const{payload:a}=Ss(e.access_token);if(a.exp&&(r=a.exp,i=r<=t),i){const{session:o,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!o)return{data:{user:null,session:null},error:null};n=o}else{const{data:o,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(T(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 r;if(!e){const{data:a,error:o}=t;if(o)throw o;e=(r=a.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new ye;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(T(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!ee())throw new is("No browser detected.");if(e.error||e.error_description||e.error_code)throw new is(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 Dr("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new is("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 Dr("No code detected.");const{data:O,error:w}=await this._exchangeCodeForSession(e.code);
25if(w)throw w;const E=new URL(window.location.href);return E.searchParams.delete("code"),window.history.replaceState(window.history.state,"",E.toString()),{data:{session:O.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:o,expires_at:c,token_type:u}=e;if(!n||!o||!a||!u)throw new is("No session defined in URL");const h=Math.round(Date.now()/1e3),d=parseInt(o);let f=h+d;c&&(f=parseInt(c)),(f-h)*1e3<=it;const g=f-d;h-g>=120||h-g<0;const{data:y,error:m}=await this._getUser(n);if(m)throw m;const _={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:a,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:_,redirectType:e.type},error:null}}catch(r){if(T(r))return{data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await xe(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 r;const{data:i,error:n}=t;if(n)return{error:n};const a=(r=i.session)===null||r===void 0?void 0:r.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!($a(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return e!=="others"&&(await this._removeSession(),await ge(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=Ha(),r={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,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{const{data:{session:n},error:a}=t;if(a)throw a;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.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)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await et(this.storage,this.storageKey,!0));try{return await P(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(T(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(T(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{const{data:r,error:i}=await this._useSession(async n=>{var a,o,c,u,h;const{data:d,error:f}=n;if(f)throw f;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await P(this.fetch,"GET",p,{headers:this.headers,jwt:(h=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&h!==void 0?h:void 0})});if(i)throw i;return ee()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(T(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;const{data:n,error:a}=t;if(a)throw a;
25return await P(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(T(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await Ga(async i=>(i>0&&await za(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await P(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:oe})),(i,n)=>{const a=200*Math.pow(2,i);return n&&_s(n)&&Date.now()+a-r<it})}catch(r){if(this._debug(t,"error",r),T(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),ee()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const i=await xe(this.storage,this.storageKey);if(i&&this.userStorage){let a=await xe(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:i.user},await nt(this.userStorage,this.storageKey+"-user",a)),i.user=(e=a?.user)!==null&&e!==void 0?e:ks()}else if(i&&!i.user&&!i.user){const a=await xe(this.storage,this.storageKey+"-user");a&&a?.user?(i.user=a.user,await ge(this.storage,this.storageKey+"-user"),await nt(this.storage,this.storageKey,i)):i.user=ks()}if(this._debug(r,"session from storage",i),!this._isValidSession(i)){this._debug(r,"session is not valid"),i!==null&&await this._removeSession();return}const n=((t=i.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<ws;if(this._debug(r,`session has${n?"":" not"} expired with margin of ${ws}s`),n){if(this.autoRefreshToken&&i.refresh_token){const{error:a}=await this._callRefreshToken(i.refresh_token);a&&(_s(a)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(i.access_token);!o&&a?.user?(i.user=a.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(a){this._debug(r,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(r,"error",i);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new ye;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new fs;const{data:n,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!n.session)throw new ye;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);const o={session:n.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(n){if(this._debug(i,"error",n),T(n)){const a={session:null,error:n};return _s(n)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(a),n.length>0){for(let o=0;o<n.length;o+=1);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&t.user&&await nt(this.userStorage,this.storageKey+"-user",{user:t.user});const i=Object.assign({},t);delete i.user;const n=Mr(i);await nt(this.storage,this.storageKey,n)}else{const i=Mr(t);await nt(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),await ge(this.storage,this.storageKey),await ge(this.storage,this.storageKey+"-code-verifier"),await ge(this.storage,this.storageKey+"-user"),this.userStorage&&await ge(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ee()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch{}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),it);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:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-e)/it);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${it}ms, refresh threshold is ${xs} ticks`),i<=xs&&await this._callRefreshToken(r.refresh_token)})}catch{}}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()"),!ee()||!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{}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(
25await 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,r){const i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[n,a]=await et(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(a)}`});i.push(o.toString())}if(r?.queryParams){const n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:i,error:n}=t;return n?{data:null,error:n}:await P(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(T(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;const{data:n,error:a}=t;if(a)return{data:null,error:a};const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:c,error:u}=await P(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return u?{data:null,error:u}:(e.factorType==="totp"&&(!((i=c?.totp)===null||i===void 0)&&i.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(t){if(T(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:i,error:n}=t;if(n)return{data:null,error:n};const{data:a,error:o}=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:o})})}catch(t){if(T(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:i,error:n}=t;return n?{data:null,error:n}:await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(T(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}: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 r=e?.factors||[],i=r.filter(a=>a.factor_type==="totp"&&a.status==="verified"),n=r.filter(a=>a.factor_type==="phone"&&a.status==="verified");return{data:{all:r,totp:i,phone:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;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:a}=Ss(i.access_token);let o=null;a.aal&&(o=a.aal);let c=o;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");const h=a.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:h},error:null}}))}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(o=>o.kid===e);if(r)return r;const i=Date.now();if(r=this.jwks.keys.find(o=>
25o.kid===e),r&&this.jwks_cached_at+xa>i)return r;const{data:n,error:a}=await P(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!n.keys||n.keys.length===0||(this.jwks=n,this.jwks_cached_at=i,r=n.keys.find(o=>o.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){const{data:p,error:g}=await this.getSession();if(g||!p.session)return{data:null,error:g};r=p.session.access_token}const{header:i,payload:n,signature:a,raw:{header:o,payload:c}}=Ss(r);t?.allowExpired||so(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(r);if(p)throw p;return{data:{claims:n,header:i,signature:a},error:null}}const h=ro(i.alg),d=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,d,a,qa(`${o}.${c}`)))throw new Us("Invalid JWT signature");return{data:{claims:n,header:i,signature:a},error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}}Ut.nextInstanceID=0;const wo=Ut;class _o extends wo{constructor(e){super(e)}}var So=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(a){a(n)})}return new(t||(t=Promise))(function(n,a){function o(h){try{u(r.next(h))}catch(d){a(d)}}function c(h){try{u(r.throw(h))}catch(d){a(d)}}function u(h){h.done?n(h.value):i(h.value).then(o,c)}u((r=r.apply(s,[])).next())})};class ko{constructor(e,t,r){var i,n,a;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const o=Ta(e),c=new URL(o);this.realtimeUrl=new URL("realtime/v1",c),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",c),this.storageUrl=new URL("storage/v1",c),this.functionsUrl=new URL("functions/v1",c);const u=`sb-${c.hostname.split(".")[0]}-auth-token`,h={db:ma,realtime:wa,auth:Object.assign(Object.assign({},ba),{storageKey:u}),global:va},d=Pa(r??{},h);this.storageKey=(i=d.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=d.global.headers)!==null&&n!==void 0?n:{},d.accessToken?(this.accessToken=d.accessToken,this.auth=new Proxy({},{get:(f,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=d.auth)!==null&&a!==void 0?a:{},this.headers,d.global.fetch),this.fetch=Oa(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},d.realtime)),this.rest=new _n(new URL("rest/v1",c).href,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this.storage=new pa(this.storageUrl.href,this.headers,this.fetch,r?.storage),d.accessToken||this._listenForAuthEvents()}get functions(){return new hn(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={},r={}){return this.rest.rpc(e,t,r)}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 So(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,userStorage:n,storageKey:a,flowType:o,lock:c,debug:u},h,d){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new _o({url:this.authUrl.href,headers:Object.assign(Object.assign({},f),h),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,userStorage:n,flowType:o,lock:c,debug:u,fetch:d,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new Nn(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?this.changedAccessToken=r:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const pc=(s,e,t)=>new ko(s,e,t);function Oo(){if(typeof window<"u"||typeof process>"u")return!1;const s=process.version;if(s==null)return!1;const e=s.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}Oo();var Ve=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(s){return this.listeners.add(s),this.onSubscribe(),()=>{this.listeners.delete(s),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},De,be,at,si,Eo=(si=class extends Ve{constructor(){super();b(this,De);b(this,be);b(this,at);v(this,at,e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}})}onSubscribe(){l(this,be)||this.setEventListener(l(this,at))}onUnsubscribe(){var e;this.hasListeners()||((e=l(this,be))==null||e.call(this),v(this,be,void 0))}setEventListener(e){var t;v(this,at,e),(t=l(this,be))==null||t.call(this),v(this,be,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){l(this,De)!==e&&(v(this,De,e),this.onFocus())}onFocus(){const e=this.isFocused();
25this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof l(this,De)=="boolean"?l(this,De):globalThis.document?.visibilityState!=="hidden"}},De=new WeakMap,be=new WeakMap,at=new WeakMap,si),ur=new Eo,To={setTimeout:(s,e)=>setTimeout(s,e),clearTimeout:s=>clearTimeout(s),setInterval:(s,e)=>setInterval(s,e),clearInterval:s=>clearInterval(s)},we,rr,ri,Po=(ri=class{constructor(){b(this,we,To);b(this,rr,!1)}setTimeoutProvider(s){v(this,we,s)}setTimeout(s,e){return l(this,we).setTimeout(s,e)}clearTimeout(s){l(this,we).clearTimeout(s)}setInterval(s,e){return l(this,we).setInterval(s,e)}clearInterval(s){l(this,we).clearInterval(s)}},we=new WeakMap,rr=new WeakMap,ri),Ue=new Po;function Co(s){setTimeout(s,0)}var Ro=typeof window>"u"||"Deno"in globalThis;function D(){}function jo(s,e){return typeof s=="function"?s(e):s}function Ds(s){return typeof s=="number"&&s>=0&&s!==1/0}function $i(s,e){return Math.max(s+(e||0)-Date.now(),0)}function Re(s,e){return typeof s=="function"?s(e):s}function J(s,e){return typeof s=="function"?s(e):s}function Wr(s,e){const{type:t="all",exact:r,fetchStatus:i,predicate:n,queryKey:a,stale:o}=s;if(a){if(r){if(e.queryHash!==lr(a,e.options))return!1}else if(!Dt(e.queryKey,a))return!1}if(t!=="all"){const c=e.isActive();if(t==="active"&&!c||t==="inactive"&&c)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||i&&i!==e.state.fetchStatus||n&&!n(e))}function Vr(s,e){const{exact:t,status:r,predicate:i,mutationKey:n}=s;if(n){if(!e.options.mutationKey)return!1;if(t){if(We(e.options.mutationKey)!==We(n))return!1}else if(!Dt(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}function lr(s,e){return(e?.queryKeyHashFn||We)(s)}function We(s){return JSON.stringify(s,(e,t)=>Ls(t)?Object.keys(t).sort().reduce((r,i)=>(r[i]=t[i],r),{}):t)}function Dt(s,e){return s===e?!0:typeof s!=typeof e?!1:s&&e&&typeof s=="object"&&typeof e=="object"?Object.keys(e).every(t=>Dt(s[t],e[t])):!1}var Ao=Object.prototype.hasOwnProperty;function hr(s,e,t=0){if(s===e)return s;if(t>500)return e;const r=zr(s)&&zr(e);if(!r&&!(Ls(s)&&Ls(e)))return e;const n=(r?s:Object.keys(s)).length,a=r?e:Object.keys(e),o=a.length,c=r?new Array(o):{};let u=0;for(let h=0;h<o;h++){const d=r?h:a[h],f=s[d],p=e[d];if(f===p){c[d]=f,(r?h<n:Ao.call(s,d))&&u++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[d]=p;continue}const g=hr(f,p,t+1);c[d]=g,g===f&&u++}return n===o&&u===n?s:c}function Lt(s,e){if(!e||Object.keys(s).length!==Object.keys(e).length)return!1;for(const t in s)if(s[t]!==e[t])return!1;return!0}function zr(s){return Array.isArray(s)&&s.length===Object.keys(s).length}function Ls(s){if(!Gr(s))return!1;const e=s.constructor;if(e===void 0)return!0;const t=e.prototype;return!(!Gr(t)||!t.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(s)!==Object.prototype)}function Gr(s){return Object.prototype.toString.call(s)==="[object Object]"}function xo(s){return new Promise(e=>{Ue.setTimeout(e,s)})}function Ns(s,e,t){return typeof t.structuralSharing=="function"?t.structuralSharing(s,e):t.structuralSharing!==!1?hr(s,e):e}function gc(s){return s}function Io(s,e,t=0){const r=[...s,e];return t&&r.length>t?r.slice(1):r}function $o(s,e,t=0){const r=[e,...s];return t&&r.length>t?r.slice(0,-1):r}var dr=Symbol();function Ui(s,e){return!s.queryFn&&e?.initialPromise?()=>e.initialPromise:!s.queryFn||s.queryFn===dr?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function fr(s,e){return typeof s=="function"?s(...e):!!s}function Uo(s,e,t){let r=!1,i;return Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(i??(i=e()),r||(r=!0,i.aborted?t():i.addEventListener("abort",t,{once:!0})),i)}),s}var Nt=(()=>{let s=()=>Ro;return{isServer(){return s()},setIsServer(e){s=e}}})();function Fs(){let s,e;const t=new Promise((i,n)=>{s=i,e=n});t.status="pending",t.catch(()=>{});function r(i){Object.assign(t,i),delete t.resolve,delete t.reject}return t.resolve=i=>{r({status:"fulfilled",value:i}),s(i)},t.reject=i=>{r({status:"rejected",reason:i}),e(i)},t}function Do(s){let e;if(s.then(t=>(e=t,t),D)?.catch(D),e!==void 0)return{data:e}}function Di(s){return s}function Lo(s){return{mutationKey:s.options.mutationKey,state:s.state,...s.options.scope&&{scope:s.options.scope},...s.meta&&{meta:s.meta}}}function No(s,e,t){const r=()=>{const i=s.promise?.then(e).catch(n=>t(n)?Promise.reject(new Error("redacted")):Promise.reject(n));return i?.catch(D),i};return{dehydratedAt:Date.now(),state:{...s.state,...s.state.data!==void 0&&{data:e(s.state.data)}},queryKey:s.queryKey,queryHash:s.queryHash,...s.state.status==="pending"&&{promise:r()},...s.meta&&{meta:s.meta},...s.queryType&&{queryType:s.queryType}}}
25function Fo(s){return s.state.isPaused}function Bo(s){return s.state.status==="success"}function Mo(s){return!0}function yc(s,e={}){const t=e.shouldDehydrateMutation??s.getDefaultOptions().dehydrate?.shouldDehydrateMutation??Fo,r=s.getMutationCache().getAll().flatMap(c=>t(c)?[Lo(c)]:[]),i=e.shouldDehydrateQuery??s.getDefaultOptions().dehydrate?.shouldDehydrateQuery??Bo,n=e.shouldRedactErrors??s.getDefaultOptions().dehydrate?.shouldRedactErrors??Mo,a=e.serializeData??s.getDefaultOptions().dehydrate?.serializeData??Di,o=s.getQueryCache().getAll().flatMap(c=>i(c)?[No(c,a,n)]:[]);return{mutations:r,queries:o}}function vc(s,e,t){if(typeof e!="object"||e===null)return;const r=s.getMutationCache(),i=s.getQueryCache(),n=t?.defaultOptions?.deserializeData??s.getDefaultOptions().hydrate?.deserializeData??Di,a=e.mutations||[],o=e.queries||[];a.forEach(({state:c,...u})=>{r.build(s,{...s.getDefaultOptions().hydrate?.mutations,...t?.defaultOptions?.mutations,...u},c)}),o.forEach(({queryKey:c,state:u,queryHash:h,meta:d,promise:f,dehydratedAt:p,queryType:g})=>{const y=f?Do(f):void 0,m=u.data===void 0?y?.data:u.data,_=m===void 0?m:n(m);let O=i.get(h);const w=O?.state.status==="pending",E=O?.state.fetchStatus==="fetching";if(O){const A=y&&p!==void 0&&p>O.state.dataUpdatedAt;if(u.dataUpdatedAt>O.state.dataUpdatedAt||A){const{fetchStatus:C,...F}=u;O.setState({...F,data:_,...u.status==="pending"&&_!==void 0&&{status:"success",dataUpdatedAt:p??Date.now(),...!E&&{fetchStatus:"idle"}}})}}else O=i.build(s,{...s.getDefaultOptions().hydrate?.queries,...t?.defaultOptions?.queries,queryKey:c,queryHash:h,meta:d,_type:g},{...u,data:_,fetchStatus:"idle",status:u.status==="pending"&&_!==void 0?"success":u.status,...u.status==="pending"&&_!==void 0&&{dataUpdatedAt:p??Date.now()}});f&&!y&&!w&&!E&&(p===void 0||p>O.state.dataUpdatedAt)&&O.fetch(void 0,{initialPromise:Promise.resolve(f).then(n)}).catch(D)})}var qo=Co;function Qo(){let s=[],e=0,t=o=>{o()},r=o=>{o()},i=qo;const n=o=>{e?s.push(o):i(()=>{t(o)})},a=()=>{const o=s;s=[],o.length&&i(()=>{r(()=>{o.forEach(c=>{t(c)})})})};return{batch:o=>{let c;e++;try{c=o()}finally{e--,e||a()}return c},batchCalls:o=>(...c)=>{n(()=>{o(...c)})},schedule:n,setNotifyFunction:o=>{t=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{i=o}}}var $=Qo(),ot,_e,ct,ii,Ko=(ii=class extends Ve{constructor(){super();b(this,ot,!0);b(this,_e);b(this,ct);v(this,ct,e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}})}onSubscribe(){l(this,_e)||this.setEventListener(l(this,ct))}onUnsubscribe(){var e;this.hasListeners()||((e=l(this,_e))==null||e.call(this),v(this,_e,void 0))}setEventListener(e){var t;v(this,ct,e),(t=l(this,_e))==null||t.call(this),v(this,_e,e(this.setOnline.bind(this)))}setOnline(e){l(this,ot)!==e&&(v(this,ot,e),this.listeners.forEach(r=>{r(e)}))}isOnline(){return l(this,ot)}},ot=new WeakMap,_e=new WeakMap,ct=new WeakMap,ii),us=new Ko;function Ho(s){return Math.min(1e3*2**s,3e4)}function Li(s){return(s??"online")==="online"?us.isOnline():!0}var Bs=class extends Error{constructor(s){super("CancelledError"),this.revert=s?.revert,this.silent=s?.silent}};function Ni(s){let e=!1,t=0,r;const i=Fs(),n=()=>i.status!=="pending",a=y=>{if(!n()){const m=new Bs(y);f(m),s.onCancel?.(m)}},o=()=>{e=!0},c=()=>{e=!1},u=()=>ur.isFocused()&&(s.networkMode==="always"||us.isOnline())&&s.canRun(),h=()=>Li(s.networkMode)&&s.canRun(),d=y=>{n()||(r?.(),i.resolve(y))},f=y=>{n()||(r?.(),i.reject(y))},p=()=>new Promise(y=>{r=m=>{(n()||u())&&y(m)},s.onPause?.()}).then(()=>{r=void 0,n()||s.onContinue?.()}),g=()=>{if(n())return;let y;const m=t===0?s.initialPromise:void 0;try{y=m??s.fn()}catch(_){y=Promise.reject(_)}Promise.resolve(y).then(d).catch(_=>{if(n())return;const O=s.retry??(Nt.isServer()?0:3),w=s.retryDelay??Ho,E=typeof w=="function"?w(t,_):w,A=O===!0||typeof O=="number"&&t<O||typeof O=="function"&&O(t,_);if(e||!A){f(_);return}t++,s.onFail?.(t,_),xo(E).then(()=>u()?void 0:p()).then(()=>{e?f(_):g()})})};return{promise:i,status:()=>i.status,cancel:a,continue:()=>(r?.(),i),cancelRetry:o,continueRetry:c,canStart:h,start:()=>(h()?g():p().then(g),i)}}var Le,ni,Fi=(ni=class{constructor(){b(this,Le)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ds(this.gcTime)&&v(this,Le,Ue.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(Nt.isServer()?1/0:300*1e3))}clearGcTimeout(){l(this,Le)!==void 0&&(Ue.clearTimeout(l(this,Le)),v(this,Le,void 0))}},Le=new WeakMap,ni);function Wo(s){return{onFetch:(e,t)=>
25{const r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],a=e.state.data?.pageParams||[];let o={pages:[],pageParams:[]},c=0;const u=async()=>{let h=!1;const d=g=>{Uo(g,()=>e.signal,()=>h=!0)},f=Ui(e.options,e.fetchOptions),p=async(g,y,m)=>{if(h)return Promise.reject(e.signal.reason);if(y==null&&g.pages.length)return Promise.resolve(g);const O=(()=>{const C={client:e.client,queryKey:e.queryKey,pageParam:y,direction:m?"backward":"forward",meta:e.options.meta};return d(C),C})(),w=await f(O),{maxPages:E}=e.options,A=m?$o:Io;return{pages:A(g.pages,w,E),pageParams:A(g.pageParams,y,E)}};if(i&&n.length){const g=i==="backward",y=g?Vo:Jr,m={pages:n,pageParams:a},_=y(r,m);o=await p(m,_,g)}else{const g=s??n.length;do{const y=c===0?a[0]??r.initialPageParam:Jr(r,o);if(c>0&&y==null)break;o=await p(o,y),c++}while(c<g)}return o};e.options.persister?e.fetchFn=()=>e.options.persister?.(u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},t):e.fetchFn=u}}}function Jr(s,{pages:e,pageParams:t}){const r=e.length-1;return e.length>0?s.getNextPageParam(e[r],e,t[r],t):void 0}function Vo(s,{pages:e,pageParams:t}){return e.length>0?s.getPreviousPageParam?.(e[0],e,t[0],t):void 0}var ut,Ne,lt,Z,Fe,M,Ft,Be,G,Bi,ce,ai,zo=(ai=class extends Fi{constructor(e){super();b(this,G);b(this,ut);b(this,Ne);b(this,lt);b(this,Z);b(this,Fe);b(this,M);b(this,Ft);b(this,Be);v(this,Be,!1),v(this,Ft,e.defaultOptions),this.setOptions(e.options),this.observers=[],v(this,Fe,e.client),v(this,Z,l(this,Fe).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,v(this,Ne,Yr(this.options)),this.state=e.state??l(this,Ne),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return l(this,ut)}get promise(){return l(this,M)?.promise}setOptions(e){if(this.options={...l(this,Ft),...e},e?._type&&v(this,ut,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Yr(this.options);t.data!==void 0&&(this.setState(Xr(t.data,t.dataUpdatedAt)),v(this,Ne,t))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Z).remove(this)}setData(e,t){const r=Ns(this.state.data,e,this.options);return S(this,G,ce).call(this,{data:r,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),r}setState(e){S(this,G,ce).call(this,{type:"setState",state:e})}cancel(e){const t=l(this,M)?.promise;return l(this,M)?.cancel(e),t?t.then(D).catch(D):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Ne)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>J(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===dr||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Re(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:!$i(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,M)?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,M)?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),l(this,Z).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(l(this,M)&&(l(this,Be)||S(this,G,Bi).call(this)?l(this,M).cancel({revert:!0}):l(this,M).cancelRetry()),this.scheduleGc()),l(this,Z).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||S(this,G,ce).call(this,{type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&l(this,M)?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(l(this,M))return l(this,M).continueRetry(),l(this,M).promise}if(e&&this.setOptions(e),!this.options.queryFn){const u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}const r=new AbortController,i=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(v(this,Be,!0),r.signal)}
25)},n=()=>{const u=Ui(this.options,t),d=(()=>{const f={client:l(this,Fe),queryKey:this.queryKey,meta:this.meta};return i(f),f})();return v(this,Be,!1),this.options.persister?this.options.persister(u,d,this):u(d)},o=(()=>{const u={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:l(this,Fe),state:this.state,fetchFn:n};return i(u),u})();(l(this,ut)==="infinite"?Wo(this.options.pages):this.options.behavior)?.onFetch(o,this),v(this,lt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&S(this,G,ce).call(this,{type:"fetch",meta:o.fetchOptions?.meta}),v(this,M,Ni({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:u=>{u instanceof Bs&&u.revert&&this.setState({...l(this,lt),fetchStatus:"idle"}),r.abort()},onFail:(u,h)=>{S(this,G,ce).call(this,{type:"failed",failureCount:u,error:h})},onPause:()=>{S(this,G,ce).call(this,{type:"pause"})},onContinue:()=>{S(this,G,ce).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const u=await l(this,M).start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),l(this,Z).config.onSuccess?.(u,this),l(this,Z).config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Bs){if(u.silent)return l(this,M).promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw S(this,G,ce).call(this,{type:"error",error:u}),l(this,Z).config.onError?.(u,this),l(this,Z).config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}},ut=new WeakMap,Ne=new WeakMap,lt=new WeakMap,Z=new WeakMap,Fe=new WeakMap,M=new WeakMap,Ft=new WeakMap,Be=new WeakMap,G=new WeakSet,Bi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},ce=function(e){const t=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Mi(r.data,this.options),fetchMeta:e.meta??null};case"success":const i={...r,...Xr(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return v(this,lt,e.manual?i:void 0),i;case"error":const n=e.error;return{...r,error:n,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=t(this.state),$.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Z).notify({query:this,type:"updated",action:e})})},ai);function Mi(s,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Li(e.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function Xr(s,e){return{data:s,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Yr(s){const e=typeof s.initialData=="function"?s.initialData():s.initialData,t=e!==void 0,r=t?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:t?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:t?"success":"pending",fetchStatus:"idle"}}var H,R,Bt,K,Me,ht,le,Se,Mt,dt,ft,qe,Qe,ke,pt,j,Pt,Ms,qs,Qs,Ks,Hs,Ws,Vs,qi,oi,pr=(oi=class extends Ve{constructor(e,t){super();b(this,j);b(this,H);b(this,R);b(this,Bt);b(this,K);b(this,Me);b(this,ht);b(this,le);b(this,Se);b(this,Mt);b(this,dt);b(this,ft);b(this,qe);b(this,Qe);b(this,ke);b(this,pt,new Set);this.options=t,v(this,H,e),v(this,Se,null),v(this,le,Fs()),this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,R).addObserver(this),Zr(l(this,R),this.options)?S(this,j,Pt).call(this):this.updateResult(),S(this,j,Ks).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zs(l(this,R),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zs(l(this,R),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,S(this,j,Hs).call(this),S(this,j,Ws).call(this),l(this,R).removeObserver(this)}setOptions(e){const t=this.options,r=l(this,R);if(this.options=l(this,H).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof J(this.options.enabled,l(this,R))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");S(this,j,Vs).call(this),l(this,R).setOptions(this.options),t._defaulted&&!Lt(this.options,t)&&l(this,H).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,R),observer:this});const i=this.hasListeners();i&&ei(l(this,R),r,this.options,t)&&S(this,j,Pt).call(this),this.updateResult(),i&&(l(this,R)!==r||J(this.options.enabled,l(this,R))!==J(t.enabled,l(this,R))||Re(this.options.staleTime,l(this,R))!==Re(t.staleTime,l(this,R)))&&S(this,j,Ms).call(this);const n=S(this,j,qs).call(this);i&&(l(this,R)!==r||J(this.options.enabled,l(this,R))!==J(t.enabled,l(this,R))||n!==l(this,ke))&&S(this,j,Qs).call(this,n)}getOptimisticResult(e){const t=l(this,H).getQueryCache().build(l(this,H),e),r=this.createResult(t,e);return Jo(this,r)&&(v(this,K,r),v(this,ht,this.options),v(this,Me,l(this,R).state)),r}getCurrentResult(){return l(this,K)}trackResult(e,t){return new Proxy(e,{get:(r,i)=>(this.trackProp(i),t?.(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,le).status==="pending"&&l(this,le).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,i))})}trackProp(e){l(this,pt).add(e)}getCurrentQuery(){return l(this,R)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=l(this,H).defaultQueryOptions(e),r=l(this,H).getQueryCache().build(l(this,H),t);return r.fetch().then(()=>this.createResult(r,t))}fetch(e){return S(this,j,Pt).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,K)))}createResult(e,t){const r=l(this,R),i=this.options,n=l(this,K),a=l(this,Me),o=l(this,ht),u=e!==r?e.state:l(this,Bt),{state:h}=e;let d={...h},f=!1,p;if(t._optimisticResults){const Y=this.hasListeners(),kt=!Y&&Zr(e,t),Gt=Y&&ei(e,r,t,i);(kt||Gt)&&(d={...d,...Mi(h.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:g,errorUpdatedAt:y,status:m}=d;p=d.data;let _=!1;if(t.placeholderData!==void 0&&p===void 0&&m==="pending"){let Y;n?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(Y=n.data,_=!0):Y=typeof t.placeholderData=="function"?t.placeholderData(l(this,ft)?.state.data,l(this,ft)):t.placeholderData,Y!==void 0&&(m="success",p=Ns(n?.data,Y,t),f=!0)}if(t.select&&p!==void 0&&!_)if(n&&p===a?.data&&t.select===l(this,Mt))p=l(this,dt);else try{v(this,Mt,t.select),p=t.select(p),p=Ns(n?.data,p,t),v(this,dt,p),v(this,Se,null)}catch(Y){v(this,Se,Y)}l(this,Se)&&(g=l(this,Se),p=l(this,dt),y=Date.now(),m="error");const O=d.fetchStatus==="fetching",w=m==="pending",E=m==="error",A=w&&O,C=p!==void 0,Q={status:m,fetchStatus:d.fetchStatus,isPending:w,isSuccess:m==="success",isError:E,isInitialLoading:A,isLoading:A,data:p,dataUpdatedAt:d.dataUpdatedAt,error:g,errorUpdatedAt:y,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdate
25Count:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:O,isRefetching:O&&!w,isLoadingError:E&&!C,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:E&&C,isStale:gr(e,t),refetch:this.refetch,promise:l(this,le),isEnabled:J(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const Y=Q.data!==void 0,kt=Q.status==="error"&&!Y,Gt=Xt=>{kt?Xt.reject(Q.error):Y&&Xt.resolve(Q.data)},yr=()=>{const Xt=v(this,le,Q.promise=Fs());Gt(Xt)},Jt=l(this,le);switch(Jt.status){case"pending":e.queryHash===r.queryHash&&Gt(Jt);break;case"fulfilled":(kt||Q.data!==Jt.value)&&yr();break;case"rejected":(!kt||Q.error!==Jt.reason)&&yr();break}}return Q}updateResult(){const e=l(this,K),t=this.createResult(l(this,R),this.options);if(v(this,Me,l(this,R).state),v(this,ht,this.options),l(this,Me).data!==void 0&&v(this,ft,l(this,R)),Lt(t,e))return;v(this,K,t);const r=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,n=typeof i=="function"?i():i;if(n==="all"||!n&&!l(this,pt).size)return!0;const a=new Set(n??l(this,pt));return this.options.throwOnError&&a.add("error"),Object.keys(l(this,K)).some(o=>{const c=o;return l(this,K)[c]!==e[c]&&a.has(c)})};S(this,j,qi).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&S(this,j,Ks).call(this)}},H=new WeakMap,R=new WeakMap,Bt=new WeakMap,K=new WeakMap,Me=new WeakMap,ht=new WeakMap,le=new WeakMap,Se=new WeakMap,Mt=new WeakMap,dt=new WeakMap,ft=new WeakMap,qe=new WeakMap,Qe=new WeakMap,ke=new WeakMap,pt=new WeakMap,j=new WeakSet,Pt=function(e){S(this,j,Vs).call(this);let t=l(this,R).fetch(this.options,e);return e?.throwOnError||(t=t.catch(D)),t},Ms=function(){S(this,j,Hs).call(this);const e=Re(this.options.staleTime,l(this,R));if(Nt.isServer()||l(this,K).isStale||!Ds(e))return;const r=$i(l(this,K).dataUpdatedAt,e)+1;v(this,qe,Ue.setTimeout(()=>{l(this,K).isStale||this.updateResult()},r))},qs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,R)):this.options.refetchInterval)??!1},Qs=function(e){S(this,j,Ws).call(this),v(this,ke,e),!(Nt.isServer()||J(this.options.enabled,l(this,R))===!1||!Ds(l(this,ke))||l(this,ke)===0)&&v(this,Qe,Ue.setInterval(()=>{(this.options.refetchIntervalInBackground||ur.isFocused())&&S(this,j,Pt).call(this)},l(this,ke)))},Ks=function(){S(this,j,Ms).call(this),S(this,j,Qs).call(this,S(this,j,qs).call(this))},Hs=function(){l(this,qe)!==void 0&&(Ue.clearTimeout(l(this,qe)),v(this,qe,void 0))},Ws=function(){l(this,Qe)!==void 0&&(Ue.clearInterval(l(this,Qe)),v(this,Qe,void 0))},Vs=function(){const e=l(this,H).getQueryCache().build(l(this,H),this.options);if(e===l(this,R))return;const t=l(this,R);v(this,R,e),v(this,Bt,e.state),this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))},qi=function(e){$.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(l(this,K))}),l(this,H).getQueryCache().notify({query:l(this,R),type:"observerResultsUpdated"})})},oi);function Go(s,e){return J(e.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&J(e.retryOnMount,s)===!1)}function Zr(s,e){return Go(s,e)||s.state.data!==void 0&&zs(s,e,e.refetchOnMount)}function zs(s,e,t){if(J(e.enabled,s)!==!1&&Re(e.staleTime,s)!=="static"){const r=typeof t=="function"?t(s):t;return r==="always"||r!==!1&&gr(s,e)}return!1}function ei(s,e,t,r){return(s!==e||J(r.enabled,s)===!1)&&(!t.suspense||s.state.status!=="error")&&gr(s,t)}function gr(s,e){return J(e.enabled,s)!==!1&&s.isStaleByTime(Re(e.staleTime,s))}function Jo(s,e){return!Lt(s.getCurrentResult(),e)}var qt,ie,q,Ke,ne,ve,ci,Xo=(ci=class extends Fi{constructor(e){super();b(this,ne);b(this,qt);b(this,ie);b(this,q);b(this,Ke);v(this,qt,e.client),this.mutationId=e.mutationId,v(this,q,e.mutationCache),v(this,ie,[]),this.state=e.state||Qi(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){l(this,ie).includes(e)||(l(this,ie).push(e),this.clearGcTimeout(),l(this,q).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){v(this,ie,l(this,ie).filter(t=>t!==e)),this.scheduleGc(),l(this,q).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){l(this,ie).length||(this.state.status==="pending"?this.scheduleGc():l(this,q).remove(this))}continue(){return l(this,Ke)?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{S(this,ne,ve).call(this,{type:"continue"})},r={client:l(this,qt),meta:this.options.meta,mutationKey:this.options.mutationKey};v(this,Ke,Ni({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{S(this,ne,ve).call(this,{type:"failed",failureCount:a,error:o})},onPause:()=>{S(this,ne,ve).call(this,{type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,q).canRun(this)}));const i=this.state.status==="pending",n=!l(this,Ke).canStart();try{if(i)t();else{S(this,ne,ve).call(this,{type:"pending",variables:e,isPaused:n}),l(this,q).config.onMutate&&await l(this,q).config.onMutate(e,this,r);const o=await this.options.onMutate?.(e,r);o!==this.state.context&&S(this,ne,ve).call(this,{type:"pending",context:o,variables:e,isPaused:n})}const a=await l(this,Ke).start();return await l(this,q).config.onSuccess?.(a,e,this.state.context,this,r),await this.options.onSuccess?.(a,e,this.state.context,r),await l(this,q).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,e,this.state.context,r),S(this,ne,ve).call(this,{type:"success",data:a}),a}catch(a){try{await l(this,q).config.onError?.(a,e,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,e,this.state.context,r)}catch(o){Promise.reject(o)}try{await l(this,q).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,r)}catch(o){Promise.reject(o)}throw S(this,ne,ve).call(this,{type:"error",error:a}),a}finally{l(this,q).runNext(this)}}},qt=new WeakMap,ie=new WeakMap,q=new WeakMap,Ke=new WeakMap,ne=new WeakSet,ve=function(e){const t=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};
25case"pending":return{...r,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{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),$.batch(()=>{l(this,ie).forEach(r=>{r.onMutationUpdate(e)}),l(this,q).notify({mutation:this,type:"updated",action:e})})},ci);function Qi(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var he,se,Qt,ui,Yo=(ui=class extends Ve{constructor(e={}){super();b(this,he);b(this,se);b(this,Qt);this.config=e,v(this,he,new Set),v(this,se,new Map),v(this,Qt,0)}build(e,t,r){const i=new Xo({client:e,mutationCache:this,mutationId:++Yt(this,Qt)._,options:e.defaultMutationOptions(t),state:r});return this.add(i),i}add(e){l(this,he).add(e);const t=ns(e);if(typeof t=="string"){const r=l(this,se).get(t);r?r.push(e):l(this,se).set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(l(this,he).delete(e)){const t=ns(e);if(typeof t=="string"){const r=l(this,se).get(t);if(r)if(r.length>1){const i=r.indexOf(e);i!==-1&&r.splice(i,1)}else r[0]===e&&l(this,se).delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=ns(e);if(typeof t=="string"){const i=l(this,se).get(t)?.find(n=>n.state.status==="pending");return!i||i===e}else return!0}runNext(e){const t=ns(e);return typeof t=="string"?l(this,se).get(t)?.find(i=>i!==e&&i.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){$.batch(()=>{l(this,he).forEach(e=>{this.notify({type:"removed",mutation:e})}),l(this,he).clear(),l(this,se).clear()})}getAll(){return Array.from(l(this,he))}find(e){const t={exact:!0,...e};return this.getAll().find(r=>Vr(t,r))}findAll(e={}){return this.getAll().filter(t=>Vr(e,t))}notify(e){$.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>
25t.state.isPaused);return $.batch(()=>Promise.all(e.map(t=>t.continue().catch(D))))}},he=new WeakMap,se=new WeakMap,Qt=new WeakMap,ui);function ns(s){return s.options.scope?.id}var de,Oe,W,fe,pe,as,Gs,li,Zo=(li=class extends Ve{constructor(e,t){super();b(this,pe);b(this,de);b(this,Oe);b(this,W);b(this,fe);v(this,de,e),this.setOptions(t),this.bindMethods(),S(this,pe,as).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=l(this,de).defaultMutationOptions(e),Lt(this.options,t)||l(this,de).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,W),observer:this}),t?.mutationKey&&this.options.mutationKey&&We(t.mutationKey)!==We(this.options.mutationKey)?this.reset():l(this,W)?.state.status==="pending"&&l(this,W).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,W)?.removeObserver(this)}onMutationUpdate(e){S(this,pe,as).call(this),S(this,pe,Gs).call(this,e)}getCurrentResult(){return l(this,Oe)}reset(){l(this,W)?.removeObserver(this),v(this,W,void 0),S(this,pe,as).call(this),S(this,pe,Gs).call(this)}mutate(e,t){return v(this,fe,t),l(this,W)?.removeObserver(this),v(this,W,l(this,de).getMutationCache().build(l(this,de),this.options)),l(this,W).addObserver(this),l(this,W).execute(e)}},de=new WeakMap,Oe=new WeakMap,W=new WeakMap,fe=new WeakMap,pe=new WeakSet,as=function(){const e=l(this,W)?.state??Qi();v(this,Oe,{...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){$.batch(()=>{if(l(this,fe)&&this.hasListeners()){const t=l(this,Oe).variables,r=l(this,Oe).context,i={client:l(this,de),meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{l(this,fe).onSuccess?.(e.data,t,r,i)}catch(n){Promise.reject(n)}try{l(this,fe).onSettled?.(e.data,null,t,r,i)}catch(n){Promise.reject(n)}}else if(e?.type==="error"){try{l(this,fe).onError?.(e.error,t,r,i)}catch(n){Promise.reject(n)}try{l(this,fe).onSettled?.(void 0,e.error,t,r,i)}catch(n){Promise.reject(n)}}}this.listeners.forEach(t=>{t(l(this,Oe))})})},li);function ti(s,e){const t=new Set(e);return s.filter(r=>!t.has(r))}function ec(s,e,t){const r=s.slice(0);return r[e]=t,r}var gt,V,yt,He,z,Ee,Kt,Ht,Wt,Vt,N,Js,Xs,Ki,Ys,Zs,er,hi,tc=(hi=class extends Ve{constructor(e,t,r){super();b(this,N);b(this,gt);b(this,V);b(this,yt);b(this,He);b(this,z);b(this,Ee);b(this,Kt);b(this,Ht);b(this,Wt);b(this,Vt,[]);v(this,gt,e),v(this,He,r),v(this,yt,[]),v(this,z,[]),v(this,V,[]),this.setQueries(t)}onSubscribe(){this.listeners.size===1&&l(this,z).forEach(e=>{e.subscribe(t=>{S(this,N,Zs).call(this,e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,l(this,z).forEach(e=>{e.destroy()})}setQueries(e,t){v(this,yt,e),v(this,He,t),$.batch(()=>{const r=l(this,z),i=S(this,N,Ys).call(this,l(this,yt));i.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const n=i.map(d=>d.observer),a=n.map(d=>d.getCurrentResult()),o=r.length!==n.length,c=n.some((d,f)=>d!==r[f]),u=o||c,h=u?!0:a.some((d,f)=>{const p=l(this,V)[f];return!p||!Lt(d,p)});!u&&!h||(u&&(v(this,Vt,i),v(this,z,n)),v(this,V,a),this.hasListeners()&&(u&&(ti(r,n).forEach(d=>{d.destroy()}),ti(n,r).forEach(d=>{d.subscribe(f=>{S(this,N,Zs).call(this,d,f)})})),S(this,N,er).call(this)))})}getCurrentResult(){return l(this,V)}getQueries(){return l(this,z).map(e=>e.getCurrentQuery())}getObservers(){return l(this,z)}getOptimisticResult(e,t){const r=S(this,N,Ys).call(this,e),i=r.map(a=>a.observer.getOptimisticResult(a.defaultedQueryOptions)),n=r.map(a=>a.defaultedQueryOptions.queryHash);return[i,a=>S(this,N,Xs).call(this,a??i,t,n),()=>S(this,N,Js).call(this,i,r)]}},gt=new WeakMap,V=new WeakMap,yt=new WeakMap,He=new WeakMap,z=new WeakMap,Ee=new WeakMap,Kt=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Vt=new WeakMap,N=new WeakSet,Js=function(e,t){return t.map((r,i)=>{const n=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?n:r.observer.trackResult(n,a=>{t.forEach(o=>{o.observer.trackProp(a)})})})},Xs=function(e,t,r){if(t){const i=l(this,Wt),n=r!==void 0&&i!==void 0&&(i.length!==r.length||r.some((a,o)=>a!==i[o]));return(!l(this,Ee)||l(this,V)!==l(this,Ht)||n||t!==l(this,Kt))&&(v(this,Kt,t),v(this,Ht,l(this,V)),r!==void 0&&v(this,Wt,r),v(this,Ee,hr(l(this,Ee),t(e)))),l(this,Ee)}return e},Ki=function(){return l(this,He)?.combine!==void 0&&l(this,z).some((e,t)=>e.options.suspense&&l(this,V)[t]?.data===void 0)},Ys=function(e){const t=new Map;l(this,z).forEach(i=>
25{const n=i.options.queryHash;if(!n)return;const a=t.get(n);a?a.push(i):t.set(n,[i])});const r=[];return e.forEach(i=>{const n=l(this,gt).defaultQueryOptions(i),o=t.get(n.queryHash)?.shift()??new pr(l(this,gt),n);r.push({defaultedQueryOptions:n,observer:o})}),r},Zs=function(e,t){const r=l(this,z).indexOf(e);r!==-1&&(v(this,V,ec(l(this,V),r,t)),S(this,N,er).call(this))},er=function(){if(this.hasListeners()){const e=S(this,N,Js).call(this,l(this,V),l(this,Vt)),t=S(this,N,Ki).call(this),r=l(this,Ee),i=t?r:S(this,N,Xs).call(this,e,l(this,He)?.combine);(t||r!==i)&&$.batch(()=>{this.listeners.forEach(n=>{n(l(this,V))})})}},hi),ae,di,sc=(di=class extends Ve{constructor(e={}){super();b(this,ae);this.config=e,v(this,ae,new Map)}build(e,t,r){const i=t.queryKey,n=t.queryHash??lr(i,t);let a=this.get(n);return a||(a=new zo({client:e,queryKey:i,queryHash:n,options:e.defaultQueryOptions(t),state:r,defaultOptions:e.getQueryDefaults(i)}),this.add(a)),a}add(e){l(this,ae).has(e.queryHash)||(l(this,ae).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=l(this,ae).get(e.queryHash);t&&(e.destroy(),t===e&&l(this,ae).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){$.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return l(this,ae).get(e)}getAll(){return[...l(this,ae).values()]}find(e){const t={exact:!0,...e};return this.getAll().find(r=>Wr(t,r))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(r=>Wr(e,r)):t}notify(e){$.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){$.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){$.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ae=new WeakMap,di),U,Te,Pe,vt,mt,Ce,bt,wt,fi,mc=(fi=class{constructor(s={}){b(this,U);b(this,Te);b(this,Pe);b(this,vt);b(this,mt);b(this,Ce);b(this,bt);b(this,wt);v(this,U,s.queryCache||new sc),v(this,Te,s.mutationCache||new Yo),v(this,Pe,s.defaultOptions||{}),v(this,vt,new Map),v(this,mt,new Map),v(this,Ce,0)}mount(){Yt(this,Ce)._++,l(this,Ce)===1&&(v(this,bt,ur.subscribe(async s=>{s&&(await this.resumePausedMutations(),l(this,U).onFocus())})),v(this,wt,us.subscribe(async s=>{s&&(await this.resumePausedMutations(),l(this,U).onOnline())})))}unmount(){var s,e;Yt(this,Ce)._--,l(this,Ce)===0&&((s=l(this,bt))==null||s.call(this),v(this,bt,void 0),(e=l(this,wt))==null||e.call(this),v(this,wt,void 0))}isFetching(s){return l(this,U).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return l(this,Te).findAll({...s,status:"pending"}).length}getQueryData(s){const e=this.defaultQueryOptions({queryKey:s});return l(this,U).get(e.queryHash)?.state.data}ensureQueryData(s){const e=this.defaultQueryOptions(s),t=l(this,U).build(this,e),r=t.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&t.isStaleByTime(Re(e.staleTime,t))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(s){return l(this,U).findAll(s).map(({queryKey:e,state:t})=>{const r=t.data;return[e,r]})}setQueryData(s,e,t){const r=this.defaultQueryOptions({queryKey:s}),n=l(this,U).get(r.queryHash)?.state.data,a=jo(e,n);if(a!==void 0)return l(this,U).build(this,r).setData(a,{...t,manual:!0})}setQueriesData(s,e,t){return $.batch(()=>l(this,U).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,e,t)]))}getQueryState(s){const e=this.defaultQueryOptions({queryKey:s});return l(this,U).get(e.queryHash)?.state}removeQueries(s){const e=l(this,U);$.batch(()=>{e.findAll(s).forEach(t=>{e.remove(t)})})}resetQueries(s,e){const t=l(this,U);return $.batch(()=>(t.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},e)))}cancelQueries(s,e={}){const t={revert:!0,...e},r=$.batch(()=>l(this,U).findAll(s).map(i=>i.cancel(t)));return Promise.all(r).then(D).catch(D)}invalidateQueries(s,e={}){return $.batch(()=>(l(this,U).findAll(s).forEach(t=>{t.invalidate()}),s?.refetchType==="none"?Promise.resolve():this.refetchQueries({...s,type:s?.refetchType??s?.type??"active"},e)))}refetchQueries(s,e={}){const t={...e,cancelRefetch:e.cancelRefetch??!0},r=$.batch(()=>l(this,U).findAll(s).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,t);return t.throwOnError||(n=n.catch(D)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(r).then(D)}fetchQuery(s){const e=this.defaultQueryOptions(s);e.retry===void 0&&(e.retry=!1);const t=l(this,U).build(this,e);return t.isStaleByTime(Re(e.staleTime,t))?t.fetch(e):Promise.resolve(t.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(D).catch(D)}fetchInfiniteQuery(s){return s._type="infinite",this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(D).catch(D)}ensureInfiniteQueryData(s){return s._type="infinite",this.ensureQueryData(s)}resumePausedMutations(){return us.isOnline()?l(this,Te).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,U)}getMutationCache(){return l(this,Te)}getDefaultOptions(){return l(this,Pe)}setDefaultOptions(s){v(this,Pe,s)}setQueryDefaults(s,e){l(this,vt).set(We(s),{queryKey:s,defaultOptions:e})}getQueryDefaults(s){const e=[...l(this,vt).values()],t={};return e.forEach(r=>{Dt(s,r.queryKey)&&Object.assign(t,r.defaultOptions)}),t}setMutationDefaults(s,e){l(this,mt).set(We(s),{mutationKey:s,defaultOptions:e})}getMutationDefaults(s){const e=[...l(this,mt).values()],t={};return e.forEach(r=>{Dt(s,r.mutationKey)&&Object.assign(t,r.defaultOptions)}),t}defaultQueryOptions(s){if(s._defaulted)return s;const e={...l(this,Pe).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return e.queryHash||(e.queryHash=lr(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===dr&&(e.enabled=!1),e}defaultMutationOptions(s){return s?._defaulted?s:{...l(this,Pe).mutations,...s?.mutationKey&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){l(this,U).clear(),l(this,Te).clear()}},U=new WeakMap,Te=new WeakMap,Pe=new WeakMap,vt=new WeakMap,mt=new WeakMap,Ce=new WeakMap,bt=new WeakMap,wt=new WeakMap,fi),Hi=I.createContext(void 0),ps=s=>{const e=I.useContext(Hi);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},bc=({client:s,children:e})=>(I.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),nn.jsx(Hi.Provider,{value:s,children:e})),Wi=I.createContext(!1),Vi=()=>I.useContext(Wi),wc=Wi.Provider;function rc(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var ic=I.createContext(rc()),zi=()=>I.useContext(ic),Gi=(s,e,t)=>{const r=t?.state.error&&typeof s.throwOnError=="function"?fr(s.throwOnError,[t.state.error,t]):s.throwOnError;(s.suspense||s.experimental_prefetchInRender||r)&&(e.isReset()||(s.retryOnMount=!1))},Ji=s=>{I.useEffect(()=>{s.clearReset()},[s])},Xi=({result:s,errorResetBoundary:e,throwOnError:t,query:r,suspense:i})=>s.isError&&!e.isReset()&&!s.isFetching&&r&&(i&&s.data===void 0||fr(t,[s.error,r])),Yi=s=>{if(s.suspense){const t=i=>i==="static"?i:Math.max(i??1e3,1e3),r=s.staleTime;s.staleTime=typeof r=="function"?(...i)=>t(r(...i)):t(r),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},nc=(s,e)=>s.isLoading&&s.isFetching&&!e,tr=(s,e)=>s?.suspense&&e.isPending,sr=(s,e,t)=>e.fetchOptimistic(s).catch(()=>{t.clearReset()});function _c({queries:s,...e},t){const r=ps(),i=Vi(),n=zi(),a=I.useMemo(()=>s.map(y=>{const m=r.defaultQueryOptions(y);return m._optimisticResults=i?"isRestoring":"optimistic",m}),[s,r,i]);a.forEach(y=>{Yi(y);const m=r.getQueryCache().get(y.queryHash);Gi(y,n,m)}),Ji(n);const[o]=I.useState(()=>new tc(r,a,e)),[c,u,h]=o.getOptimisticResult(a,e.combine),d=!i&&e.subscribed!==!1;I.useSyncExternalStore(I.useCallback(y=>
25d?o.subscribe($.batchCalls(y)):D,[o,d]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),I.useEffect(()=>{o.setQueries(a,e)},[a,e,o]);const p=c.some((y,m)=>tr(a[m],y))?c.flatMap((y,m)=>{const _=a[m];if(_&&tr(_,y)){const O=new pr(r,_);return sr(_,O,n)}return[]}):[];if(p.length>0)throw Promise.all(p);const g=c.find((y,m)=>{const _=a[m];return _&&Xi({result:y,errorResetBoundary:n,throwOnError:_.throwOnError,query:r.getQueryCache().get(_.queryHash),suspense:_.suspense})});if(g?.error)throw g.error;return u(h())}function ac(s,e,t){const r=Vi(),i=zi(),n=ps(),a=n.defaultQueryOptions(s);n.getDefaultOptions().queries?._experimental_beforeQuery?.(a);const o=n.getQueryCache().get(a.queryHash),c=s.subscribed!==!1;a._optimisticResults=r?"isRestoring":c?"optimistic":void 0,Yi(a),Gi(a,i,o),Ji(i);const u=!n.getQueryCache().get(a.queryHash),[h]=I.useState(()=>new e(n,a)),d=h.getOptimisticResult(a),f=!r&&c;if(I.useSyncExternalStore(I.useCallback(p=>{const g=f?h.subscribe($.batchCalls(p)):D;return h.updateResult(),g},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),I.useEffect(()=>{h.setOptions(a)},[a,h]),tr(a,d))throw sr(a,h,i);if(Xi({result:d,errorResetBoundary:i,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!Nt.isServer()&&nc(d,r)&&(u?sr(a,h,i):o?.promise)?.catch(D).finally(()=>{h.updateResult()}),a.notifyOnChangeProps?d:h.trackResult(d)}function Sc(s,e){return ac(s,pr)}function kc(s,e){const t=ps(),r=t.getQueryCache();return I.useSyncExternalStore(I.useCallback(i=>r.subscribe($.batchCalls(i)),[r]),()=>t.isFetching(s),()=>t.isFetching(s))}function Oc(s,e){const t=ps(),[r]=I.useState(()=>new Zo(t,s));I.useEffect(()=>{r.setOptions(s)},[r,s]);const i=I.useSyncExternalStore(I.useCallback(a=>r.subscribe($.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),n=I.useCallback((a,o)=>{r.mutate(a,o).catch(D)},[r]);if(i.error&&fr(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:n,mutateAsync:i.mutate}}export{wc as I,bc as Q,ue as R,ir as _,Sc as a,Oc as b,pc as c,yc as d,mc as e,kc as f,en as g,vc as h,_c as i,nn as j,gc as k,tn as l,Ue as t,ps as u};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.