import{g as Lt,a as Dt}from"./vendor-D8-FJEVI.js";const Nt="modulepreload",Bt=function(n){return"/"+n},He={},de=function(e,t,s){let r=Promise.resolve();if(t&&t.length>0){let l=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");r=l(t.map(c=>{if(c=Bt(c),c in He)return;He[c]=!0;const u=c.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Nt,u||(d.as="script"),d.crossOrigin="",d.href=c,a&&d.setAttribute("nonce",a),document.head.appendChild(d),u)return new Promise((f,g)=>{d.addEventListener("load",f),d.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(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"&&i(a.reason);return e().catch(i)})},qt=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>de(async()=>{const{default:s}=await Promise.resolve().then(()=>ie);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 Mt 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 Oe;(function(n){n.Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2"})(Oe||(Oe={}));var Ft=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};class Wt{constructor(e,{headers:t={},customFetch:s,region:r=Oe.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=qt(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Ft(this,void 0,void 0,function*(){try{const{headers:r,method:i,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 u;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",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));const h=yield this.fetch(c.toString(),{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:u}).catch(w=>{throw new Mt(w)}),d=h.headers.get("x-relay-error");if(d&&d==="true")throw new ze(h);if(!h.ok)throw new Je(h);let f=((s=h.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield h.json():f==="application/octet-stream"?g=yield h.blob():f==="text/event-stream"?g=h:f==="multipart/form-data"?g=yield h.formData():g=yield h.text(),{data:g,error:null,response:h}}catch(r){return{data:null,error:r,response:r instanceof Je||r instanceof ze?r.context:void 0}}})}}var j={},H={},z={},J={},G={},V={},Kt=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")},re=Kt();const Ht=re.fetch,yt=re.fetch.bind(re),wt=re.Headers,zt=re.Request,Jt=re.Response,ie=Object.freeze(Object.defineProperty({__proto__:null,Headers:wt,Request:zt,Response:Jt,default:yt,fetch:Ht},Symbol.toStringTag,{value:"Module"})),Gt=Lt(ie);var ge={},Ge;function bt(){if(Ge)return ge;Ge=1,Object.defineProperty(ge,"__esModule",{value:!0});class n extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}return ge.default=n,ge}var Ve;function mt(){if(Ve)return V;Ve=1;var n=V&&V.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(V,"__esModule",{value:!0});const e=n(Gt),t=n(bt());class s{constructor(i){this.shouldThrowOnError=!1,this.method=i.method,this.url=i.url,this.headers=i.headers,this.schema=i.schema,this.body=i.body,this.shouldThrowOnError=i.shouldThrowOnError,this.signal=i.signal,this.isMaybeSingle=i.isMaybeSingle,i.fetch?this.fetch=i.fetch:typeof fetch>"u"?this.fetch=e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(i,o){return this.headers=Object.assign({},this.headers),this.headers[i]=o,this}then(i,o){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const a=this.fetch;let l=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async c=>{var u,h,d;let f=null,g=null,w=null,_=c.status,m=c.statusText;if(c.ok){if(this.method!=="HEAD"){const O=await c.text();O===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?g=O:g=JSON.parse(O))}const p=(u=this.headers.Prefer)===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),b=(h=c.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");p&&b&&b.length>1&&(w=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(f={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,w=null,_=406,m="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{const p=await c.text();try{f=JSON.parse(p),Array.isArray(f)&&c.status===404&&(g=[],f=null,_=200,m="OK")}catch{c.status===404&&p===""?(_=204,m="No Content"):f={message:p}}if(f&&this.isMaybeSingle&&(!((d=f?.details)===null||d===void 0)&&d.includes("0 rows"))&&(f=null,_=200,m="OK"),f&&this.shouldThrowOnError)throw new t.default(f)}return{error:f,data:g,count:w,status:_,statusText:m}});return this.shouldThrowOnError||(l=l.catch(c=>{var u,h,d;return{error:{message:`${(u=c?.name)!==null&&u!==void 0?u:"FetchError"}: ${c?.message}`,details:`${(h=c?.stack)!==null&&h!==void 0?h:""}`,hint:"",code:`${(d=c?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),l.then(i,o)}returns(){return this}overrideTypes(){return this}}return V.default=s,V}var Qe;function kt(){if(Qe)return G;Qe=1;var n=G&&G.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(G,"__esModule",{value:!0});const e=n(mt());class t extends e.default{select(r){let i=!1;const o=(r??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(r,{ascending:i=!0,nullsFirst:o,foreignTable:a,referencedTable:l=a}={}){const c=l?`${l}.order`:"order",u=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${u?`${u},`:""}${r}.${i?"asc":"desc"}${o===void 0?"":o?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:i,referencedTable:o=i}={}){const a=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(a,`${r}`),this}range(r,i,{foreignTable:o,referencedTable:a=o}={}){const l=typeof a>"u"?"offset":`${a}.offset`,c=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${r}`),this.url.searchParams.set(c,`${i-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:r=!1,verbose:i=!1,settings:o=!1,buffers:a=!1,wal:l=!1,format:c="text"}={}){var u;const h=[r?"analyze":null,i?"verbose":null,o?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),d=(u=this.headers.Accept)!==null&&u!==void 0?u:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${c}; for="${d}"; options=${h};`,c==="json"?this:this}rollback(){var r;return((r=this.headers.Prefer)!==null&&r!==void 0?r:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}return G.default=t,G}var Ye;function Me(){if(Ye)return J;Ye=1;var n=J&&J.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(J,"__esModule",{value:!0});const e=n(kt());class t extends e.default{eq(r,i){return this.url.searchParams.append(r,`eq.${i}`),this}neq(r,i){return this.url.searchParams.append(r,`neq.${i}`),this}gt(r,i){return this.url.searchParams.append(r,`gt.${i}`),this}gte(r,i){return this.url.searchParams.append(r,`gte.${i}`),this}lt(r,i){return this.url.searchParams.append(r,`lt.${i}`),this}lte(r,i){return this.url.searchParams.append(r,`lte.${i}`),this}like(r,i){return this.url.searchParams.append(r,`like.${i}`),this}likeAllOf(r,i){return this.url.searchParams.append(r,`like(all).{${i.join(",")}}`),this}likeAnyOf(r,i){return this.url.searchParams.append(r,`like(any).{${i.join(",")}}`),this}ilike(r,i){return this.url.searchParams.append(r,`ilike.${i}`),this}ilikeAllOf(r,i){return this.url.searchParams.append(r,`ilike(all).{${i.join(",")}}`),this}ilikeAnyOf(r,i){return this.url.searchParams.append(r,`ilike(any).{${i.join(",")}}`),this}is(r,i){return this.url.searchParams.append(r,`is.${i}`),this}in(r,i){const o=Array.from(new Set(i)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(r,`in.(${o})`),this}contains(r,i){return typeof i=="string"?this.url.searchParams.append(r,`cs.${i}`):Array.isArray(i)?this.url.searchParams.append(r,`cs.{${i.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(i)}`),this}containedBy(r,i){return typeof i=="string"?this.url.searchParams.append(r,`cd.${i}`):Array.isArray(i)?this.url.searchParams.append(r,`cd.{${i.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(i)}`),this}rangeGt(r,i){return this.url.searchParams.append(r,`sr.${i}`),this}rangeGte(r,i){return this.url.searchParams.append(r,`nxl.${i}`),this}rangeLt(r,i){return this.url.searchParams.append(r,`sl.${i}`),this}rangeLte(r,i){return this.url.searchParams.append(r,`nxr.${i}`),this}rangeAdjacent(r,i){return this.url.searchParams.append(r,`adj.${i}`),this}overlaps(r,i){return typeof i=="string"?this.url.searchParams.append(r,`ov.${i}`):this.url.searchParams.append(r,`ov.{${i.join(",")}}`),this}textSearch(r,i,{config:o,type:a}={}){let l="";a==="plain"?l="pl":a==="phrase"?l="ph":a==="websearch"&&(l="w");const c=o===void 0?"":`(${o})`;return this.url.searchParams.append(r,`${l}fts${c}.${i}`),this}match(r){return Object.entries(r).forEach(([i,o])=>{this.url.searchParams.append(i,`eq.${o}`)}),this}not(r,i,o){return this.url.searchParams.append(r,`not.${i}.${o}`),this}or(r,{foreignTable:i,referencedTable:o=i}={}){const a=o?`${o}.or`:"or";return this.url.searchParams.append(a,`(${r})`),this}filter(r,i,o){return this.url.searchParams.append(r,`${i}.${o}`),this}}return J.default=t,J}var Xe;function St(){if(Xe)return z;Xe=1;var n=z&&z.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(z,"__esModule",{value:!0});const e=n(Me());class t{constructor(r,{headers:i={},schema:o,fetch:a}){this.url=r,this.headers=i,this.schema=o,this.fetch=a}select(r,{head:i=!1,count:o}={}){const a=i?"HEAD":"GET";let l=!1;const c=(r??"*").split("").map(u=>/\s/.test(u)&&!l?"":(u==='"'&&(l=!l),u)).join("");return this.url.searchParams.set("select",c),o&&(this.headers.Prefer=`count=${o}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(r,{count:i,defaultToNull:o=!0}={}){const a="POST",l=[];if(this.headers.Prefer&&l.push(this.headers.Prefer),i&&l.push(`count=${i}`),o||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(r)){const c=r.reduce((u,h)=>u.concat(Object.keys(h)),[]);if(c.length>0){const u=[...new Set(c)].map(h=>`"${h}"`);this.url.searchParams.set("columns",u.join(","))}}return new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:this.fetch,allowEmpty:!1})}upsert(r,{onConflict:i,ignoreDuplicates:o=!1,count:a,defaultToNull:l=!0}={}){const c="POST",u=[`resolution=${o?"ignore":"merge"}-duplicates`];if(i!==void 0&&this.url.searchParams.set("on_conflict",i),this.headers.Prefer&&u.push(this.headers.Prefer),a&&u.push(`count=${a}`),l||u.push("missing=default"),this.headers.Prefer=u.join(","),Array.isArray(r)){const h=r.reduce((d,f)=>d.concat(Object.keys(f)),[]);if(h.length>0){const d=[...new Set(h)].map(f=>`"${f}"`);this.url.searchParams.set("columns",d.join(","))}}return new e.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:this.fetch,allowEmpty:!1})}update(r,{count:i}={}){const o="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),this.headers.Prefer=a.join(","),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:this.fetch,allowEmpty:!1})}delete({count:r}={}){const i="DELETE",o=[];return r&&o.push(`count=${r}`),this.headers.Prefer&&o.unshift(this.headers.Prefer),this.headers.Prefer=o.join(","),new e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}return z.default=t,z}var ne={},oe={},Ze;function Vt(){return Ze||(Ze=1,Object.defineProperty(oe,"__esModule",{value:!0}),oe.version=void 0,oe.version="0.0.0-automated"),oe}var et;function Qt(){if(et)return ne;et=1,Object.defineProperty(ne,"__esModule",{value:!0}),ne.DEFAULT_HEADERS=void 0;const n=Vt();return ne.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${n.version}`},ne}var tt;function Yt(){if(tt)return H;tt=1;var n=H&&H.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(H,"__esModule",{value:!0});const e=n(St()),t=n(Me()),s=Qt();class r{constructor(o,{headers:a={},schema:l,fetch:c}={}){this.url=o,this.headers=Object.assign(Object.assign({},s.DEFAULT_HEADERS),a),this.schemaName=l,this.fetch=c}from(o){const a=new URL(`${this.url}/${o}`);return new e.default(a,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(o){return new r(this.url,{headers:this.headers,schema:o,fetch:this.fetch})}rpc(o,a={},{head:l=!1,get:c=!1,count:u}={}){let h;const d=new URL(`${this.url}/rpc/${o}`);let f;l||c?(h=l?"HEAD":"GET",Object.entries(a).filter(([w,_])=>_!==void 0).map(([w,_])=>[w,Array.isArray(_)?`{${_.join(",")}}`:`${_}`]).forEach(([w,_])=>{d.searchParams.append(w,_)})):(h="POST",f=a);const g=Object.assign({},this.headers);return u&&(g.Prefer=`count=${u}`),new t.default({method:h,url:d,headers:g,schema:this.schemaName,body:f,fetch:this.fetch,allowEmpty:!1})}}return H.default=r,H}var st;function Xt(){if(st)return j;st=1;var n=j&&j.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(j,"__esModule",{value:!0}),j.PostgrestError=j.PostgrestBuilder=j.PostgrestTransformBuilder=j.PostgrestFilterBuilder=j.PostgrestQueryBuilder=j.PostgrestClient=void 0;const e=n(Yt());j.PostgrestClient=e.default;const t=n(St());j.PostgrestQueryBuilder=t.default;const s=n(Me());j.PostgrestFilterBuilder=s.default;const r=n(kt());j.PostgrestTransformBuilder=r.default;const i=n(mt());j.PostgrestBuilder=i.default;const o=n(bt());return j.PostgrestError=o.default,j.default={PostgrestClient:e.default,PostgrestQueryBuilder:t.default,PostgrestFilterBuilder:s.default,PostgrestTransformBuilder:r.default,PostgrestBuilder:i.default,PostgrestError:o.default},j}var Zt=Xt();const es=Dt(Zt),{PostgrestClient:ts,PostgrestQueryBuilder:Fr,PostgrestFilterBuilder:Wr,PostgrestTransformBuilder:Kr,PostgrestBuilder:Hr,PostgrestError:zr}=es;class ss{static dynamicRequire(e){try{return typeof process<"u"&&process.versions&&process.versions.node&&typeof require<"u"?require(e):null}catch{return null}}static detectEnvironment(){var e,t;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 s=parseInt(process.versions.node.split(".")[0]);if(s>=22)try{if(typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};const r=this.dynamicRequire("undici");if(r&&r.WebSocket)return{type:"native",constructor:r.WebSocket};throw new Error("undici not available")}catch{return{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:'Install the "ws" package or check your Node.js installation.'}}try{const r=this.dynamicRequire("ws");if(r)return{type:"ws",constructor:(t=r.WebSocket)!==null&&t!==void 0?t:r};throw new Error("ws package not available")}catch{return{type:"unsupported",error:`Node.js ${s} detected without WebSocket support.`,workaround:'Install the "ws" package: npm install 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 rs="2.15.0",is=`realtime-js/${rs}`,ns="1.0.0",$e=1e4,os=1e3,as=100;var le;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(le||(le={}));var T;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(T||(T={}));var R;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(R||(R={}));var Ce;(function(n){n.websocket="websocket"})(Ce||(Ce={}));var W;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(W||(W={}));class ls{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),i=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+i));o=o+i;const c=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}}class Et{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(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(k||(k={}));const rt=(n,e,t={})=>{var s;const r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((i,o)=>(i[o]=cs(o,n,e,r),i),{})},cs=(n,e,t,s)=>{const r=e.find(a=>a.name===n),i=r?.type,o=t[n];return i&&!s.includes(i)?Tt(i,o):Re(o)},Tt=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return fs(e,t)}switch(n){case k.bool:return us(e);case k.float4:case k.float8:case k.int2:case k.int4:case k.int8:case k.numeric:case k.oid:return hs(e);case k.json:case k.jsonb:return ds(e);case k.timestamp:return gs(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=n=>n,us=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},hs=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},ds=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},fs=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,s=n[t];if(n[0]==="{"&&s==="}"){let i;const o=n.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>Tt(e,a))}return n},gs=n=>typeof n=="string"?n.replace(" ","T"):n,jt=n=>{let e=n;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 it;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(it||(it={}));class ce{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ce.syncState(this.state,r,i,o),this.pendingDiffs.forEach(l=>{this.state=ce.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=ce.syncDiff(this.state,r,i,o),a())}),this.onJoin((r,i,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:i,newPresences:o})}),this.onLeave((r,i,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const i=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(i,(c,u)=>{o[c]||(l[c]=u)}),this.map(o,(c,u)=>{const h=i[c];if(h){const d=u.map(_=>_.presence_ref),f=h.map(_=>_.presence_ref),g=u.filter(_=>f.indexOf(_.presence_ref)<0),w=h.filter(_=>d.indexOf(_.presence_ref)<0);g.length>0&&(a[c]=g),w.length>0&&(l[c]=w)}else a[c]=u}),this.syncDiff(i,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){const{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(i,(a,l)=>{var c;const u=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),u.length>0){const h=e[a].map(f=>f.presence_ref),d=u.filter(f=>h.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,u,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const u=l.map(h=>h.presence_ref);c=c.filter(h=>u.indexOf(h.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(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):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 nt;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(nt||(nt={}));var ue;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(ue||(ue={}));var x;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(x||(x={}));class Fe{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=T.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,R.join,this.params,this.timeout),this.rejoinTimer=new Et(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=T.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=T.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this._on(R.reply,{},(r,i)=>{this._trigger(this._replyEventName(i),r)}),this.presence=new ce(this),this.broadcastEndpointURL=jt(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==T.closed){const{config:{broadcast:i,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[ue.PRESENCE]&&this.bindings[ue.PRESENCE].length>0,u={},h={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(d=>e?.(x.CHANNEL_ERROR,d)),this._onClose(()=>e?.(x.CLOSED)),this.updateJoinPayload(Object.assign({config:h},u)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:d})=>{var f;if(this.socket.setAuth(),d===void 0){e?.(x.SUBSCRIBED);return}else{const g=this.bindings.postgres_changes,w=(f=g?.length)!==null&&f!==void 0?f:0,_=[];for(let m=0;m{this.state=T.errored,e?.(x.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(d).join(", ")||"error")))}).receive("timeout",()=>{e?.(x.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===T.joined&&e===ue.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:i,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:i,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(i=>{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)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=T.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(R.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(r=>{s=new ke(this,R.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?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=T.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const r=new AbortController,i=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),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>as){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,i;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:u}=R;if(s&&[a,l,c,u].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,w,_;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((_=(w=f.filter)===null||w===void 0?void 0:w.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var g,w,_,m,A,p;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){const b=f.id,O=(g=f.filter)===null||g===void 0?void 0:g.event;return b&&((w=t.ids)===null||w===void 0?void 0:w.includes(b))&&(O==="*"||O?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const b=(A=(m=f?.filter)===null||m===void 0?void 0:m.event)===null||A===void 0?void 0:A.toLocaleLowerCase();return b==="*"||b===((p=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:w,table:_,commit_timestamp:m,type:A,errors:p}=g;d=Object.assign(Object.assign({},{schema:w,table:_,commit_timestamp:m,eventType:A,new:{},old:{},errors:p}),this._getPayloadRecords(g))}f.callback(d,s)})}_isClosed(){return this.state===T.closed}_isJoined(){return this.state===T.joined}_isJoining(){return this.state===T.joining}_isLeaving(){return this.state===T.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(r=>{var i;return!(((i=r.type)===null||i===void 0?void 0:i.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(R.close,{},e)}_onError(e){this._on(R.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=T.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=rt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=rt(e.columns,e.old_record)),t}}const ot=()=>{},pe={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},ps=[1e3,2e3,5e3,1e4],_s=1e4,vs=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class ys{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=pe.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ot,this.ref=0,this.reconnectTimer=null,this.logger=ot,this.conn=null,this.sendBuffer=[],this.serializer=new ls,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=r=>{let i;return r?i=r:typeof fetch>"u"?i=(...o)=>de(async()=>{const{default:a}=await Promise.resolve().then(()=>ie);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.`)}):i=fetch,(...o)=>i(...o)},!(!((s=t?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Ce.websocket}`,this.httpEndpoint=jt(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ss.createWebSocket(this.endpointURL())}catch(e){throw this._setConnectionState("disconnected"),new Error(`WebSocket not available: ${e.message}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:ns}))}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 le.connecting:return W.Connecting;case le.open:return W.Open;case le.closing:return W.Closing;default:return W.Closed}}isConnected(){return this.connectionState()===W.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const s=`realtime:${e}`,r=this.getChannels().find(i=>i.topic===s);if(r)return r;{const i=new Fe(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){const{topic:t,event:s,payload:r,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${i})`,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(os,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},pe.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:i,ref:o}=t,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${s} ${r} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(s)).forEach(c=>c._trigger(r,i,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(R.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([vs],{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:is};t&&s.updateJoinPayload(r),s.joinedOnce&&s._isJoined()&&s._push(R.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 Et(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},pe.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,r,i,o,a,l,c;if(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e?.timeout)!==null&&s!==void 0?s:$e,this.heartbeatIntervalMs=(r=e?.heartbeatIntervalMs)!==null&&r!==void 0?r:pe.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(u=>ps[u-1]||_s),this.encode=(l=e?.encode)!==null&&l!==void 0?l:((u,h)=>h(JSON.stringify(u))),this.decode=(c=e?.decode)!==null&&c!==void 0?c:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}}class We extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function P(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class ws 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 bs=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const Pt=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>de(async()=>{const{default:s}=await Promise.resolve().then(()=>ie);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},ms=()=>bs(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield de(()=>Promise.resolve().then(()=>ie),void 0)).Response:Response}),xe=n=>{if(Array.isArray(n))return n.map(t=>xe(t));if(typeof n=="function"||n!==Object(n))return n;const e={};return Object.entries(n).forEach(([t,s])=>{const r=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[r]=xe(s)}),e},ks=n=>{if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)};var K=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const Se=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Ss=(n,e,t)=>K(void 0,void 0,void 0,function*(){const s=yield ms();n instanceof s&&!t?.noResolveJson?n.json().then(r=>{const i=n.status||500,o=r?.statusCode||i+"";e(new ws(Se(r),i,o))}).catch(r=>{e(new Ie(Se(r),r))}):e(new Ie(Se(n),n))}),Es=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"||!s?r:(ks(s)?(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s)):r.body=s,Object.assign(Object.assign({},r),t))};function fe(n,e,t,s,r,i){return K(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,Es(e,s,r,i)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Ss(l,a,s))})})}function we(n,e,t,s){return K(this,void 0,void 0,function*(){return fe(n,"GET",e,t,s)})}function U(n,e,t,s,r){return K(this,void 0,void 0,function*(){return fe(n,"POST",e,s,r,t)})}function Ue(n,e,t,s,r){return K(this,void 0,void 0,function*(){return fe(n,"PUT",e,s,r,t)})}function Ts(n,e,t,s){return K(this,void 0,void 0,function*(){return fe(n,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function At(n,e,t,s,r){return K(this,void 0,void 0,function*(){return fe(n,"DELETE",e,s,r,t)})}var $=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const js={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},at={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Ps{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Pt(r)}uploadOrUpdate(e,t,s,r){return $(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},at),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?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l))):(i=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),r?.headers&&(a=Object.assign(Object.assign({},a),r.headers));const c=this._removeEmptyFolders(t),u=this._getFinalPath(c),h=yield(e=="PUT"?Ue:U)(this.fetch,`${this.url}/object/${u}`,i,Object.assign({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:h.Id,fullPath:h.Key},error:null}}catch(i){if(P(i))return{data:null,error:i};throw i}})}upload(e,t,s){return $(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return $(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:at.upsert},r),u=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,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const h=yield Ue(this.fetch,a.toString(),l,{headers:u});return{data:{path:i,fullPath:h.Key},error:null}}catch(l){if(P(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return $(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");const i=yield U(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+i.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(P(s))return{data:null,error:s};throw s}})}update(e,t,s){return $(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return $(this,void 0,void 0,function*(){try{return{data:yield U(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}copy(e,t,s){return $(this,void 0,void 0,function*(){try{return{data:{path:(yield U(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return $(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield U(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers});const o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return $(this,void 0,void 0,function*(){try{const r=yield U(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=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}${i}`):null})),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}download(e,t){return $(this,void 0,void 0,function*(){const r=typeof t?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(t?.transform||{}),o=i?`?${i}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield we(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(P(a))return{data:null,error:a};throw a}})}info(e){return $(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield we(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:xe(s),error:null}}catch(s){if(P(s))return{data:null,error:s};throw s}})}exists(e){return $(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield Ts(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(P(s)&&s instanceof Ie){const r=s.originalError;if([400,404].includes(r?.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],i=t?.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&r.push(i);const a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(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 $(this,void 0,void 0,function*(){try{return{data:yield At(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}list(e,t,s){return $(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},js),t),{prefix:e||""});return{data:yield U(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}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 As="2.10.4",Os={"X-Client-Info":`storage-js/${As}`};var Q=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};class $s{constructor(e,t={},s,r){const i=new URL(e);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),this.url=i.href,this.headers=Object.assign(Object.assign({},Os),t),this.fetch=Pt(s)}listBuckets(){return Q(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(P(e))return{data:null,error:e};throw e}})}getBucket(e){return Q(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Q(this,void 0,void 0,function*(){try{return{data:yield U(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(P(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Q(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(P(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Q(this,void 0,void 0,function*(){try{return{data:yield U(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Q(this,void 0,void 0,function*(){try{return{data:yield At(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}}class Cs extends $s{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new Ps(this.url,this.headers,e,this.fetch)}}const Rs="2.54.0";let ae="";typeof Deno<"u"?ae="deno":typeof document<"u"?ae="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ae="react-native":ae="node";const Is={"X-Client-Info":`supabase-js-${ae}/${Rs}`},xs={headers:Is},Us={schema:"public"},Ls={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ds={};var Ns=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const Bs=n=>{let e;return n?e=n:typeof fetch>"u"?e=yt:e=fetch,(...t)=>e(...t)},qs=()=>typeof Headers>"u"?wt:Headers,Ms=(n,e,t)=>{const s=Bs(t),r=qs();return(i,o)=>Ns(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:n;let c=new r(o?.headers);return c.has("apikey")||c.set("apikey",n),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(i,Object.assign(Object.assign({},o),{headers:c}))})};var Fs=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};function Ws(n){return n.endsWith("/")?n:n+"/"}function Ks(n,e){var t,s;const{db:r,auth:i,realtime:o,global:a}=n,{db:l,auth:c,realtime:u,global:h}=e,d={db:Object.assign(Object.assign({},l),r),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},u),o),storage:{},global:Object.assign(Object.assign(Object.assign({},h),a),{headers:Object.assign(Object.assign({},(t=h?.headers)!==null&&t!==void 0?t:{}),(s=a?.headers)!==null&&s!==void 0?s:{})}),accessToken:()=>Fs(this,void 0,void 0,function*(){return""})};return n.accessToken?d.accessToken=n.accessToken:delete d.accessToken,d}const Ot="2.71.1",te=30*1e3,Le=3,Ee=Le*te,Hs="http://localhost:9999",zs="supabase.auth.token",Js={"X-Client-Info":`gotrue-js/${Ot}`},De="X-Supabase-Api-Version",$t={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Gs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Vs=600*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(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class Qs extends Ke{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function Ys(n){return v(n)&&n.name==="AuthApiError"}class Ct extends Ke{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class B extends Ke{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class D extends B{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Xs(n){return v(n)&&n.name==="AuthSessionMissingError"}class _e extends B{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ve extends B{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ye extends B{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 Zs(n){return v(n)&&n.name==="AuthImplicitGrantRedirectError"}class lt extends B{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 B{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Te(n){return v(n)&&n.name==="AuthRetryableFetchError"}class ct extends B{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Be extends B{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ut=` \r=`.split(""),er=(()=>{const n=new Array(128);for(let e=0;e=6;){const s=e.queue>>e.queuedBits-6&63;t(be[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(be[s]),e.queuedBits-=6}}function Rt(n,e,t){const s=er[n];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(n)}"`)}}function dt(n){const e=[],t=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},r={queue:0,queuedBits:0},i=o=>{rr(o,s,t)};for(let o=0;o>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function sr(n,e){for(let t=0;t55295&&s<=56319){const r=(s-55296)*1024&65535;s=(n.charCodeAt(t+1)-56320&65535|r)+65536,t+=1}tr(s,e)}}function rr(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let s=1;s<6;s+=1)if((n>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function ir(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};for(let r=0;re.push(t)),new Uint8Array(e)}function or(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};return n.forEach(r=>ht(r,t,s)),ht(null,t,s),e.join("")}function ar(n){return Math.round(Date.now()/1e3)+n}function lr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n=="x"?e:e&3|8).toString(16)})}const C=()=>typeof window<"u"&&typeof document<"u",q={tested:!1,writable:!1},It=()=>{if(!C())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(q.tested)return q.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),q.tested=!0,q.writable=!0}catch{q.tested=!0,q.writable=!1}return q.writable};function cr(n){const e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,i)=>{e[i]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}const xt=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>de(async()=>{const{default:s}=await Promise.resolve().then(()=>ie);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},ur=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",se=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},M=async(n,e)=>{const t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},L=async(n,e)=>{await n.removeItem(e)};class me{constructor(){this.promise=new me.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}me.promiseConstructor=Promise;function je(n){const e=n.split(".");if(e.length!==3)throw new Be("Invalid JWT structure");for(let s=0;s{setTimeout(()=>e(null),n)})}function dr(n,e){return new Promise((s,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await n(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){r(o);return}}})()})}function fr(n){return("0"+n.toString(16)).substr(-2)}function gr(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let r="";for(let i=0;i<56;i++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,fr).join("")}async function pr(n){const t=new TextEncoder().encode(n),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(i=>String.fromCharCode(i)).join("")}async function _r(n){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."),n;const t=await pr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Y(n,e,t=!1){const s=gr();let r=s;t&&(r+="/PASSWORD_RECOVERY"),await se(n,`${e}-code-verifier`,r);const i=await _r(s);return[i,s===i?"plain":"s256"]}const vr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function yr(n){const e=n.headers.get(De);if(!e||!e.match(vr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function wr(n){if(!n)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function br(n){switch(n){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 mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function X(n){if(!mr.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Pe(){const n={};return new Proxy(n,{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 ft(n){return JSON.parse(JSON.stringify(n))}var kr=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);rn.msg||n.message||n.error_description||n.error||JSON.stringify(n),Sr=[502,503,504];async function gt(n){var e;if(!ur(n))throw new Ne(F(n),0);if(Sr.includes(n.status))throw new Ne(F(n),n.status);let t;try{t=await n.json()}catch(i){throw new Ct(F(i),i)}let s;const r=yr(n);if(r&&r.getTime()>=$t["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 ct(F(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new D}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((i,o)=>i&&typeof o=="string",!0))throw new ct(F(t),n.status,t.weak_password.reasons);throw new Qs(F(t),n.status||500,s)}const Er=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function y(n,e,t,s){var r;const i=Object.assign({},s?.headers);i[De]||(i[De]=$t["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Tr(n,e,t+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Tr(n,e,t,s,r,i){const o=Er(e,s,r,i);let a;try{a=await n(t,Object.assign({},o))}catch(l){throw console.error(l),new Ne(F(l),0)}if(a.ok||await gt(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await gt(l)}}function I(n){var e;let t=null;Or(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=ar(n.expires_in)));const s=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:s},error:null}}function pt(n){const e=I(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=n.weak_password),e}function N(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function jr(n){return{data:n,error:null}}function Pr(n){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:i}=n,o=kr(n,["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:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Ar(n){return n}function Or(n){return n.access_token&&n.refresh_token&&n.expires_in}const Ae=["global","local","others"];var $r=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r0&&(f.forEach(g=>{const w=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);c[`${_}Page`]=w}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(v(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){X(e);try{return await y(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:N})}catch(t){if(v(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){X(e);try{return await y(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:N})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){X(e);try{return await y(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:N})}catch(s){if(v(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){X(e.userId);try{const{data:t,error:s}=await y(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){X(e.userId),X(e.id);try{return{data:await y(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 _t(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}function Rr(){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 Z={debug:!!(globalThis&&It()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Ut extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ir extends Ut{}async function xr(n,e,t){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",n,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Z.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",n)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(n,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",n,r.name);try{return await t()}finally{Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",n,r.name)}}else{if(e===0)throw Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",n),new Ir(`Acquiring an exclusive Navigator LockManager lock "${n}" immediately failed`);if(Z.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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()}}))}Rr();const Ur={url:Hs,storageKey:zs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Js,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function vt(n,e,t){return await t()}const ee={};class he{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=he.nextInstanceID,he.nextInstanceID+=1,this.instanceID>0&&C()&&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({},Ur),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 Cr({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=xt(r.fetch),this.lock=r.lock||vt,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:C()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=xr:this.lock=vt,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:It()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=_t(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=_t(this.memoryStorage)),C()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}get jwks(){var e,t;return(t=(e=ee[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){ee[this.storageKey]=Object.assign(Object.assign({},ee[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=ee[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ee[this.storageKey]=Object.assign(Object.assign({},ee[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Ot}) ${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=cr(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),C()&&this.detectSessionInUrl&&s!=="none"){const{data:r,error:i}=await this._getSessionFromURL(t,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Zs(i)){const l=(e=i.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:i}}return await this._removeSession(),{error:i}}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 Ct("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:I}),{data:o,error:a}=i;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(i){if(v(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,s,r;try{let i;if("email"in e){const{email:u,password:h,options:d}=e;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await Y(this.storage,this.storageKey)),i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:u,password:h,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:g},xform:I})}else if("phone"in e){const{phone:u,password:h,options:d}=e;i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:I})}else throw new ve("You must provide either an email or phone number and a password");const{data:o,error:a}=i;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(i){if(v(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:i,password:o,options:a}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:pt})}else if("phone"in e){const{phone:i,password:o,options:a}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:pt})}else throw new ve("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 _e}:(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,i;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:(i=e.options)===null||i===void 0?void 0:i.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,i,o,a,l,c,u,h,d,f;let g,w;if("message"in e)g=e.message,w=e.signature;else{const{chain:_,wallet:m,statement:A,options:p}=e;let b;if(C())if(typeof m=="object")b=m;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"))b=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 m!="object"||!p?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=m}const O=new URL((t=p?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in b&&b.signIn){const S=await b.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},p?.signInWithSolana),{version:"1",domain:O.host,uri:O.href}),A?{statement:A}: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),w=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in b)||typeof b.signMessage!="function"||!("publicKey"in b)||typeof b!="object"||!b.publicKey||!("toBase58"in b.publicKey)||typeof b.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${O.host} wants you to sign in with your Solana account:`,b.publicKey.toBase58(),...A?["",A,""]:[""],"Version: 1",`URI: ${O.href}`,`Issued At: ${(r=(s=p?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&r!==void 0?r:new Date().toISOString()}`,...!((i=p?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${p.signInWithSolana.notBefore}`]:[],...!((o=p?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${p.signInWithSolana.expirationTime}`]:[],...!((a=p?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${p.signInWithSolana.chainId}`]:[],...!((l=p?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${p.signInWithSolana.nonce}`]:[],...!((c=p?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${p.signInWithSolana.requestId}`]:[],...!((h=(u=p?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...p.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(` `);const S=await b.signMessage(new TextEncoder().encode(g),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");w=S}}try{const{data:_,error:m}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:or(w)},!((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:I});if(m)throw m;return!_||!_.session||!_.user?{data:{user:null,session:null},error:new _e}:(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),{data:Object.assign({},_),error:m})}catch(_){if(v(_))return{data:{user:null,session:null},error:_};throw _}}async _exchangeCodeForSession(e){const t=await M(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/");try{const{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:I});if(await L(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new _e}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:r??null}),error:o})}catch(i){if(v(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:i,nonce:o}=e,a=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:I}),{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 _e}:(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,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Y(this.storage,this.storageKey));const{error:h}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:u}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:u}}throw new ve("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,i;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:I});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return 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 i=null,o=null;return this.flowType==="pkce"&&([i,o]=await Y(this.storage,this.storageKey)),await y(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?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:jr})}catch(i){if(v(i))return{data:null,error:i};throw i}}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 D;const{error:r}=await y(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:i}=e,{error:o}=await y(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:s,type:r,options:i}=e,{data:o,error:a}=await y(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new ve("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 M(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()(!o&&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,u))})}return{data:{session:e},error:null}}const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{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 y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:N}):await this._useSession(async t=>{var s,r,i;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 D}:await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0,xform:N})})}catch(t){if(v(t))return Xs(t)&&(await this._removeSession(),await L(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:i}=s;if(i)throw i;if(!r.session)throw new D;const o=r.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Y(this.storage,this.storageKey));const{data:c,error:u}=await y(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:N});if(u)throw u;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 D;const t=Date.now()/1e3;let s=t,r=!0,i=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};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;i={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(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},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?.refresh_token)throw new D;const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}: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(!C())throw new ye("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ye(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 lt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ye("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 lt("No code detected.");const{data:A,error:p}=await this._exchangeCodeForSession(e.code);if(p)throw p;const b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:A.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new ye("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(a);let d=u+h;l&&(d=parseInt(l));const f=d-u;f*1e3<=te&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const g=d-h;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,u):u-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,u);const{data:w,error:_}=await this._getUser(i);if(_)throw _;const m={provider_token:s,provider_refresh_token:r,access_token:i,expires_in:h,expires_at:d,refresh_token:o,token_type:c,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:m,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 M(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:i}=t;if(i)return{error:i};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&&!(Ys(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await L(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=lr(),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:i},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){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",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await Y(this.storage,this.storageKey,!0));try{return await y(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(i){if(v(i))return{data:null,error:i};throw i}}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 i=>{var o,a,l,c,u;const{data:h,error:d}=i;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 y(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(r)throw r;return C()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(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:i,error:o}=t;if(o)throw o;return await y(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=i.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 dr(async r=>(r>0&&await hr(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:I})),(r,i)=>{const o=200*Math.pow(2,r);return i&&Te(i)&&Date.now()+o-s{try{await a.callback(e,t)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;athis._autoRefreshTokenTick(),te);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)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${te}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 Ut)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!C()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){const r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,o]=await Y(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){const i=new URLSearchParams(s.queryParams);r.push(i.toString())}return 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:i}=t;return i?{data:null,error:i}:await y(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=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:i,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 y(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&(!((r=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:i}=t;if(i)return{data:null,error:i};const{data:o,error:a}=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=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:i}=t;return i?{data:null,error:i}:await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(s=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?.factors||[],r=s.filter(o=>o.factor_type==="totp"&&o.status==="verified"),i=s.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:s,totp:r,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:r},error:i}=e;if(i)return{data:null,error:i};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(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");const u=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:u},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+Vs>r)return s;const{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=r,s=i.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:i,signature:o,raw:{header:a,payload:l}}=je(s);t?.allowExpired||wr(i.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?.keys?{keys:t.keys}:t?.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:r,signature:o},error:null}}const u=br(r.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,o,nr(`${a}.${l}`)))throw new Be("Invalid JWT signature");return{data:{claims:i,header:r,signature:o},error:null}}catch(s){if(v(s))return{data:null,error:s};throw s}}}he.nextInstanceID=0;const Lr=he;class Dr extends Lr{constructor(e){super(e)}}var Nr=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):r(u.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};class Br{constructor(e,t,s){var r,i,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=Ws(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`,u={db:Us,realtime:Ds,auth:Object.assign(Object.assign({},Ls),{storageKey:c}),global:xs},h=Ks(s??{},u);this.storageKey=(r=h.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.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=h.auth)!==null&&o!==void 0?o:{},this.headers,h.global.fetch),this.fetch=Ms(t,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new ts(new URL("rest/v1",l).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),this.storage=new Cs(this.storageUrl.href,this.headers,this.fetch,s?.storage),h.accessToken||this._listenForAuthEvents()}get functions(){return new Wt(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 Nr(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:i,flowType:o,lock:a,debug:l},c,u){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Dr({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,lock:a,debug:l,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new ys(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?this.changedAccessToken=s:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Jr=(n,e,t)=>new Br(n,e,t);function qr(){if(typeof window<"u"||typeof process>"u")return!1;const n=process.version;if(n==null)return!1;const e=n.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}qr()&&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{Jr as c};