import{e as Rt,d as $}from"./vendor-react-DL0tRKZA.js";const It="modulepreload",xt=function(i){return"/"+i},He={},le=function(e,t,s){let r=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));r=Promise.allSettled(t.map(l=>{if(l=xt(l),l in He)return;He[l]=!0;const c=l.endsWith(".css"),h=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${h}`))return;const u=document.createElement("link");if(u.rel=c?"stylesheet":It,c||(u.as="script"),u.crossOrigin="",u.href=l,a&&u.setAttribute("nonce",a),document.head.appendChild(u),c)return new Promise((d,f)=>{u.addEventListener("load",d),u.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${l}`)))})}))}function n(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return r.then(o=>{for(const a of o||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})},Ut=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>le(async()=>{const{default:s}=await Promise.resolve().then(()=>ee);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};class qe extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class Lt extends qe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ze extends qe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Je extends qe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Pe;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(Pe||(Pe={}));var Dt=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class Nt{constructor(e,{headers:t={},customFetch:s,region:r=Pe.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Ut(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Dt(this,void 0,void 0,function*(){try{const{headers:r,method:n,body:o}=t;let a={},{region:l}=t;l||(l=this.region);const c=new URL(`${this.url}/${e}`);l&&l!=="any"&&(a["x-region"]=l,c.searchParams.set("forceFunctionRegion",l));let h;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));const u=yield this.fetch(c.toString(),{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:h}).catch(m=>{throw new Lt(m)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new ze(u);if(!u.ok)throw new Je(u);let f=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield u.json():f==="application/octet-stream"?g=yield u.blob():f==="text/event-stream"?g=u:f==="multipart/form-data"?g=yield u.formData():g=yield u.text(),{data:g,error:null,response:u}}catch(r){return{data:null,error:r,response:r instanceof Je||r instanceof ze?r.context:void 0}}})}}var P={},Me={},ve={},ce={},we={},ye={},Bt=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},Z=Bt();const qt=Z.fetch,ct=Z.fetch.bind(Z),ht=Z.Headers,Mt=Z.Request,Ft=Z.Response,ee=Object.freeze(Object.defineProperty({__proto__:null,Headers:ht,Request:Mt,Response:Ft,default:ct,fetch:qt},Symbol.toStringTag,{value:"Module"})),Wt=Rt(ee);var me={};Object.defineProperty(me,"__esModule",{value:!0});let Kt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};me.default=Kt;var ut=$&&$.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ye,"__esModule",{value:!0});const Ht=ut(Wt),zt=ut(me);let Jt=class{constructor(e){var t,s;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(s=e.isMaybeSingle)!==null&&s!==void 0?s:!1,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Ht.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l,c;let h=null,u=null,d=null,f=n.status,g=n.statusText;if(n.ok){if(this.method!=="HEAD"){const T=await n.text();T===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((o=this.headers.get("Accept"))===null||o===void 0)&&o.includes("application/vnd.pgrst.plan+text"))?u=T:u=JSON.parse(T))}const _=(a=this.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),b=(l=n.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");_&&b&&b.length>1&&(d=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(h={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,d=null,f=406,g="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const _=await n.text();try{h=JSON.parse(_),Array.isArray(h)&&n.status===404&&(u=[],h=null,f=200,g="OK")}catch{n.status===404&&_===""?(f=204,g="No Content"):h={message:_}}if(h&&this.isMaybeSingle&&(!((c=h==null?void 0:h.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,f=200,g="OK"),h&&this.shouldThrowOnError)throw new zt.default(h)}return{error:h,data:u,count:d,status:f,statusText:g}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,l;return{error:{message:`${(o=n==null?void 0:n.name)!==null&&o!==void 0?o:"FetchError"}: ${n==null?void 0:n.message}`,details:`${(a=n==null?void 0:n.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n==null?void 0:n.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}returns(){return this}overrideTypes(){return this}};ye.default=Jt;var Gt=$&&$.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(we,"__esModule",{value:!0});const Vt=Gt(ye);let Qt=class extends Vt.default{select(e){let t=!1;const s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:n=r}={}){const o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){const n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:n=!1,format:o="text"}={}){var a;const l=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`),o==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};we.default=Qt;var Yt=$&&$.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ce,"__esModule",{value:!0});const Xt=Yt(we);let Zt=class extends Xt.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const s=Array.from(new Set(t)).map(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="websearch"&&(n="w");const o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){const r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};ce.default=Zt;var es=$&&$.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ve,"__esModule",{value:!0});const se=es(ce);let ts=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=new Headers(t),this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){const r=t?"HEAD":"GET";let n=!1;const o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&this.headers.append("Prefer",`count=${s}`),new se.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:s=!0}={}){var r;const n="POST";if(t&&this.headers.append("Prefer",`count=${t}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){const a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new se.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){var o;const a="POST";if(this.headers.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),t!==void 0&&this.url.searchParams.set("on_conflict",t),r&&this.headers.append("Prefer",`count=${r}`),n||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((c,h)=>c.concat(Object.keys(h)),[]);if(l.length>0){const c=[...new Set(l)].map(h=>`"${h}"`);this.url.searchParams.set("columns",c.join(","))}}return new se.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}update(e,{count:t}={}){var s;const r="PATCH";return t&&this.headers.append("Prefer",`count=${t}`),new se.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}delete({count:e}={}){var t;const s="DELETE";return e&&this.headers.append("Prefer",`count=${e}`),new se.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch})}};ve.default=ts;var dt=$&&$.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Me,"__esModule",{value:!0});const ss=dt(ve),rs=dt(ce);let is=class ft{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.fetch=r}from(e){const t=new URL(`${this.url}/${e}`);return new ss.default(t,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new ft(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){var o;let a;const l=new URL(`${this.url}/rpc/${e}`);let c;s||r?(a=s?"HEAD":"GET",Object.entries(t).filter(([u,d])=>d!==void 0).map(([u,d])=>[u,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([u,d])=>{l.searchParams.append(u,d)})):(a="POST",c=t);const h=new Headers(this.headers);return n&&h.set("Prefer",`count=${n}`),new rs.default({method:a,url:l,headers:h,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}};Me.default=is;var te=$&&$.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(P,"__esModule",{value:!0});P.PostgrestError=P.PostgrestBuilder=P.PostgrestTransformBuilder=P.PostgrestFilterBuilder=P.PostgrestQueryBuilder=P.PostgrestClient=void 0;const gt=te(Me);P.PostgrestClient=gt.default;const pt=te(ve);P.PostgrestQueryBuilder=pt.default;const _t=te(ce);P.PostgrestFilterBuilder=_t.default;const vt=te(we);P.PostgrestTransformBuilder=vt.default;const wt=te(ye);P.PostgrestBuilder=wt.default;const yt=te(me);P.PostgrestError=yt.default;var ns=P.default={PostgrestClient:gt.default,PostgrestQueryBuilder:pt.default,PostgrestFilterBuilder:_t.default,PostgrestTransformBuilder:vt.default,PostgrestBuilder:wt.default,PostgrestError:yt.default};const{PostgrestClient:os,PostgrestQueryBuilder:Xr,PostgrestFilterBuilder:Zr,PostgrestTransformBuilder:ei,PostgrestBuilder:ti,PostgrestError:si}=ns;class as{static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"&&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:
import ws from "ws"
new RealtimeClient(url, { transport: ws })`}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`

Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const s=this.getWebSocketConstructor();return new s(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const ls="2.15.1",cs=`realtime-js/${ls}`,hs="1.0.0",$e=1e4,us=1e3,ds=100;var ie;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(ie||(ie={}));var j;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(j||(j={}));var I;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(I||(I={}));var Ce;(function(i){i.websocket="websocket"})(Ce||(Ce={}));var K;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(K||(K={}));class fs{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),n=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=s.decode(e.slice(o,o+r));o=o+r;const l=s.decode(e.slice(o,o+n));o=o+n;const c=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}}class mt{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 k;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(k||(k={}));const Ge=(i,e,t={})=>{var s;const r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=gs(o,i,e,r),n),{})},gs=(i,e,t,s)=>{const r=e.find(a=>a.name===i),n=r==null?void 0:r.type,o=t[i];return n&&!s.includes(n)?bt(n,o):Re(o)},bt=(i,e)=>{if(i.charAt(0)==="_"){const t=i.slice(1,i.length);return ws(e,t)}switch(i){case k.bool:return ps(e);case k.float4:case k.float8:case k.int2:case k.int4:case k.int8:case k.numeric:case k.oid:return _s(e);case k.json:case k.jsonb:return vs(e);case k.timestamp:return ys(e);case k.abstime:case k.date:case k.daterange:case k.int4range:case k.int8range:case k.money:case k.reltime:case k.text:case k.time:case k.timestamptz:case k.timetz:case k.tsrange:case k.tstzrange:return Re(e);default:return Re(e)}},Re=i=>i,ps=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},_s=i=>{if(typeof i=="string"){const e=parseFloat(i);if(!Number.isNaN(e))return e}return i},vs=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},ws=(i,e)=>{if(typeof i!="string")return i;const t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n;const o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>bt(e,a))}return i},ys=i=>typeof i=="string"?i.replace(" ","T"):i,kt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class ke{constructor(e,t,s={},r=$e){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Ve;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Ve||(Ve={}));class ne{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ne.syncState(this.state,r,n,o),this.pendingDiffs.forEach(l=>{this.state=ne.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=ne.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(c,h)=>{o[c]||(l[c]=h)}),this.map(o,(c,h)=>{const u=n[c];if(u){const d=h.map(_=>_.presence_ref),f=u.map(_=>_.presence_ref),g=h.filter(_=>f.indexOf(_.presence_ref)<0),m=u.filter(_=>d.indexOf(_.presence_ref)<0);g.length>0&&(a[c]=g),m.length>0&&(l[c]=m)}else a[c]=h}),this.syncDiff(n,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){const{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,l)=>{var c;const h=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),h.length>0){const u=e[a].map(f=>f.presence_ref),d=h.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,h,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const h=l.map(u=>u.presence_ref);c=c.filter(u=>h.indexOf(u.presence_ref)<0),e[a]=c,r(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,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 Qe;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Qe||(Qe={}));var oe;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes",i.SYSTEM="system"})(oe||(oe={}));var L;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(L||(L={}));class Fe{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=j.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 ke(this,I.join,this.params,this.timeout),this.rejoinTimer=new mt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=j.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=j.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this._on(I.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new ne(this),this.broadcastEndpointURL=kt(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.state==j.closed){const{config:{broadcast:n,presence:o,private:a}}=this.params,l=(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(d=>d.filter))!==null&&r!==void 0?r:[],c=!!this.bindings[oe.PRESENCE]&&this.bindings[oe.PRESENCE].length>0,h={},u={broadcast:n,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(d=>e==null?void 0:e(L.CHANNEL_ERROR,d)),this._onClose(()=>e==null?void 0:e(L.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:d})=>{var f;if(this.socket.setAuth(),d===void 0){e==null||e(L.SUBSCRIBED);return}else{const g=this.bindings.postgres_changes,m=(f=g==null?void 0:g.length)!==null&&f!==void 0?f:0,_=[];for(let b=0;b<m;b++){const T=g[b],{filter:{event:p,schema:y,table:C,filter:S}}=T,E=d&&d[b];if(E&&E.event===p&&E.schema===y&&E.table===C&&E.filter===S)_.push(Object.assign(Object.assign({},T),{id:E.id}));else{this.unsubscribe(),this.state=j.errored,e==null||e(L.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e(L.SUBSCRIBED);return}}).receive("error",d=>{this.state=j.errored,e==null||e(L.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(d).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(L.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===j.joined&&e===oe.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){const{event:n,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=c.body)===null||r===void 0?void 0:r.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=j.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(I.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(r=>{s=new ke(this,I.leave,{},e),s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s==null||s.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=j.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new ke(this,e,t,s);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>ds){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:h}=I;if(s&&[a,l,c,h].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(f=>{var g,m,_;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((_=(m=f.filter)===null||m===void 0?void 0:m.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var g,m,_,b,T,p;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){const y=f.id,C=(g=f.filter)===null||g===void 0?void 0:g.event;return y&&((m=t.ids)===null||m===void 0?void 0:m.includes(y))&&(C==="*"||(C==null?void 0:C.toLocaleLowerCase())===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const y=(T=(b=f==null?void 0:f.filter)===null||b===void 0?void 0:b.event)===null||T===void 0?void 0:T.toLocaleLowerCase();return y==="*"||y===((p=t==null?void 0:t.event)===null||p===void 0?void 0:p.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){const g=d.data,{schema:m,table:_,commit_timestamp:b,type:T,errors:p}=g;d=Object.assign(Object.assign({},{schema:m,table:_,commit_timestamp:b,eventType:T,new:{},old:{},errors:p}),this._getPayloadRecords(g))}f.callback(d,s)})}_isClosed(){return this.state===j.closed}_isJoined(){return this.state===j.joined}_isJoining(){return this.state===j.joining}_isLeaving(){return this.state===j.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&Fe.isEqual(r.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(I.close,{},e)}_onError(e){this._on(I.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=j.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Ge(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Ge(e.columns,e.old_record)),t}}const Ye=()=>{},ue={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},ms=[1e3,2e3,5e3,1e4],bs=1e4,ks=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`;class Ss{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=$e,this.transport=null,this.heartbeatIntervalMs=ue.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ye,this.ref=0,this.reconnectTimer=null,this.logger=Ye,this.conn=null,this.sendBuffer=[],this.serializer=new fs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=r=>{let n;return r?n=r:typeof fetch>"u"?n=(...o)=>le(async()=>{const{default:a}=await Promise.resolve().then(()=>ee);return{default:a}},void 0).then(({default:a})=>a(...o)).catch(a=>{throw new Error(`Failed to load @supabase/node-fetch: ${a.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):n=fetch,(...o)=>n(...o)},!(!((s=t==null?void 0:t.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Ce.websocket}`,this.httpEndpoint=kt(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t==null?void 0: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=as.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}

To use Realtime in Node.js, you need to provide a WebSocket implementation:

Option 1: Use Node.js 22+ which has native WebSocket support
Option 2: Install and provide the "ws" package:

  npm install ws

  import ws from "ws"
  const client = new RealtimeClient(url, {
    ...options,
    transport: ws
  })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:hs}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},e?this.conn.close(e,t??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case ie.connecting:return K.Connecting;case ie.open:return K.Open;case ie.closing:return K.Closing;default:return K.Closed}}isConnected(){return this.connectionState()===K.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const s=`realtime:${e}`,r=this.getChannels().find(n=>n.topic===s);if(r)return r;{const n=new Fe(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(us,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},ue.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{t.topic==="phoenix"&&t.event==="phx_reply"&&this.heartbeatCallback(t.payload.status==="ok"?"ok":"error"),t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:s,event:r,payload:n,ref:o}=t,a=o?`(${o})`:"",l=n.status||"";this.log("receive",`${l} ${s} ${r} ${a}`.trim(),n),this.channels.filter(c=>c._isMember(s)).forEach(c=>c._trigger(r,n,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(I.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_workerObjectUrl(e){let t;if(e)t=e;else{const s=new Blob([ks],{type:"application/javascript"});t=URL.createObjectURL(s)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;e?t=e:this.accessToken?t=await this.accessToken():t=this.accessTokenValue,this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(s=>{const r={access_token:t,version:cs};t&&s.updateJoinPayload(r),s.joinedOnce&&s._isJoined()&&s._push(I.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t)}catch(r){this.log("error",`error in ${e} callback`,r)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new mt(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},ue.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,r,n,o,a,l,c;if(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e==null?void 0:e.timeout)!==null&&s!==void 0?s:$e,this.heartbeatIntervalMs=(r=e==null?void 0:e.heartbeatIntervalMs)!==null&&r!==void 0?r:ue.HEARTBEAT_INTERVAL,this.worker=(n=e==null?void 0:e.worker)!==null&&n!==void 0?n:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(a=e==null?void 0:e.reconnectAfterMs)!==null&&a!==void 0?a:h=>ms[h-1]||bs,this.encode=(l=e==null?void 0:e.encode)!==null&&l!==void 0?l:(h,u)=>u(JSON.stringify(h)),this.decode=(c=e==null?void 0:e.decode)!==null&&c!==void 0?c:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}class We extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function A(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}class Ts extends We{constructor(e,t,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Ie extends We{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var Es=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const St=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>le(async()=>{const{default:s}=await Promise.resolve().then(()=>ee);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},js=()=>Es(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield le(()=>Promise.resolve().then(()=>ee),void 0)).Response:Response}),xe=i=>{if(Array.isArray(i))return i.map(t=>xe(t));if(typeof i=="function"||i!==Object(i))return i;const e={};return Object.entries(i).forEach(([t,s])=>{const r=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[r]=xe(s)}),e},As=i=>{if(typeof i!="object"||i===null)return!1;const e=Object.getPrototypeOf(i);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in i)&&!(Symbol.iterator in i)};var H=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Se=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Os=(i,e,t)=>H(void 0,void 0,void 0,function*(){const s=yield js();i instanceof s&&!(t!=null&&t.noResolveJson)?i.json().then(r=>{const n=i.status||500,o=(r==null?void 0:r.statusCode)||n+"";e(new Ts(Se(r),n,o))}).catch(r=>{e(new Ie(Se(r),r))}):e(new Ie(Se(i),i))}),Ps=(i,e,t,s)=>{const r={method:i,headers:(e==null?void 0:e.headers)||{}};return i==="GET"||!s?r:(As(s)?(r.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),r.body=JSON.stringify(s)):r.body=s,e!=null&&e.duplex&&(r.duplex=e.duplex),Object.assign(Object.assign({},r),t))};function he(i,e,t,s,r,n){return H(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Ps(e,s,r,n)).then(l=>{if(!l.ok)throw l;return s!=null&&s.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Os(l,a,s))})})}function pe(i,e,t,s){return H(this,void 0,void 0,function*(){return he(i,"GET",e,t,s)})}function x(i,e,t,s,r){return H(this,void 0,void 0,function*(){return he(i,"POST",e,s,r,t)})}function Ue(i,e,t,s,r){return H(this,void 0,void 0,function*(){return he(i,"PUT",e,s,r,t)})}function $s(i,e,t,s){return H(this,void 0,void 0,function*(){return he(i,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function Tt(i,e,t,s,r){return H(this,void 0,void 0,function*(){return he(i,"DELETE",e,s,r,t)})}var O=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Cs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Xe={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Rs{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=St(r)}uploadOrUpdate(e,t,s,r){return O(this,void 0,void 0,function*(){try{let n;const o=Object.assign(Object.assign({},Xe),r);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l)),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l))):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),r!=null&&r.headers&&(a=Object.assign(Object.assign({},a),r.headers));const c=this._removeEmptyFolders(t),h=this._getFinalPath(c),u=yield(e=="PUT"?Ue:x)(this.fetch,`${this.url}/object/${h}`,n,Object.assign({headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(n){if(A(n))return{data:null,error:n};throw n}})}upload(e,t,s){return O(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return O(this,void 0,void 0,function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:Xe.upsert},r),h=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",c.cacheControl)):(l=s,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType);const u=yield Ue(this.fetch,a.toString(),l,{headers:h});return{data:{path:n,fullPath:u.Key},error:null}}catch(l){if(A(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return O(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);t!=null&&t.upsert&&(r["x-upsert"]="true");const n=yield x(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new We("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}update(e,t,s){return O(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return O(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s==null?void 0:s.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}copy(e,t,s){return O(this,void 0,void 0,function*(){try{return{data:{path:(yield x(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s==null?void 0:s.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return O(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield x(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s!=null&&s.transform?{transform:s.transform}:{}),{headers:this.headers});const o=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return O(this,void 0,void 0,function*(){try{const r=yield x(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}download(e,t){return O(this,void 0,void 0,function*(){const r=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),o=n?`?${n}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield pe(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(A(a))return{data:null,error:a};throw a}})}info(e){return O(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield pe(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:xe(s),error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}exists(e){return O(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield $s(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(A(s)&&s instanceof Ie){const r=s.originalError;if([400,404].includes(r==null?void 0:r.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],n=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);const a=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});l!==""&&r.push(l);let c=r.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${c}`)}}}remove(e){return O(this,void 0,void 0,function*(){try{return{data:yield Tt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}list(e,t,s){return O(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},Cs),t),{prefix:e||""});return{data:yield x(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}listV2(e,t){return O(this,void 0,void 0,function*(){try{const s=Object.assign({},e);return{data:yield x(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t),error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const Is="2.11.0",xs={"X-Client-Info":`storage-js/${Is}`};var z=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class Us{constructor(e,t={},s,r){const n=new URL(e);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href,this.headers=Object.assign(Object.assign({},xs),t),this.fetch=St(s)}listBuckets(){return z(this,void 0,void 0,function*(){try{return{data:yield pe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(A(e))return{data:null,error:e};throw e}})}getBucket(e){return z(this,void 0,void 0,function*(){try{return{data:yield pe(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return z(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return z(this,void 0,void 0,function*(){try{return{data:yield Ue(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}emptyBucket(e){return z(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}deleteBucket(e){return z(this,void 0,void 0,function*(){try{return{data:yield Tt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}}class Ls extends Us{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new Rs(this.url,this.headers,e,this.fetch)}}const Ds="2.56.0";let re="";typeof Deno<"u"?re="deno":typeof document<"u"?re="web":typeof navigator<"u"&&navigator.product==="ReactNative"?re="react-native":re="node";const Ns={"X-Client-Info":`supabase-js-${re}/${Ds}`},Bs={headers:Ns},qs={schema:"public"},Ms={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Fs={};var Ws=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};const Ks=i=>{let e;return i?e=i:typeof fetch>"u"?e=ct:e=fetch,(...t)=>e(...t)},Hs=()=>typeof Headers>"u"?ht:Headers,zs=(i,e,t)=>{const s=Ks(t),r=Hs();return(n,o)=>Ws(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:i;let c=new r(o==null?void 0:o.headers);return c.has("apikey")||c.set("apikey",i),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(n,Object.assign(Object.assign({},o),{headers:c}))})};var Js=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};function Gs(i){return i.endsWith("/")?i:i+"/"}function Vs(i,e){var t,s;const{db:r,auth:n,realtime:o,global:a}=i,{db:l,auth:c,realtime:h,global:u}=e,d={db:Object.assign(Object.assign({},l),r),auth:Object.assign(Object.assign({},c),n),realtime:Object.assign(Object.assign({},h),o),storage:{},global:Object.assign(Object.assign(Object.assign({},u),a),{headers:Object.assign(Object.assign({},(t=u==null?void 0:u.headers)!==null&&t!==void 0?t:{}),(s=a==null?void 0:a.headers)!==null&&s!==void 0?s:{})}),accessToken:()=>Js(this,void 0,void 0,function*(){return""})};return i.accessToken?d.accessToken=i.accessToken:delete d.accessToken,d}const Et="2.71.1",Y=30*1e3,Le=3,Te=Le*Y,Qs="http://localhost:9999",Ys="supabase.auth.token",Xs={"X-Client-Info":`gotrue-js/${Et}`},De="X-Supabase-Api-Version",jt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Zs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,er=10*60*1e3;class Ke extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function v(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}class tr extends Ke{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function sr(i){return v(i)&&i.name==="AuthApiError"}class At extends Ke{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class q extends Ke{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class N extends q{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function rr(i){return v(i)&&i.name==="AuthSessionMissingError"}class de extends q{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class fe extends q{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ge extends q{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 ir(i){return v(i)&&i.name==="AuthImplicitGrantRedirectError"}class Ze extends q{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 Ne extends q{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Ee(i){return v(i)&&i.name==="AuthRetryableFetchError"}class et extends q{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Be extends q{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const _e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tt=` 	
\r=`.split(""),nr=(()=>{const i=new Array(128);for(let e=0;e<i.length;e+=1)i[e]=-1;for(let e=0;e<tt.length;e+=1)i[tt[e].charCodeAt(0)]=-2;for(let e=0;e<_e.length;e+=1)i[_e[e].charCodeAt(0)]=e;return i})();function st(i,e,t){if(i!==null)for(e.queue=e.queue<<8|i,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(_e[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(_e[s]),e.queuedBits-=6}}function Ot(i,e,t){const s=nr[i];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(i)}"`)}}function rt(i){const e=[],t=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},r={queue:0,queuedBits:0},n=o=>{lr(o,s,t)};for(let o=0;o<i.length;o+=1)Ot(i.charCodeAt(o),r,n);return e.join("")}function or(i,e){if(i<=127){e(i);return}else if(i<=2047){e(192|i>>6),e(128|i&63);return}else if(i<=65535){e(224|i>>12),e(128|i>>6&63),e(128|i&63);return}else if(i<=1114111){e(240|i>>18),e(128|i>>12&63),e(128|i>>6&63),e(128|i&63);return}throw new Error(`Unrecognized Unicode codepoint: ${i.toString(16)}`)}function ar(i,e){for(let t=0;t<i.length;t+=1){let s=i.charCodeAt(t);if(s>55295&&s<=56319){const r=(s-55296)*1024&65535;s=(i.charCodeAt(t+1)-56320&65535|r)+65536,t+=1}or(s,e)}}function lr(i,e,t){if(e.utf8seq===0){if(i<=127){t(i);return}for(let s=1;s<6;s+=1)if(!(i>>7-s&1)){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=i&31;else if(e.utf8seq===3)e.codepoint=i&15;else if(e.utf8seq===4)e.codepoint=i&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(i<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|i&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function cr(i){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};for(let r=0;r<i.length;r+=1)Ot(i.charCodeAt(r),t,s);return new Uint8Array(e)}function hr(i){const e=[];return ar(i,t=>e.push(t)),new Uint8Array(e)}function ur(i){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};return i.forEach(r=>st(r,t,s)),st(null,t,s),e.join("")}function dr(i){return Math.round(Date.now()/1e3)+i}function fr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){const e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}const R=()=>typeof window<"u"&&typeof document<"u",M={tested:!1,writable:!1},Pt=()=>{if(!R())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(M.tested)return M.writable;const i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),M.tested=!0,M.writable=!0}catch{M.tested=!0,M.writable=!1}return M.writable};function gr(i){const e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}const $t=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>le(async()=>{const{default:s}=await Promise.resolve().then(()=>ee);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},pr=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",X=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},F=async(i,e)=>{const t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},D=async(i,e)=>{await i.removeItem(e)};class be{constructor(){this.promise=new be.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}be.promiseConstructor=Promise;function je(i){const e=i.split(".");if(e.length!==3)throw new Be("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Zs.test(e[s]))throw new Be("JWT not in base64url format");return{header:JSON.parse(rt(e[0])),payload:JSON.parse(rt(e[1])),signature:cr(e[2]),raw:{header:e[0],payload:e[1]}}}async function _r(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function vr(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{const o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function wr(i){return("0"+i.toString(16)).substr(-2)}function yr(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,wr).join("")}async function mr(i){const t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}async function br(i){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),i;const t=await mr(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function J(i,e,t=!1){const s=yr();let r=s;t&&(r+="/PASSWORD_RECOVERY"),await X(i,`${e}-code-verifier`,r);const n=await br(s);return[n,s===n?"plain":"s256"]}const kr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Sr(i){const e=i.headers.get(De);if(!e||!e.match(kr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Tr(i){if(!i)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(i<=e)throw new Error("JWT has expired")}function Er(i){switch(i){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 jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function G(i){if(!jr.test(i))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ae(){const i={};return new Proxy(i,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const s=t.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function it(i){return JSON.parse(JSON.stringify(i))}var Ar=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t};const W=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Or=[502,503,504];async function nt(i){var e;if(!pr(i))throw new Ne(W(i),0);if(Or.includes(i.status))throw new Ne(W(i),i.status);let t;try{t=await i.json()}catch(n){throw new At(W(n),n)}let s;const r=Sr(i);if(r&&r.getTime()>=jt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new et(W(t),i.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new N}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new et(W(t),i.status,t.weak_password.reasons);throw new tr(W(t),i.status||500,s)}const Pr=(i,e,t,s)=>{const r={method:i,headers:(e==null?void 0:e.headers)||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function w(i,e,t,s){var r;const n=Object.assign({},s==null?void 0:s.headers);n[De]||(n[De]=jt["2024-01-01"].name),s!=null&&s.jwt&&(n.Authorization=`Bearer ${s.jwt}`);const o=(r=s==null?void 0:s.query)!==null&&r!==void 0?r:{};s!=null&&s.redirectTo&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await $r(i,e,t+a,{headers:n,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function $r(i,e,t,s,r,n){const o=Pr(e,s,r,n);let a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new Ne(W(l),0)}if(a.ok||await nt(a),s!=null&&s.noResolveJson)return a;try{return await a.json()}catch(l){await nt(l)}}function U(i){var e;let t=null;xr(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=dr(i.expires_in)));const s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function ot(i){const e=U(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function B(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function Cr(i){return{data:i,error:null}}function Rr(i){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=Ar(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Ir(i){return i}function xr(i){return i.access_token&&i.refresh_token&&i.expires_in}const Oe=["global","local","others"];var Ur=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t};class Lr{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=$t(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t=Oe[0]){if(Oe.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Oe.join(", ")}`);try{return await w(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(v(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await w(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:B})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=Ur(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s==null?void 0:s.newEmail,delete r.newEmail),await w(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:Rr,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(v(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await w(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:B})}catch(t){if(v(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},h=await w(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e==null?void 0:e.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:Ir});if(h.error)throw h.error;const u=await h.json(),d=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(g=>{const m=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);c[`${_}Page`]=m}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(v(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){G(e);try{return await w(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:B})}catch(t){if(v(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){G(e);try{return await w(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:B})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){G(e);try{return await w(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:B})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){G(e.userId);try{const{data:t,error:s}=await w(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(v(t))return{data:null,error:t};throw t}}async _deleteFactor(e){G(e.userId),G(e.id);try{return{data:await w(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(v(t))return{data:null,error:t};throw t}}}function at(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function Dr(){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 V={debug:!!(globalThis&&Pt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Ct extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Nr extends Ct{}async function Br(i,e,t){V.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),V.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){V.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{V.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw V.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new Nr(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(V.debug)try{const n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null,"  "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}Dr();const qr={url:Qs,storageKey:Ys,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Xs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function lt(i,e,t){return await t()}const Q={};class ae{constructor(e){var t,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=ae.nextInstanceID,ae.nextInstanceID+=1,this.instanceID>0&&R()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const r=Object.assign(Object.assign({},qr),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new Lr({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=$t(r.fetch),this.lock=r.lock||lt,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:R()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Br:this.lock=lt,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?(r.storage?this.storage=r.storage:Pt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=at(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=at(this.memoryStorage)),R()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}get jwks(){var e,t;return(t=(e=Q[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Q[this.storageKey]=Object.assign(Object.assign({},Q[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Q[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Q[this.storageKey]=Object.assign(Object.assign({},Q[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Et}) ${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=gr(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),R()&&this.detectSessionInUrl&&s!=="none"){const{data:r,error:n}=await this._getSessionFromURL(t,s);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),ir(n)){const l=(e=n.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:n}}return await this._removeSession(),{error:n}}const{session:o,redirectType:a}=r;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return v(t)?{error:t}:{error:new At("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}},xform:U}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(v(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){const{email:h,password:u,options:d}=e;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await J(this.storage,this.storageKey)),n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:h,password:u,data:(t=d==null?void 0:d.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:f,code_challenge_method:g},xform:U})}else if("phone"in e){const{phone:h,password:u,options:d}=e;n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:u,data:(s=d==null?void 0:d.data)!==null&&s!==void 0?s:{},channel:(r=d==null?void 0:d.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:U})}else throw new fe("You must provide either an email or phone number and a password");const{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(v(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:o,options:a}=e;t=await w(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:ot})}else if("phone"in e){const{phone:n,password:o,options:a}=e;t=await w(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:ot})}else throw new fe("You must provide either an email or phone number and a password");const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new de}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(v(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.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,s,r,n,o,a,l,c,h,u,d,f;let g,m;if("message"in e)g=e.message,m=e.signature;else{const{chain:_,wallet:b,statement:T,options:p}=e;let y;if(R())if(typeof b=="object")y=b;else{const S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))y=S.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 b!="object"||!(p!=null&&p.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=b}const C=new URL((t=p==null?void 0:p.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in y&&y.signIn){const S=await y.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},p==null?void 0:p.signInWithSolana),{version:"1",domain:C.host,uri:C.href}),T?{statement:T}:null));let E;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")E=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)E=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)g=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),m=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in y)||typeof y.signMessage!="function"||!("publicKey"in y)||typeof y!="object"||!y.publicKey||!("toBase58"in y.publicKey)||typeof y.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${C.host} wants you to sign in with your Solana account:`,y.publicKey.toBase58(),...T?["",T,""]:[""],"Version: 1",`URI: ${C.href}`,`Issued At: ${(r=(s=p==null?void 0:p.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&r!==void 0?r:new Date().toISOString()}`,...!((n=p==null?void 0:p.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${p.signInWithSolana.notBefore}`]:[],...!((o=p==null?void 0:p.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${p.signInWithSolana.expirationTime}`]:[],...!((a=p==null?void 0:p.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${p.signInWithSolana.chainId}`]:[],...!((l=p==null?void 0:p.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${p.signInWithSolana.nonce}`]:[],...!((c=p==null?void 0:p.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${p.signInWithSolana.requestId}`]:[],...!((u=(h=p==null?void 0:p.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||u===void 0)&&u.length?["Resources",...p.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
`);const S=await y.signMessage(new TextEncoder().encode(g),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=S}}try{const{data:_,error:b}=await w(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:ur(m)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:U});if(b)throw b;return!_||!_.session||!_.user?{data:{user:null,session:null},error:new de}:(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),{data:Object.assign({},_),error:b})}catch(_){if(v(_))return{data:{user:null,session:null},error:_};throw _}}async _exchangeCodeForSession(e){const t=await F(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/");try{const{data:n,error:o}=await w(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:U});if(await D(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new de}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}catch(n){if(v(n))return{data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await w(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:U}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new de}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(v(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,h=null;this.flowType==="pkce"&&([c,h]=await J(this.storage,this.storageKey));const{error:u}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l==null?void 0:l.data)!==null&&t!==void 0?t:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l==null?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:h}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(n=l==null?void 0:l.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:h}}throw new fe("You must provide either an email or phone number.")}catch(a){if(v(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await w(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:U});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(r){if(v(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await J(this.storage,this.storageKey)),await w(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e==null?void 0:e.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Cr})}catch(n){if(v(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new N;const{error:r}=await w(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(v(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:n}=e,{error:o}=await w(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},redirectTo:n==null?void 0:n.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:s,type:r,options:n}=e,{data:o,error:a}=await w(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a}}throw new fe("You must provide either an email or phone number and a type")}catch(t){if(v(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await F(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Te:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const o=await F(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ae()}if(this.storage.isServer&&e.user){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,h)=>(!o&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,c,h))})}return{data:{session:e},error:null}}const{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},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 w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:B}):await this._useSession(async t=>{var s,r,n;const{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new N}:await w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:B})})}catch(t){if(v(t))return rr(t)&&(await this._removeSession(),await D(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new N;const o=r.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await J(this.storage,this.storageKey));const{data:c,error:h}=await w(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:B});if(h)throw h;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new N;const t=Date.now()/1e3;let s=t,r=!0,n=null;const{payload:o}=je(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){const{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(v(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new N;const{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(v(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!R())throw new ge("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ge(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 Ze("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ge("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 Ze("No code detected.");const{data:T,error:p}=await this._exchangeCodeForSession(e.code);if(p)throw p;const y=new URL(window.location.href);return y.searchParams.delete("code"),window.history.replaceState(window.history.state,"",y.toString()),{data:{session:T.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!n||!a||!o||!c)throw new ge("No session defined in URL");const h=Math.round(Date.now()/1e3),u=parseInt(a);let d=h+u;l&&(d=parseInt(l));const f=d-h;f*1e3<=Y&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);const g=d-u;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,h):h-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,d,h);const{data:m,error:_}=await this._getUser(n);if(_)throw _;const b={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:b,redirectType:e.type},error:null}}catch(s){if(v(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await F(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;const{data:r,error:n}=t;if(n)return{error:n};const o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(sr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await D(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=fr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{const{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await J(this.storage,this.storageKey,!0));try{return await w(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(v(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(v(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{const{data:s,error:r}=await this._useSession(async n=>{var o,a,l,c,h;const{data:u,error:d}=n;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await w(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(r)throw r;return R()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),{data:{provider:e.provider,url:s==null?void 0:s.url},error:null}}catch(s){if(v(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;const{data:n,error:o}=t;if(o)throw o;return await w(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(v(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await vr(async r=>(r>0&&await _r(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await w(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:U})),(r,n)=>{const o=200*Math.pow(2,r);return n&&Ee(n)&&Date.now()+o-s<Y})}catch(s){if(this._debug(t,"error",s),v(s))return{data:{session:null,user:null},error:s};throw s}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 s=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",s),R()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,t;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const r=await F(this.storage,this.storageKey);if(r&&this.userStorage){let o=await F(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:r.user},await X(this.userStorage,this.storageKey+"-user",o)),r.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ae()}else if(r&&!r.user&&!r.user){const o=await F(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(r.user=o.user,await D(this.storage,this.storageKey+"-user"),await X(this.storage,this.storageKey,r)):r.user=Ae()}if(this._debug(s,"session from storage",r),!this._isValidSession(r)){this._debug(s,"session is not valid"),r!==null&&await this._removeSession();return}const n=((t=r.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Te;if(this._debug(s,`session has${n?"":" not"} expired with margin of ${Te}s`),n){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Ee(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(r.user&&r.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(r.access_token);!a&&(o!=null&&o.user)?(r.user=o.user,await this._saveSession(r),await this._notifyAllSubscribers("SIGNED_IN",r)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(s,"error",r),console.error(r);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new N;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new be;const{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new N;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);const a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"error",n),v(n)){const o={session:null,error:n};return Ee(n)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),s=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&t.user&&await X(this.userStorage,this.storageKey+"-user",{user:t.user});const r=Object.assign({},t);delete r.user;const n=it(r);await X(this.storage,this.storageKey,n)}else{const r=it(t);await X(this.storage,this.storageKey,r)}}async _removeSession(){this._debug("#_removeSession()"),await D(this.storage,this.storageKey),await D(this.storage,this.storageKey+"-code-verifier"),await D(this.storage,this.storageKey+"-user"),this.userStorage&&await D(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&R()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Y);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const r=Math.floor((s.expires_at*1e3-e)/Y);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${Y}ms, refresh threshold is ${Le} ticks`),r<=Le&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ct)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!R()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){const r=[`provider=${encodeURIComponent(t)}`];if(s!=null&&s.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[n,o]=await J(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s!=null&&s.queryParams){const n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s!=null&&s.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:r,error:n}=t;return n?{data:null,error:n}:await w(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r==null?void 0:r.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(v(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;const{data:n,error:o}=t;if(o)return{data:null,error:o};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:l,error:c}=await w(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&(!((r=l==null?void 0:l.totp)===null||r===void 0)&&r.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(v(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:n}=t;if(n)return{data:null,error:n};const{data:o,error:a}=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r==null?void 0:r.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(v(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:n}=t;return n?{data:null,error:n}:await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(s=r==null?void 0:r.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(v(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const s=(e==null?void 0:e.factors)||[],r=s.filter(o=>o.factor_type==="totp"&&o.status==="verified"),n=s.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:s,totp:r,phone:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=je(r.access_token);let a=null;o.aal&&(a=o.aal);let l=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");const h=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:h},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(a=>a.kid===e);if(s)return s;const r=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+er>r)return s;const{data:n,error:o}=await w(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!n.keys||n.keys.length===0||(this.jwks=n,this.jwks_cached_at=r,s=n.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,t={}){try{let s=e;if(!s){const{data:f,error:g}=await this.getSession();if(g||!f.session)return{data:null,error:g};s=f.session.access_token}const{header:r,payload:n,signature:o,raw:{header:a,payload:l}}=je(s);t!=null&&t.allowExpired||Tr(n.exp);const c=!r.alg||r.alg.startsWith("HS")||!r.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(r.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:n,header:r,signature:o},error:null}}const h=Er(r.alg),u=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,u,o,hr(`${a}.${l}`)))throw new Be("Invalid JWT signature");return{data:{claims:n,header:r,signature:o},error:null}}catch(s){if(v(s))return{data:null,error:s};throw s}}}ae.nextInstanceID=0;const Mr=ae;class Fr extends Mr{constructor(e){super(e)}}var Wr=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?n(h.value):r(h.value).then(a,l)}c((s=s.apply(i,e||[])).next())})};class Kr{constructor(e,t,s){var r,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const a=Gs(e),l=new URL(a);this.realtimeUrl=new URL("realtime/v1",l),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",l),this.storageUrl=new URL("storage/v1",l),this.functionsUrl=new URL("functions/v1",l);const c=`sb-${l.hostname.split(".")[0]}-auth-token`,h={db:qs,realtime:Fs,auth:Object.assign(Object.assign({},Ms),{storageKey:c}),global:Bs},u=Vs(s??{},h);this.storageKey=(r=u.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=u.global.headers)!==null&&n!==void 0?n:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=zs(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},u.realtime)),this.rest=new os(new URL("rest/v1",l).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this.storage=new Ls(this.storageUrl.href,this.headers,this.fetch,s==null?void 0:s.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new Nt(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Wr(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:n,flowType:o,lock:a,debug:l},c,h){const u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fr({url:this.authUrl.href,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,lock:a,debug:l,fetch:h,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new Ss(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s==null?void 0:s.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?this.changedAccessToken=s:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const ri=(i,e,t)=>new Kr(i,e,t);function Hr(){if(typeof window<"u"||typeof process>"u")return!1;const i=process.version;if(i==null)return!1;const e=i.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}Hr()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");export{le as _,ri as c};