1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CzN0SCRv.js","assets/index-BAFf3ThT.css"])))=>i.map(i=>d[i]); 2import{bz as Ee,cb as As,cc as Cs,X as Rs,K as $s,r as L,c2 as Is,L as Us,Y as j,N as Ct,j as g,_ as Le,$ as Ne,a0 as Ls,cd as Xe,a1 as Ze,a2 as De,J as he,bk as Rt,ak as $t,au as It,a5 as Ut,a3 as Ns,aa as Ds,c8 as Bs,aC as qs,ce as Ms,cf as Fs,cg as Hs}from"./index-CzN0SCRv.js";const Ws=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>Ee(async()=>{const{default:s}=await Promise.resolve().then(()=>je);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};class mt extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class Ks extends mt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Lt extends mt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Nt extends mt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var ct;(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"})(ct||(ct={}));var Js=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};class zs{constructor(e,{headers:t={},customFetch:s,region:r=ct.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Ws(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Js(this,void 0,void 0,function*(){try{const{headers:r,method:i,body:a}=t;let o={},{region:l}=t;l||(l=this.region);const c=new URL(`${this.url}/${e}`);l&&l!=="any"&&(o["x-region"]=l,c.searchParams.set("forceFunctionRegion",l));let u;a&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&a instanceof Blob||a instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",u=a):typeof a=="string"?(o["Content-Type"]="text/plain",u=a):typeof FormData<"u"&&a instanceof FormData?u=a:(o["Content-Type"]="application/json",u=JSON.stringify(a)));const h=yield this.fetch(c.toString(),{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),r),body:u}).catch(w=>{throw new Ks(w)}),d=h.headers.get("x-relay-error");if(d&&d==="true")throw new Lt(h);if(!h.ok)throw new Nt(h);let f=((s=h.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield h.json():f==="application/octet-stream"?p=yield h.blob():f==="text/event-stream"?p=h:f==="multipart/form-data"?p=yield h.formData():p=yield h.text(),{data:p,error:null,response:h}}catch(r){return{data:null,error:r,response:r instanceof Nt||r instanceof Lt?r.context:void 0}}})}}var I={},de={},fe={},ge={},pe={},we={},Gs=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")},Te=Gs();const Vs=Te.fetch,ns=Te.fetch.bind(Te),as=Te.Headers,Ys=Te.Request,Qs=Te.Response,je=Object.freeze(Object.defineProperty({__proto__:null,Headers:as,Request:Ys,Response:Qs,default:ns,fetch:Vs},Symbol.toStringTag,{value:"Module"})),Xs=As(je);var Be={},Dt;function os(){if(Dt)return Be;Dt=1,Object.defineProperty(Be,"__esModule",{value:!0});class n extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
2de=t.code}}return Be.default=n,Be}var Bt;function ls(){if(Bt)return we;Bt=1;var n=we&&we.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(we,"__esModule",{value:!0});const e=n(Xs),t=n(os());class s{constructor(i){var a,o;this.shouldThrowOnError=!1,this.method=i.method,this.url=i.url,this.headers=new Headers(i.headers),this.schema=i.schema,this.body=i.body,this.shouldThrowOnError=(a=i.shouldThrowOnError)!==null&&a!==void 0?a:!1,this.signal=i.signal,this.isMaybeSingle=(o=i.isMaybeSingle)!==null&&o!==void 0?o:!1,i.fetch?this.fetch=i.fetch:typeof fetch>"u"?this.fetch=e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(i,a){return this.headers=new Headers(this.headers),this.headers.set(i,a),this}then(i,a){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const o=this.fetch;let l=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async c=>{var u,h,d,f;let p=null,w=null,_=null,S=c.status,E=c.statusText;if(c.ok){if(this.method!=="HEAD"){const m=await c.text();m===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((u=this.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text"))?w=m:w=JSON.parse(m))}const k=(h=this.headers.get("Prefer"))===null||h===void 0?void 0:h.match(/count=(exact|planned|estimated)/),R=(d=c.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");k&&R&&R.length>1&&(_=parseInt(R[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(w)&&(w.length>1?(p={code:"PGRST116",details:`Results contain ${w.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},w=null,_=null,S=406,E="Not Acceptable"):w.length===1?w=w[0]:w=null)}else{const k=await c.text();try{p=JSON.parse(k),Array.isArray(p)&&c.status===404&&(w=[],p=null,S=200,E="OK")}catch{c.status===404&&k===""?(S=204,E="No Content"):p={message:k}}if(p&&this.isMaybeSingle&&(!((f=p==null?void 0:p.details)===null||f===void 0)&&f.includes("0 rows"))&&(p=null,S=200,E="OK"),p&&this.shouldThrowOnError)throw new t.default(p)}return{error:p,data:w,count:_,status:S,statusText:E}});return this.shouldThrowOnError||(l=l.catch(c=>{var u,h,d;return{error:{message:`${(u=c==null?void 0:c.name)!==null&&u!==void 0?u:"FetchError"}: ${c==null?void 0:c.message}`,details:`${(h=c==null?void 0:c.stack)!==null&&h!==void 0?h:""}`,hint:"",code:`${(d=c==null?void 0:c.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),l.then(i,a)}returns(){return this}overrideTypes(){return this}}return we.default=s,we}var qt;function cs(){if(qt)return pe;qt=1;var n=pe&&pe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pe,"__esModule",{value:!0});const e=n(ls());class t extends e.default{select(r){let i=!1;const a=(r??"*").split("").map(o=>/\s/.test(o)&&!i?"":(o==='"'&&(i=!i),o)).join("");return this.url.searchParams.set("select",a),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:i=!0,nullsFirst:a,foreignTable:o,referencedTable:l=o}={}){const c=l?`${l}.order`:"order",u=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${u?`${u},`:""}${r}.${i?"asc":"desc"}${a===void 0?"":a?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:i,referencedTable:a=i}={}){const o=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(o,`${r}`),this}range(r,i,{foreignTable:a,referencedTable:o=a}={}){const l=typeof o>"u"?"offset":`${o}.offset`,c=typeof o>"u"?"limit":`${o}.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.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
2explain({analyze:r=!1,verbose:i=!1,settings:a=!1,buffers:o=!1,wal:l=!1,format:c="text"}={}){var u;const h=[r?"analyze":null,i?"verbose":null,a?"settings":null,o?"buffers":null,l?"wal":null].filter(Boolean).join("|"),d=(u=this.headers.get("Accept"))!==null&&u!==void 0?u:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${c}; for="${d}"; options=${h};`),c==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}}return pe.default=t,pe}var Mt;function bt(){if(Mt)return ge;Mt=1;var n=ge&&ge.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ge,"__esModule",{value:!0});const e=n(cs());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 a=Array.from(new Set(i)).map(o=>typeof o=="string"&&new RegExp("[,()]").test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(r,`in.(${a})`),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:a,type:o}={}){let l="";o==="plain"?l="pl":o==="phrase"?l="ph":o==="websearch"&&(l="w");const c=a===void 0?"":`(${a})`;return this.url.searchParams.append(r,`${l}fts${c}.${i}`),this}match(r){return Object.entries(r).forEach(([i,a])=>{this.url.searchParams.append(i,`eq.${a}`)}),this}not(r,i,a){return this.url.searchParams.append(r,`not.${i}.${a}`),this}or(r,{foreignTable:i,referencedTable:a=i}={}){const o=a?`${a}.or`:"or";return this.url.searchParams.append(o,`(${r})`),this}filter(r,i,a){return this.url.searchParams.append(r,`${i}.${a}`),this}}return ge.default=t,ge}var Ft;function us(){if(Ft)return fe;Ft=1;var n=fe&&fe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(fe,"__esModule",{value:!0});const e=n(bt());class t{constructor(r,{headers:i={},schema:a,fetch:o}){this.url=r,this.headers=new Headers(i),this.schema=a,this.fetch=o}select(r,{head:i=!1,count:a}={}){const o=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),a&&this.headers.append("Prefer",`count=${a}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(r,{count:i,defaultToNull:a=!0}={}){var o;const l="POST";if(i&&this.headers.append("Prefer",`count=${i}`),a||this.headers.append("Prefer","missing=default"),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:l,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}upsert(r,{onConflict:i,ignoreDuplicates:a=!1,count:o,defaultToNull:l=!0}={}){var c;const u="POST";if(this.headers.append("Prefer",`resolution=${a?"ignore":"merge"}-duplicates`),i!==void 0&&this.url.searchParams.set("on_conflict",i),o&&this.headers.append("Prefer",`count=${o}`),l||this.headers.append("Prefer","missing=default"),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:u,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}update(r,{count:i}={}){var a;const o="PATCH";return i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}delete({count:r}={}){var i;const a="DELETE";return r&&this.headers.append("Prefer",`count=${r}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}}return fe.default=t,fe}var Ht;function Zs(){if(Ht)return de;Ht=1;var n=de&&de.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};
2Object.defineProperty(de,"__esModule",{value:!0});const e=n(us()),t=n(bt());class s{constructor(i,{headers:a={},schema:o,fetch:l}={}){this.url=i,this.headers=new Headers(a),this.schemaName=o,this.fetch=l}from(i){const a=new URL(`${this.url}/${i}`);return new e.default(a,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(i){return new s(this.url,{headers:this.headers,schema:i,fetch:this.fetch})}rpc(i,a={},{head:o=!1,get:l=!1,count:c}={}){var u;let h;const d=new URL(`${this.url}/rpc/${i}`);let f;o||l?(h=o?"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 p=new Headers(this.headers);return c&&p.set("Prefer",`count=${c}`),new t.default({method:h,url:d,headers:p,schema:this.schemaName,body:f,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}}return de.default=s,de}var Wt;function er(){if(Wt)return I;Wt=1;var n=I&&I.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(I,"__esModule",{value:!0}),I.PostgrestError=I.PostgrestBuilder=I.PostgrestTransformBuilder=I.PostgrestFilterBuilder=I.PostgrestQueryBuilder=I.PostgrestClient=void 0;const e=n(Zs());I.PostgrestClient=e.default;const t=n(us());I.PostgrestQueryBuilder=t.default;const s=n(bt());I.PostgrestFilterBuilder=s.default;const r=n(cs());I.PostgrestTransformBuilder=r.default;const i=n(ls());I.PostgrestBuilder=i.default;const a=n(os());return I.PostgrestError=a.default,I.default={PostgrestClient:e.default,PostgrestQueryBuilder:t.default,PostgrestFilterBuilder:s.default,PostgrestTransformBuilder:r.default,PostgrestBuilder:i.default,PostgrestError:a.default},I}var tr=er();const sr=Cs(tr),{PostgrestClient:rr,PostgrestQueryBuilder:Ji,PostgrestFilterBuilder:zi,PostgrestTransformBuilder:Gi,PostgrestBuilder:Vi,PostgrestError:Yi}=sr;class ir{static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"){const t=process.versions;if(t&&t.node){const s=t.node,r=parseInt(s.replace(/^v/,"").split(".")[0]);return r>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 3import ws from "ws" 4new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=` 5 6Suggested 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 nr="2.15.5",ar=`realtime-js/${nr}`,or="1.0.0",ut=1e4,lr=1e3,cr=100;var Ae;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(Ae||(Ae={}));var A;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(A||(A={}));var W;(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"})(W||(W={}));var ht;(function(n){n.websocket="websocket"})(ht||(ht={}));var ne;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(ne||(ne={}));class ur{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;
6return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),i=t.getUint8(2);let a=this.HEADER_LENGTH+2;const o=s.decode(e.slice(a,a+r));a=a+r;const l=s.decode(e.slice(a,a+i));a=a+i;const c=JSON.parse(s.decode(e.slice(a,e.byteLength)));return{ref:null,topic:o,event:l,payload:c}}}class hs{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var x;(function(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"})(x||(x={}));const Kt=(n,e,t={})=>{var s;const r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((i,a)=>(i[a]=hr(a,n,e,r),i),{})},hr=(n,e,t,s)=>{const r=e.find(o=>o.name===n),i=r==null?void 0:r.type,a=t[n];return i&&!s.includes(i)?ds(i,a):dt(a)},ds=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return pr(e,t)}switch(n){case x.bool:return dr(e);case x.float4:case x.float8:case x.int2:case x.int4:case x.int8:case x.numeric:case x.oid:return fr(e);case x.json:case x.jsonb:return gr(e);case x.timestamp:return wr(e);case x.abstime:case x.date:case x.daterange:case x.int4range:case x.int8range:case x.money:case x.reltime:case x.text:case x.time:case x.timestamptz:case x.timetz:case x.tsrange:case x.tstzrange:return dt(e);default:return dt(e)}},dt=n=>n,dr=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},fr=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},gr=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},pr=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,s=n[t];if(n[0]==="{"&&s==="}"){let i;const a=n.slice(1,t);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>ds(e,o))}return n},wr=n=>typeof n=="string"?n.replace(" ","T"):n,fs=n=>{let e=n;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class et{constructor(e,t,s={},r=ut){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 Jt;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(Jt||(Jt={}));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==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{const{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Ce.syncState(this.state,r,i,a),this.pendingDiffs.forEac
6h(l=>{this.state=Ce.syncDiff(this.state,l,i,a)}),this.pendingDiffs=[],o()}),this.channel._on(s.diff,{},r=>{const{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=Ce.syncDiff(this.state,r,i,a),o())}),this.onJoin((r,i,a)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:i,newPresences:a})}),this.onLeave((r,i,a)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:i,leftPresences:a})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const i=this.cloneDeep(e),a=this.transformState(t),o={},l={};return this.map(i,(c,u)=>{a[c]||(l[c]=u)}),this.map(a,(c,u)=>{const h=i[c];if(h){const d=u.map(_=>_.presence_ref),f=h.map(_=>_.presence_ref),p=u.filter(_=>f.indexOf(_.presence_ref)<0),w=h.filter(_=>d.indexOf(_.presence_ref)<0);p.length>0&&(o[c]=p),w.length>0&&(l[c]=w)}else o[c]=u}),this.syncDiff(i,{joins:o,leaves:l},s,r)}static syncDiff(e,t,s,r){const{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(i,(o,l)=>{var c;const u=(c=e[o])!==null&&c!==void 0?c:[];if(e[o]=this.cloneDeep(l),u.length>0){const h=e[o].map(f=>f.presence_ref),d=u.filter(f=>h.indexOf(f.presence_ref)<0);e[o].unshift(...d)}s(o,u,l)}),this.map(a,(o,l)=>{let c=e[o];if(!c)return;const u=l.map(h=>h.presence_ref);c=c.filter(h=>u.indexOf(h.presence_ref)<0),e[o]=c,r(o,c,l),c.length===0&&delete e[o]}),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 zt;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(zt||(zt={}));var Re;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(Re||(Re={}));var V;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(V||(V={}));class kt{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=A.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 et(this,W.join,this.params,this.timeout),this.rejoinTimer=new hs(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=A.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=A.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=A.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=A.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=A.errored,this.rejoinTimer.scheduleTimeout())}),this._on(W.reply,{},(r,i)=>{this._trigger(this._replyEventName(i),r)}),this.presence=new Ce(this),this.broadcastEndpointURL=fs(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r,i;if(this.socket.isConnected()||this.socket.connect(),this.state==A.closed){const{config:{broadcast:a,presence:o,private:l}}=this.params,c=(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&r!==void 0?r:[],u=!!this.bindings[Re.PRESENCE]&&this.bindings[Re.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},d={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(f=>e==null?void 0:e(V.CHANNEL_ERROR,f)),this._onClose(()=>e==null?void 0:e(V.CLOSED)),this.updateJoinPayload(Object.assign({config:d},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:f})=>{var p;if(this.socket.setAuth(),f===void 0){e==null||e(V.SUBSCRIBED);return}else{const w=this.bindings.postgres_changes,_=(p=w==null?void 0:w.length)!==null&&p!==void 0?p:0,S=[];for(let E=0;E<_;E++){const v=w[E],{filter:{event:k,schema:R,table:m,filter:U}}=v,J=f&&f[E];if(J&&J.event===k&&J.schema===R&&J.table===m&&J.filter===U)S.push(Object.assign(Object.assign({},v),{id:J.id}));else{this.unsubscribe(),this.state=A.errored,e==null||e(V.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=S,e&&e(V.SUBSCRIBED);return}}).receive("error",f=>{this.state=A.errored,e==null||e(V.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(V.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===A.joined&&e===Re.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:a}=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:a,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 a,o,l;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.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=A.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(W.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(r=>{s=new et(this,W.leave,{},e),s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s==null||s.destroy()})}
6teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=A.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const r=new AbortController,i=setTimeout(()=>r.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),a}_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 et(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>cr){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 a=e.toLocaleLowerCase(),{close:o,error:l,leave:c,join:u}=W;if(s&&[o,l,c,u].indexOf(a)>=0&&s!==this._joinRef())return;let d=this._onMessage(a,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(f=>{var p,w,_;return((p=f.filter)===null||p===void 0?void 0:p.event)==="*"||((_=(w=f.filter)===null||w===void 0?void 0:w.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===a}).map(f=>f.callback(d,s)):(i=this.bindings[a])===null||i===void 0||i.filter(f=>{var p,w,_,S,E,v;if(["broadcast","presence","postgres_changes"].includes(a))if("id"in f){const k=f.id,R=(p=f.filter)===null||p===void 0?void 0:p.event;return k&&((w=t.ids)===null||w===void 0?void 0:w.includes(k))&&(R==="*"||(R==null?void 0:R.toLocaleLowerCase())===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const k=(E=(S=f==null?void 0:f.filter)===null||S===void 0?void 0:S.event)===null||E===void 0?void 0:E.toLocaleLowerCase();return k==="*"||k===((v=t==null?void 0:t.event)===null||v===void 0?void 0:v.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===a}).map(f=>{if(typeof d=="object"&&"ids"in d){const p=d.data,{schema:w,table:_,commit_timestamp:S,type:E,errors:v}=p;d=Object.assign(Object.assign({},{schema:w,table:_,commit_timestamp:S,eventType:E,new:{},old:{},errors:v}),this._getPayloadRecords(p))}f.callback(d,s)})}_isClosed(){return this.state===A.closed}_isJoined(){return this.state===A.joined}_isJoining(){return this.state===A.joining}_isLeaving(){return this.state===A.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&&kt.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(W.close,{},e)}_onError(e){this._on(W.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=A.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Kt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Kt(e.columns,e.old_record)),t}}const tt=()=>{},qe={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},vr=[1e3,2e3,5e3,1e4],_r=1e4,yr=` 7 addEventListener("message", (e) => { 8 if (e.data.event === "start") { 9 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 10 } 11 });`;class mr{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=ut,this.transport=null,this.heartbeatIntervalMs=qe.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=tt,this.ref=0,this.reconnectTimer=null,this.logger=tt,this.conn=null,this.sendBuffer=[],this.serializer
11=new ur,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=(...a)=>Ee(async()=>{const{default:o}=await Promise.resolve().then(()=>je);return{default:o}},void 0).then(({default:o})=>o(...a)).catch(o=>{throw new Error(`Failed to load @supabase/node-fetch: ${o.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):i=fetch,(...a)=>i(...a)},!(!((s=t==null?void 0:t.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${ht.websocket}`,this.httpEndpoint=fs(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t==null?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ir.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t} 12 13To use Realtime in Node.js, you need to provide a WebSocket implementation: 14 15Option 1: Use Node.js 22+ which has native WebSocket support 16Option 2: Install and provide the "ws" package: 17 18 npm install ws 19 20 import ws from "ws" 21 const client = new RealtimeClient(url, { 22 ...options, 23 transport: ws 24 })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:or}))}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 Ae.connecting:return ne.Connecting;case Ae.open:return ne.Open;case Ae.closing:return ne.Closing;default:return ne.Closed}}isConnected(){return this.connectionState()===ne.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 kt(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){const{topic:t,event:s,payload:r,ref:i}=e,a=()=>{this.encode(e,o=>{var l;(l=this.conn)===null||l===void 0||l.send(o)})};this.log("push",`${t} ${s} (${i})`,r),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(lr,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},qe.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>
240&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:s,event:r,payload:i,ref:a}=t,o=a?`(${a})`:"",l=i.status||"";this.log("receive",`${l} ${s} ${r} ${o}`.trim(),i),this.channels.filter(c=>c._isMember(s)).forEach(c=>c._trigger(r,i,a)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(W.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([yr],{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:ar};t&&s.updateJoinPayload(r),s.joinedOnce&&s._isJoined()&&s._push(W.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 hs(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},qe.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,r,i,a,o,l,c,u;if(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e
24==null?void 0:e.timeout)!==null&&s!==void 0?s:ut,this.heartbeatIntervalMs=(r=e==null?void 0:e.heartbeatIntervalMs)!==null&&r!==void 0?r:qe.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(a=e==null?void 0:e.accessToken)!==null&&a!==void 0?a:null,this.heartbeatCallback=(o=e==null?void 0:e.heartbeatCallback)!==null&&o!==void 0?o:tt,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=e==null?void 0:e.reconnectAfterMs)!==null&&l!==void 0?l:(h=>vr[h-1]||_r),this.encode=(c=e==null?void 0:e.encode)!==null&&c!==void 0?c:((h,d)=>d(JSON.stringify(h))),this.decode=(u=e==null?void 0:e.decode)!==null&&u!==void 0?u:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}class St extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function C(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class br extends St{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 ft extends St{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var kr=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};const gs=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>Ee(async()=>{const{default:s}=await Promise.resolve().then(()=>je);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Sr=()=>kr(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Ee(()=>Promise.resolve().then(()=>je),void 0)).Response:Response}),gt=n=>{if(Array.isArray(n))return n.map(t=>gt(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]=gt(s)}),e},Tr=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 ae=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};const st=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Er=(n,e,t)=>ae(void 0,void 0,void 0,function*(){const s=yield Sr();n instanceof s&&!(t!=null&&t.noResolveJson)?n.json().then(r=>{const i=n.status||500,a=(r==null?void 0:r.statusCode)||i+"";e(new br(st(r),i,a))}).catch(r=>{e(new ft(st(r),r))}):e(new ft(st(n),n))}),jr=(n,e,t,s)=>{const r={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"||!s?r:(Tr(s)?(r.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),r.body=JSON.stringify(s)):r.body=s,e!=null&&e.duplex&&(r.duplex=e.duplex),Object.assign(Object.assign({},r),t))};function Ie(n,e,t,s,r,i){return ae(this,void 0,void 0,function*(){return new Promise((a,o)=>{n(t,jr(e,s,r,i)).then(l=>{if(!l.ok)throw l;return s!=null&&s.noResolveJson?l:l.json()}).then(l=>a(l)).catch(l=>Er(l,o,s))})})}function Ke(n,e,t,s){return ae(this,void 0,void 0,function*(){return Ie(n,"GET",e,t,s)})}function K(n,e,t,s,r){return ae(this,void 0,void 0,function*(){return Ie(n,"POST",e,s,r,t)})}function pt(n,e,t,s,r){return ae(this,void 0,void 0,function*(){return Ie(n,"PUT",e,s,r,t)})}function xr(n,e,t,s){return ae(this,void 0,void 0,function*(){return Ie(n,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function ps(n,e,t,s,r){return ae(this,void 0,void 0,function*(){return Ie(n,"DELETE",e,s,r,t)})}var D=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};const Pr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Gt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Or{constructor(e,t={},s,r){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=s,this.fetch=gs(r)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,r){return D(this,void 0,void 0,function*(){try{let i;const a=Object.assign(Object.assign({},Gt),r);let o=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;typeof Blob<"u"&&s instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",this.encodeMetadata(l))):(i=s,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),r!=null&&r.headers&&(o=Object.assign(Object.assign({},o),r.headers));const c=this._removeEmptyFolders(t),u=this._getFinalPath(c),h=yield(e=="PUT"?pt:K)(this.fetch,`${this.url}/object/${u}`,i,Object.assign({headers:o},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{data:{path:c,id:h.Id,fullPath:h.Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(C(i))return{data:null,error:i};throw i}})}upload(e,t,s){return D(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return D(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),a=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${a}`);o.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:Gt.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 pt(this.fetch,o.toString(),l,{headers:u});return{data:{path:i,fullPath:h.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(C(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return D(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);t!=null&&t.upsert&&(r["x-upsert"]="true");const i=yield K(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),a=new URL(this.url+i.url),o=a.searchParams.get("token");if(!o)throw new St("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:o},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(C(s))return{data:null,error:s};throw s}})}
24update(e,t,s){return D(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return D(this,void 0,void 0,function*(){try{return{data:yield K(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s==null?void 0:s.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(C(r))return{data:null,error:r};throw r}})}copy(e,t,s){return D(this,void 0,void 0,function*(){try{return{data:{path:(yield K(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s==null?void 0:s.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(C(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return D(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield K(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s!=null&&s.transform?{transform:s.transform}:{}),{headers:this.headers});const a=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(C(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return D(this,void 0,void 0,function*(){try{const r=yield K(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=s!=null&&s.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(a=>Object.assign(Object.assign({},a),{signedUrl:a.signedURL?encodeURI(`${this.url}${a.signedURL}${i}`):null})),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(C(r))return{data:null,error:r};throw r}})}download(e,t){return D(this,void 0,void 0,function*(){const r=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),a=i?`?${i}`:"";try{const o=this._getFinalPath(e);return{data:yield(yield Ke(this.fetch,`${this.url}/${r}/${o}${a}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(this.shouldThrowOnError)throw o;if(C(o))return{data:null,error:o};throw o}})}info(e){return D(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield Ke(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:gt(s),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(C(s))return{data:null,error:s};throw s}})}exists(e){return D(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield xr(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(C(s)&&s instanceof ft){const r=s.originalError;if([400,404].includes(r==null?void 0:r.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],i=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&r.push(i);const o=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});l!==""&&r.push(l);let c=r.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${s}${c}`)}}}remove(e){return D(this,void 0,void 0,function*(){try{return{data:yield ps(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(C(t))return{data:null,error:t};throw t}})}list(e,t,s){return D(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},Pr),t),{prefix:e||""});return{data:yield K(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(C(r))return{data:null,error:r};throw r}})}listV2(e,t){return D(this,void 0,void 0,function*(){try{const s=Object.assign({},e);return{data:yield K(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(C(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const Ar="2.12.1",Cr={"X-Client-Info":`storage-js/${Ar}`};var ve=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};class Rr{constructor(e,t={},s,r){this.shouldThrowOnError=!1;const i=new URL(e);r!=null&&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({},Cr),t),this.fetch=gs(s)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return ve(this,void 0,void 0,function*(){try{return{data:yield Ke(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(C(e))return{data:null,error:e};throw e}})}getBucket(e){return ve(this,void 0,void 0,function*(){try{return{data:yield Ke(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(C(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ve(this,void 0,void 0,function*(){try{return{data:yield K(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(C(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return ve(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(C(s))return{data:null,error:s};throw s}})}emptyBucket(e){return ve(this,void 0,void 0,function*(){try{return{data:yield K(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(C(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ve(this,void 0,void 0,function*(){try{return{data:yield ps(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(C(t))return{data:null,error:t};throw t}})}}class $r extends Rr{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new Or(this.url,this.headers,e,this.fetch)}}const Ir="2.57.4";let Oe="";typeof Deno<"u"?Oe="deno":typeof document<"u"?Oe="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Oe="react-native":Oe="node";const Ur={"X-Client-Info":`supabase-js-${Oe}/${Ir}`},Lr={headers:Ur},Nr={schema:"public"},Dr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Br={};var qr=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};const Mr=n=>{let e;return n?e=n:typeof fetch>"u"?e=ns:e=fetch,(...t)=>e(...t)},Fr=()=>typeof Headers>"u"?as:Headers,Hr=(n,e,t)=>{const s=Mr(t),r=Fr();return(i,a)=>qr(void 0,void 0,void 0,function*(){var o;const l=(o=yield e())!==null&&o!==void 0?o:n;let c=new r(a==null?void 0:a.headers);return c.has("apikey")||c.set("apikey",n),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(i,Object.assign(Object.assign({},a),{headers:c}))})};var Wr=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};function Kr(n){return n.endsWith("/")?n:n+"/"}function Jr(n,e){var t,s;const{db:r,auth:i,realtime:a,global:o}=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),a),storage:{},global:Object.assign(Object.assign(Object.assign({},h),o),{headers:Object.assign(Object.assign({},(t=h==null?void 0:h.headers)!==null&&t!==void 0?t:{}),(s=o==null?void 0:o.headers)!==null&&s!==void 0?s:{})}),accessToken:()=>Wr(this,void 0,void 0,function*(){return""})};return n.accessToken?d.accessToken=n.accessToken:delete d.accessToken,d}function zr(n){const e=n==null?void 0:n.trim();if(!e)throw new Error("supabaseUrl is required.");
24if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Kr(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const ws="2.71.1",ke=30*1e3,wt=3,rt=wt*ke,Gr="http://localhost:9999",Vr="supabase.auth.token",Yr={"X-Client-Info":`gotrue-js/${ws}`},vt="X-Supabase-Api-Version",vs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Qr=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Xr=600*1e3;class Tt extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function y(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class Zr extends Tt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function ei(n){return y(n)&&n.name==="AuthApiError"}class _s extends Tt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class ee extends Tt{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class X extends ee{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ti(n){return y(n)&&n.name==="AuthSessionMissingError"}class Me extends ee{constructor(){super("Auth session or user missing","AuthInvalidToken
24ResponseError",500,void 0)}}class Fe extends ee{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class He extends ee{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 si(n){return y(n)&&n.name==="AuthImplicitGrantRedirectError"}class Vt extends ee{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 _t extends ee{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function it(n){return y(n)&&n.name==="AuthRetryableFetchError"}class Yt extends ee{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class yt extends ee{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Je="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Qt=` 25\r=`.split(""),ri=(()=>{const n=new Array(128);for(let e=0;e<n.length;e+=1)n[e]=-1;for(let e=0;e<Qt.length;e+=1)n[Qt[e].charCodeAt(0)]=-2;for(let e=0;e<Je.length;e+=1)n[Je[e].charCodeAt(0)]=e;return n})();function Xt(n,e,t){if(n!==null)for(e.queue=e.queue<<8|n,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(Je[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(Je[s]),e.queuedBits-=6}}function ys(n,e,t){const s=ri[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 Zt(n){const e=[],t=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},r={queue:0,queuedBits:0},i=a=>{ai(a,s,t)};for(let a=0;a<n.length;a+=1)ys(n.charCodeAt(a),r,i);return e.join("")}function ii(n,e){if(n<=127){e(n);return}else if(n<=2047){e(192|n>>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 ni(n,e){for(let t=0;t<n.length;t+=1){let s=n.charCodeAt(t);if(s>55295&&s<=56319){const r=(s-55296)*1024&65535;s=(n.charCodeAt(t+1)-56320&65535|r)+65536,t+=1}ii(s,e)}}function ai(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 oi(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};for(let r=0;r<n.length;r+=1)ys(n.charCodeAt(r),t,s);return new Uint8Array(e)}function li(n){const e=[];return ni(n,t=>e.push(t)),new Uint8Array(e)}function ci(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};return n.forEach(r=>Xt(r,t,s)),Xt(null,t,s),e.join("")}function ui(n){return Math.round(Date.now()/1e3)+n}function hi(){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 H=()=>typeof window<"u"&&typeof document<"u",se={tested:!1,writable:!1},ms=()=>{if(!H())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(se.tested)return se.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),se.tested=!0,se.writable=!0}catch{se.tested=!0,se.writable=!1}return se.writable};function di(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 bs=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>Ee(async()=>{const{default:s}=await Promise.resolve().then(()=>je);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},fi=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))},re=async(n,e)=>{const t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Q=async(n,e)=>{await n.removeItem(e)};class ze{constructor(){this.promise=new ze.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}ze.promiseConstructor=Promise;function nt(n){const e=n.split(".");if(e.length!==3)throw new yt("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Qr.test(e[s]))throw new yt("JWT not in base64url format");return{header:JSON.parse(Zt(e[0])),payload:JSON.parse(Zt(e[1])),signature:oi(e[2]),raw:{header:e[0],payload:e[1]}}}async function gi(n){return await new Promise(e=>{setTimeout(()=>e(null),n)})}function pi(n,e){return new Promise((s,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{const a=await n(i);if(!e(i,null,a)){s(a);return}}catch(a){if(!e(i,a)){r(a);return}}})()})}function wi(n){return("0"+n.toString(16)).substr(-2)}function vi(){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,wi).join("")}async function _i(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 yi(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code
25challenge method will default to use plain instead of sha256."),n;const t=await _i(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _e(n,e,t=!1){const s=vi();let r=s;t&&(r+="/PASSWORD_RECOVERY"),await Se(n,`${e}-code-verifier`,r);const i=await yi(s);return[i,s===i?"plain":"s256"]}const mi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function bi(n){const e=n.headers.get(vt);if(!e||!e.match(mi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ki(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 Si(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 Ti=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ye(n){if(!Ti.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function at(){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 es(n){return JSON.parse(JSON.stringify(n))}var Ei=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);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};const ie=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),ji=[502,503,504];async function ts(n){var e;if(!fi(n))throw new _t(ie(n),0);if(ji.includes(n.status))throw new _t(ie(n),n.status);let t;try{t=await n.json()}catch(i){throw new _s(ie(i),i)}let s;const r=bi(n);if(r&&r.getTime()>=vs["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 Yt(ie(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new X}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,a)=>i&&typeof a=="string",!0))throw new Yt(ie(t),n.status,t.weak_password.reasons);throw new Zr(ie(t),n.status||500,s)}const xi=(n,e,t,s)=>{const r={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function b(n,e,t,s){var r;const i=Object.assign({},s==null?void 0:s.headers);i[vt]||(i[vt]=vs["2024-01-01"].name),s!=null&&s.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const a=(r=s==null?void 0:s.query)!==null&&r!==void 0?r:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await Pi(n,e,t+o,{headers:i,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function Pi(n,e,t,s,r,i){const a=xi(e,s,r,i);let o;try{o=await n(t,Object.assign({},a))}catch(l){throw console.error(l),new _t(ie(l),0)}if(o.ok||await ts(o),s!=null&&s.noResolveJson)return o;try{return await o.json()}catch(l){await ts(l)}}function G(n){var e;let t=null;Ri(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=ui(n.expires_in)));const s=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:s},error:null}}function ss(n){const e=G(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 Z(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function Oi(n){return{data:n,error:null}}function Ai(n){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:i}=n,a=Ei(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:i},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function Ci(n){return n}function Ri(n){return n.access_token&&n.refresh_token&&n.expires_in}const ot=["global","local","others"];var $i=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);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};class Ii{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=bs(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t=ot[0]){if(ot.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ot.join(", ")}`);try{return await b(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(y(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await b(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Z})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=$i(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s==null?void 0:s.newEmail,delete r.newEmail),await b(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:Ai,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(y(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await b(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Z})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,i,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},u=await b(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(r=e==null?void 0:e.perPage)===null||r===void 0?void 0:r.toString())!==null&&i!==void 0?i:""},xform:Ci});if(u.error)throw u.error;const h=await u.json(),d=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(l=(o=u.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(p=>{const w=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(p.split(";")[1].split("=")[1]);c[`${_}Page`]=w}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(y(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){ye(e);try{return await b(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Z})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){ye(e);try{return await b(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Z})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){ye(e);
25try{return await b(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Z})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){ye(e.userId);try{const{data:t,error:s}=await b(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(y(t))return{data:null,error:t};throw t}}async _deleteFactor(e){ye(e.userId),ye(e.id);try{return{data:await b(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}}function rs(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}function Ui(){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 me={debug:!!(globalThis&&ms()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ks extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Li extends ks{}async function Ni(n,e,t){me.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",n,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),me.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){me.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",n,r.name);try{return await t()}finally{me.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",n,r.name)}}else{if(e===0)throw me.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",n),new Li(`Acquiring an exclusive Navigator LockManager lock "${n}" immediately failed`);if(me.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()}}))}Ui();const Di={url:Gr,storageKey:Vr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Yr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function is(n,e,t){return await t()}const be={};class $e{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=$e.nextInstanceID,$e.nextInstanceID+=1,this.instanceID>0&&H()&&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({},Di),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 Ii({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=bs(r.fetch),this.lock=r.lock||is,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:H()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Ni:this.lock=is,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:ms()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=rs(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=rs(this.memoryStorage)),H()&&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=be[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){be[this.storageKey]=Object.assign(Object.assign({},be[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=be[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){be[this.storageKey]=Object.assign(Object.assign({},be[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ws}) ${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=di(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),H()&&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),si(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:a,redirectType:o}=r;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return y(t)?{error:t}:{error:new _s("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const i=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}},xform:G}),{data:a,error:o}=i;if(o||!a)return{data:{user:null,session:null},error:o};const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(y(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,p=null;this.flowType==="pkce"&&([f,p]=await _e(this.storage,this.storageKey)),i=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:u,password:h,data:(t=d==null?void 0:d.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:f,code_challenge_method:p},xform:G})}else if("phone"in e){const{phone:u,password:h,options:d}=e;i=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(s=d==null?void 0:d.data)!==null&&s!==void 0?s:{},channel:(r=d==null?void 0:d.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:G})}else throw new Fe("You must provide either an email or phone number and a password");const{data:a,error:o}=i;if(o||!a)return{data:{user:null,session:null},error:o};const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(y(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:a,options:o}=e;t=await b(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:ss})}else if("phone"in e){const{phone:i,password:a,options:o}=e;t=await b(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:ss})}else throw new Fe("You must provide either an email or phone number and a password");const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Me}:(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(y(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,a,o,l,c,u,h,d,f;let p,w;if("message"in e)p=e.message,w=e.signature;else{const{chain:_,wallet:S,statement:E,options:v}=e;let k;if(H())if(typeof S=="object")k=S;else{const m=window;if("solana"in m&&typeof m.solana=="object"&&("signIn"in m.solana&&typeof m.solana.signIn=="function"||"signMessage"in m.solana&&typeof m.solana.signMessage=="function"))k=m.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof S!="object"||!(v!=null&&v.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=S}const R=new URL((t=v==null?void 0:v.url)!==null&&t!==void 0?t:window.location.href);
25if("signIn"in k&&k.signIn){const m=await k.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v==null?void 0:v.signInWithSolana),{version:"1",domain:R.host,uri:R.href}),E?{statement:E}:null));let U;if(Array.isArray(m)&&m[0]&&typeof m[0]=="object")U=m[0];else if(m&&typeof m=="object"&&"signedMessage"in m&&"signature"in m)U=m;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in U&&"signature"in U&&(typeof U.signedMessage=="string"||U.signedMessage instanceof Uint8Array)&&U.signature instanceof Uint8Array)p=typeof U.signedMessage=="string"?U.signedMessage:new TextDecoder().decode(U.signedMessage),w=U.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in k)||typeof k.signMessage!="function"||!("publicKey"in k)||typeof k!="object"||!k.publicKey||!("toBase58"in k.publicKey)||typeof k.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${R.host} wants you to sign in with your Solana account:`,k.publicKey.toBase58(),...E?["",E,""]:[""],"Version: 1",`URI: ${R.href}`,`Issued At: ${(r=(s=v==null?void 0:v.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&r!==void 0?r:new Date().toISOString()}`,...!((i=v==null?void 0:v.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}`]:[],...!((a=v==null?void 0:v.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((o=v==null?void 0:v.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((l=v==null?void 0:v.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((c=v==null?void 0:v.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((h=(u=v==null?void 0:v.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...v.signInWithSolana.resources.map(U=>`- ${U}`)]:[]].join(` 26`);const m=await k.signMessage(new TextEncoder().encode(p),"utf8");if(!m||!(m instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");w=m}}try{const{data:_,error:S}=await b(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:ci(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:G});if(S)throw S;return!_||!_.session||!_.user?{data:{user:null,session:null},error:new Me}:(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),{data:Object.assign({},_),error:S})}catch(_){if(y(_))return{data:{user:null,session:null},error:_};throw _}}async _exchangeCodeForSession(e){const t=await re(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/");try{const{data:i,error:a}=await b(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:G});if(await Q(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Me}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:r??null}),error:a})}catch(i){if(y(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:a}=e,o=await b(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:G}),{data:l,error:c}=o;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Me}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,i,a;try{if("email"in e){const{email:o,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await _e(this.storage,this.storageKey));const{error:h}=await b(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(t=l==null?void 0:l.data)!==null&&t!==void 0?t:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){const{phone:o,options:l}=e,{data:c,error:u}=await b(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(a=l==null?void 0:l.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u}}throw new Fe("You must provide either an email or phone number.")}catch(o){if(y(o))return{data:{user:null,session:null},error:o};throw o}}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:a,error:o}=await b(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:G});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(r){if(y(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let i=null,a=null;return this.flowType==="pkce"&&([i,a]=await _e(this.storage,this.storageKey)),await b(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e==null?void 0:e.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:a}),headers:this.headers,xform:Oi})}catch(i){if(y(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 X;const{error:r}=await b(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(y(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:a}=await b(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if("phone"in e){const{phone:s,type:r,options:i}=e,{data:a,error:o}=await b(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o}}throw new Fe("You must provide either an email or phone number and a type")}catch(t){if(y(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 re(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not val
26id"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<rt:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await re(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=at()}if(this.storage.isServer&&e.user){let a=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,u)=>(!a&&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."),a=!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 b(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Z}):await this._useSession(async t=>{var s,r,i;const{data:a,error:o}=t;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new X}:await b(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(r=a.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0,xform:Z})})}catch(t){if(y(t))return ti(t)&&(await this._removeSession(),await Q(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 X;const a=r.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await _e(this.storage,this.storageKey));const{data:c,error:u}=await b(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:Z});if(u)throw u;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(s){if(y(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 X;const t=Date.now()/1e3;let s=t,r=!0,i=null;const{payload:a}=nt(e.access_token);if(a.exp&&(s=a.exp,r=s<=t),r){const{session:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)throw l;i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.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(y(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:a,error:o}=t;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new X;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(y(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!H())throw new He("No browser detected.");
26if(e.error||e.error_description||e.error_code)throw new He(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 Vt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new He("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 Vt("No code detected.");const{data:E,error:v}=await this._exchangeCodeForSession(e.code);if(v)throw v;const k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:E.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:i,refresh_token:a,expires_in:o,expires_at:l,token_type:c}=e;if(!i||!o||!a||!c)throw new He("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let d=u+h;l&&(d=parseInt(l));const f=d-u;f*1e3<=ke&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const p=d-h;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,d,u);const{data:w,error:_}=await this._getUser(i);if(_)throw _;const S={provider_token:s,provider_refresh_token:r,access_token:i,expires_in:h,expires_at:d,refresh_token:a,token_type:c,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:S,redirectType:e.type},error:null}}catch(s){if(y(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 re(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 a=(s=r.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(ei(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return e!=="others"&&(await this._removeSession(),await Q(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=hi(),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:a}=t;if(a)throw a;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 _e(this.storage,this.storageKey,!0));try{return await b(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(y(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(y(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 a,o,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:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await b(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 H()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),{data:{provider:e.provider,url:s==null?void 0:s.url},error:null}}catch(s){if(y(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:a}=t;if(a)throw a;
26return await b(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(y(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 pi(async r=>(r>0&&await gi(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await b(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:G})),(r,i)=>{const a=200*Math.pow(2,r);return i&&it(i)&&Date.now()+a-s<ke})}catch(s){if(this._debug(t,"error",s),y(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),H()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,t;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const r=await re(this.storage,this.storageKey);if(r&&this.userStorage){let a=await re(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:r.user},await Se(this.userStorage,this.storageKey+"-user",a)),r.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:at()}else if(r&&!r.user&&!r.user){const a=await re(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(r.user=a.user,await Q(this.storage,this.storageKey+"-user"),await Se(this.storage,this.storageKey,r)):r.user=at()}if(this._debug(s,"session from storage",r),!this._isValidSession(r)){this._debug(s,"session is not valid"),r!==null&&await this._removeSession();return}const i=((t=r.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<rt;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${rt}s`),i){if(this.autoRefreshToken&&r.refresh_token){const{error:a}=await this._callRefreshToken(r.refresh_token);a&&(console.error(a),it(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(r.user&&r.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(r.access_token);!o&&(a!=null&&a.user)?(r.user=a.user,await this._saveSession(r),await this._notifyAllSubscribers("SIGNED_IN",r)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(s,"error",r),console.error(r);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new X;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new ze;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new X;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const o={session:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(r,"error",i),y(i)){const a={session:null,error:i};return it(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,t)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),s=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&t.user&&await Se(this.userStorage,this.storageKey+"-user",{user:t.user});const r=Object.assign({},t);delete r.user;const i=es(r);await Se(this.storage,this.storageKey,i)}else{const r=es(t);await Se(this.storage,this.storageKey,r)}}async _removeSession(){this._debug("#_removeSession()"),await Q(this.storage,this.storageKey),await Q(this.storage,this.storageKey+"-code-verifier"),await Q(this.storage,this.storageKey+"-user"),this.userStorage&&await Q(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&H()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
26catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),ke);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)/ke);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${ke}ms, refresh threshold is ${wt} ticks`),r<=wt&&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 ks)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!H()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){const r=[`provider=${encodeURIComponent(t)}`];if(s!=null&&s.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,a]=await _e(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});r.push(o.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);r.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await b(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r==null?void 0:r.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(y(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:a}=t;if(a)return{data:null,error:a};const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:l,error:c}=await b(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&(!((r=l==null?void 0:l.totp)===null||r===void 0)&&r.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(y(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:a,error:o}=await b(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r==null?void 0:r.session)===null||s===void 0?void 0:s.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:o})})}catch(t){if(y(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 b(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(s=r==null?void 0:r.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(y(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const s=(e==null?void 0:e.factors)||[],r=s.filter(a=>a.factor_type==="totp"&&a.status==="verified"),i=s.filter(a=>a.factor_type==="phone"&&a.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:a}=nt(r.access_token);let o=null;a.aal&&(o=a.aal);let l=o;((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=a.amr||[];return{data:{currentLevel:o,nextLevel:l,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(o=>o.kid===e);if(s)return s;const r=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+Xr>r)return s;const{data:i,error:a}=await b(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=r,s=i.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,t={}){try{let s=e;if(!s){const{data:f,error:p}
26=await this.getSession();if(p||!f.session)return{data:null,error:p};s=f.session.access_token}const{header:r,payload:i,signature:a,raw:{header:o,payload:l}}=nt(s);t!=null&&t.allowExpired||ki(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!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:r,signature:a},error:null}}const u=Si(r.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,a,li(`${o}.${l}`)))throw new yt("Invalid JWT signature");return{data:{claims:i,header:r,signature:a},error:null}}catch(s){if(y(s))return{data:null,error:s};throw s}}}$e.nextInstanceID=0;const Bi=$e;class qi extends Bi{constructor(e){super(e)}}var Mi=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function o(u){try{c(s.next(u))}catch(h){a(h)}}function l(u){try{c(s.throw(u))}catch(h){a(h)}}function c(u){u.done?i(u.value):r(u.value).then(o,l)}c((s=s.apply(n,e||[])).next())})};class Fi{constructor(e,t,s){var r,i,a;this.supabaseUrl=e,this.supabaseKey=t;const o=zr(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",o),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",o),this.storageUrl=new URL("storage/v1",o),this.functionsUrl=new URL("functions/v1",o);const l=`sb-${o.hostname.split(".")[0]}-auth-token`,c={db:Nr,realtime:Br,auth:Object.assign(Object.assign({},Dr),{storageKey:l}),global:Lr},u=Jr(s??{},c);this.storageKey=(r=u.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(h,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=u.auth)!==null&&a!==void 0?a:{},this.headers,u.global.fetch),this.fetch=Hr(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},u.realtime)),this.rest=new rr(new URL("rest/v1",o).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this.storage=new $r(this.storageUrl.href,this.headers,this.fetch,s==null?void 0:s.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new zs(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 Mi(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,userStorage:i,storageKey:a,flowType:o,lock:l,debug:c},u,h){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new qi({url:this.authUrl.href,headers:Object.assign(Object.assign({},d),u),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,userStorage:i,flowType:o,lock:l,debug:c,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new mr(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s==null?void 0:s.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?this.changedAccessToken=s:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Hi=(n,e,t)=>new Fi(n,e,t);function Wi(){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}Wi()&&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 N
26ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let lt=null;function We(){return lt||(lt=Hi("https://twqihbqtnrsxrfiybxlb.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR3cWloYnF0bnJzeHJmaXlieGxiIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgxODgwOTEsImV4cCI6MjA3Mzc2NDA5MX0.KQJeps2tbwaaLLiqnotAp05lS1leSEicv-Me-n7wepg")),lt}function Qi(){const[,n]=Rs(),{toast:e}=$s(),[t,s]=L.useState(""),[r,i]=L.useState(!1),[a,o]=L.useState(!1),[l,c]=L.useState(!0),[u,h]=L.useState(""),[d,f]=L.useState(!1),[p,w]=L.useState(!1),[_,S]=L.useState(null),[E,v]=L.useState(null),[k,R]=L.useState("invite"),[m]=L.useState(()=>new URLSearchParams(window.location.search).get("confirm")==="1"),[U,J]=L.useState(!1),[Et,Ss]=L.useState(null),[Ge,Ts]=L.useState(null);L.useEffect(()=>{Is()},[]);const Ve=Us({mutationFn:async O=>(await Ct("POST","/api/resend-invitation",{email:O})).json(),onSuccess:()=>{e({title:"Invitation Sent!",description:"A new invitation email has been sent. Please check your inbox."}),f(!1),h("")},onError:O=>{j("[SetupPassword:59]","Failed to resend invitation",O),e({title:"Failed to send invitation",description:O.message||"Please contact support for assistance.",variant:"destructive"})}}),Es=O=>{if(O.preventDefault(),!u.trim()){j("[SetupPassword:71]","Missing email for resend"),e({title:"Email required",description:"Please enter your email address.",variant:"destructive"});return}Ve.mutate(u)};L.useEffect(()=>{if(p)return;(async()=>{var $,q;if(m){try{const P=await fetch("/api/auth/password-setup-status",{credentials:"include",cache:"no-store"}),T=await P.json().catch(()=>({}));!P.ok||(T==null?void 0:T.required)!==!0?J(!0):typeof T.email=="string"&&Ss(T.email)}catch{J(!0)}w(!0),c(!1);return}try{const P=F=>F.replace(/token_hash=[^&]+/gi,"token_hash=REDACTED").replace(/access_token=[^&]+/gi,"access_token=REDACTED").replace(/refresh_token=[^&]+/gi,"refresh_token=REDACTED").replace(/provider_token=[^&]+/gi,"provider_token=REDACTED"),T=Xe(),B=Ms(),oe=window.location.pathname,le=T.includes("access_token"),xe=!!B.tokenHash;j("[SetupPassword:96]","Page loaded",{pathname:oe,hashLength:T.length,hasQueryToken:!!B.tokenHash,hasHashTokens:T.includes("access_token"),timestamp:new Date().toISOString()});const Pt=We(),{data:M}=await Pt.auth.getSession();if(M!=null&&M.session&&!le&&!xe){j("[SetupPassword:110]","Existing session found, ready for password setup",{userId:M.session.user.id,userEmail:M.session.user.email}),Ts(M.session.user.email||null),window.history.replaceState({},"",window.location.pathname),j("[SetupPassword:118]","Hash cleared for existing session",{newUrl:window.location.href}),w(!0),c(!1);return}const Ue=B.tokenHash,te=B.type;if(Ue&&!le){j("[SetupPassword:tokenHash]","token_hash flow detected, deferring verification to submit",{type:te}),v(Ue),R(te||"invite"),w(!0),c(!1);return}const z=new URLSearchParams(T.substring(1)),ce=z.get("access_token"),ue=z.get("refresh_token"),Pe=z.get("type"),Qe=z.get("error_code"),Ot=z.get("error_description"),At={};if(z.forEach((F,N)=>{At[N]=N.includes("token")?"REDACTED":F}),j("[SetupPassword:141]","Hash parameters parsed",{type:Pe,hasAccessToken:!!ce,hasRefreshToken:!!ue,accessTokenLength:(ce==null?void 0:ce.length)||0,refreshTokenLength:(ue==null?void 0:ue.length)||0,errorCode:Qe,errorDescription:Ot,allHashParams:At,rawHash:P(T)}),Qe){j("[SetupPassword:155]","Error code found in URL",{errorCode:Qe,errorDescription:Ot,fullContext:{type:Pe,hash:P(T)}}),e({title:"Link Expired",description:"Your invitation link has expired. Please contact support or request a new invitation.",variant:"destructive"}),c(!1);return}if(ce&&ue){j("[SetupPassword:170]","Tokens found, attempting to set session",{type:Pe});const F=We(),{data:N,error:Y}=await F.auth.setSession({access_token:ce,refresh_token:ue});if(Y){try{await F.auth.signOut({scope:"local"})}catch{}j("[SetupPassword:183]","Failed to set session",{error:Y,errorMessage:Y.message,errorName:Y.name,errorStatus:Y.status,type:Pe}),e({title:"Authentication failed",description:"The link may have expired. Please contact support for assistance.",variant:"destructive"}),c(!1);return}j("[SetupPassword:199]","Session set successfully, ready for password setup",{userId:($=N==null?void 0:N.user)==null?void 0:$.id,userEmail:(q=N==null?void 0:N.user)==null?void 0:q.email,sessionExists:!!(N!=null&&N.session)}),w(!0),window.history.replaceState({},"",window.location.pathname),Fs(),j("[SetupPassword:211]","Hash cleared, user can now set password",{newUrl:window.location.href}),c(!1);return}else j("[SetupPassword:219]","No tokens found initially, waiting for redirect",{type:Pe,hash:P(T),willWait:!0}),setTimeout(()=>{const F=Xe(),N=new URLSearchParams(F.substring(1)),Y=N.get("access_token"),Os=N.get("type");
26j("[SetupPassword:233]","Retry check after 2s wait",{hasTokenNow:!!Y,type:Os,hashChanged:F!==T,currentHash:P(F),previousHash:P(T)}),Y||(j("[SetupPassword:242]","Still no tokens after waiting - showing error",{finalHash:P(F),finalUrl:P(window.location.href)}),e({title:"Invalid link",description:"Please click the link from your email again. If the problem persists, contact support.",variant:"destructive"}),c(!1))},2e3)}catch(P){j("[SetupPassword:256]","Exception in auth callback",{error:P,errorMessage:P instanceof Error?P.message:String(P),errorStack:P instanceof Error?P.stack:void 0,url:window.location.href}),e({title:"Something went wrong",description:"Please try clicking the email link again.",variant:"destructive"}),c(!1)}})()},[p]),L.useEffect(()=>{!l&&!m&&(async()=>{const $=We(),{data:q}=await $.auth.getSession();S(!!(q!=null&&q.session))})()},[l,m]);const jt=async()=>{const O=await fetch("/api/auth/user",{credentials:"include",cache:"no-store"});let $="/onboarding",q="Your account is ready. Redirecting to onboarding...";if(O.ok){const P=await O.json(),{queryClient:T}=await Ee(async()=>{const{queryClient:B}=await import("./index-CzN0SCRv.js").then(oe=>oe.cJ);return{queryClient:B}},__vite__mapDeps([0,1]));T.setQueryData(["/api/auth/user"],P),await T.invalidateQueries({queryKey:["/api/auth/user"]}),P.onboardingCompleted&&($="/dashboard",q="Your password has been updated. Redirecting to dashboard..."),await new Promise(B=>setTimeout(B,200))}e({title:"Password set!",description:q}),n($)},js=async()=>{if(t.length<8||t.length>72){e({title:"Choose a different password",description:"Your password must be 8 to 72 characters long.",variant:"destructive"});return}o(!0);try{const O=await fetch("/api/auth/complete-password-setup",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({password:t})}),$=await O.json().catch(()=>({}));if(!O.ok){e({title:"Failed to set password",description:($==null?void 0:$.message)||($==null?void 0:$.error)||"Please try again.",variant:"destructive"}),o(!1);return}await jt()}catch(O){j("[SetupPassword:serverSetup]","Error setting password",O),e({title:"Something went wrong",description:"Please try again later.",variant:"destructive"}),o(!1)}},xs=async O=>{var $,q,P;if(O.preventDefault(),!t){j("[SetupPassword:290]","Missing password"),e({title:"Missing information",description:"Please enter a password.",variant:"destructive"});return}if(m){await js();return}if(t.length<6){j("[SetupPassword:300]","Password too short"),e({title:"Password too short",description:"Password must be at least 6 characters long.",variant:"destructive"});return}o(!0);try{const T=We();let{data:B}=await T.auth.getSession();if(E){const Ue=["invite","recovery","signup","magiclink","email","email_change"].includes(k)?k:"invite",{data:te,error:z}=await T.auth.verifyOtp({token_hash:E,type:Ue});if(z){j("[SetupPassword:verifyOtp]","Failed to verify token_hash",z),e({title:"Link expired",description:"This link has expired or was already used. Please request a new one.",variant:"destructive"}),o(!1);return}window.history.replaceState({},"",window.location.pathname),Hs(),v(null),S(!0),te!=null&&te.session?B=te:{data:B}=await T.auth.getSession()}const oe=(q=($=B==null?void 0:B.session)==null?void 0:$.user)==null?void 0:q.email;if(!oe){j("[SetupPassword:319]","No user email found in session"),e({title:"Session error",description:"Please try clicking the invitation link again.",variant:"destructive"}),o(!1);return}const{error:le}=await T.auth.updateUser({password:t});if(le){j("[SetupPassword:335]","Failed to update password",le),e({title:"Failed to set password",description:le.message||"Please try again.",variant:"destructive"}),o(!1);return}try{const{error:M}=await T.auth.signOut({scope:"others"});M&&j("[SetupPassword:signOutOthers]","Failed to sign out other sessions after password update",M)}catch(M){j("[SetupPassword:signOutOthers]","Exception signing out other sessions after password update",M)}const{data:xe}=await T.auth.getSession();if(!(await Ct("POST","/api/auth/signin",{email:oe,password:t,supabaseAccessToken:(P=xe==null?void 0:xe.session)==null?void 0:P.access_token})).ok){j("[SetupPassword:352]","Failed to create backend session after password setup"),e({title:"Session error",description:"Password set but failed to sign in. Please try signing in manually.",variant:"destructive"}),o(!1);return}try{await T.auth.signOut({scope:"local"})}catch{}await jt()}catch(T){j("[SetupPassword:392]","Error setting password",T),e({title:"Something went wrong",description:"Please try again later.",variant:"destructive"}),o(!1)}};if(l)return g.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:g.jsx(Le,{className:"w-full max-w-md bg-white shadow-xl",children:g.jsx(Ne,{className:"pt-6",children:g.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[g.jsx(Ls,{size:"md",text:"Verifying your invitation link..."}),g.jsx("p",{className:"text-sm text-gray-500",children:"This should only take a moment"})]})})})});const Ye=new URLSearchParams(Xe().substring(1)),Ps=Ye.get("access_token")&&Ye.get("refresh_token"),xt=Ye.get("error_code");return m&&U&&!l?g.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:g.jsxs(Le,{className:"w-full max-w-md bg-white shadow-xl","data-testid":"card-password-setup-expired",children:[g.jsx(Ze,{className:"text-center",children:g.jsx(De,{className:"text-2xl text-gray-900",children:"Choose a new password"})}),g.jsxs(Ne,{className:"text-center space-y-4",children:[g.jsx("p",{className:"text-gray-700",children:'Your email is confirmed. To finish, use "Forgot password" on the sign-in page and we will email you a link to choose your password.'}),g.jsx(he,{onClick:()=>n("/auth"),className:"w-full bg-blue-600 hover:bg-blue-700","data-testid":"button-go-to-signin",children:"Go to sign in"})]})]})}):!m&&!l&&!Ps&&!E&&!a&&_===!1?g.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:g.jsxs(Le,{className:"w-full max-w-md bg-white shadow-xl",children:[g.jsxs(Ze,{className:"text-center",children:[g.jsxs("div",{className:"text-2xl font-bold flex items-center justify-center gap-2 mb-2",children:[g.jsx("img",{src:Rt,alt:"SMB Sales Boost logo",className:"w-8 h-8 flex-shrink-0",loading:"eager"}),g.jsx("span",{className:"text-gray-900",children:"SMB Sales Boost"})]}),g.jsx(De,{className:"text-2xl text-red-600",children:xt?"Link Expired":"Invalid Link"})]}),g.jsxs(Ne,{className:"text-center space-y-4",children:[g.jsx("p",{className:"text-gray-700",children:xt?"Your inv
26itation link has expired. Invitation links are only valid for a limited time.":"The link you clicked doesn't seem to be valid. If you refreshed this page, open the link from your email again."}),d?g.jsxs("form",{onSubmit:Es,className:"space-y-4",children:[g.jsxs("div",{className:"space-y-2",children:[g.jsx(It,{htmlFor:"resend-email",children:"Enter your email address"}),g.jsxs("div",{className:"relative",children:[g.jsx($t,{className:"absolute left-3 top-3 h-4 w-4 text-gray-400"}),g.jsx(Ut,{id:"resend-email",type:"email",placeholder:"[email protected]",value:u,onChange:O=>h(O.target.value),className:"pl-10","data-testid":"input-resend-email",required:!0})]})]}),g.jsxs("div",{className:"space-y-2",children:[g.jsx(he,{type:"submit",className:"w-full bg-blue-600 hover:bg-blue-700",disabled:Ve.isPending,"data-testid":"button-send-invitation",children:Ve.isPending?g.jsxs(g.Fragment,{children:[g.jsx(Ns,{size:16})," Sending..."]}):"Send New Invitation"}),g.jsx(he,{type:"button",onClick:()=>{f(!1),h("")},variant:"outline",className:"w-full","data-testid":"button-cancel-resend",children:"Cancel"})]})]}):g.jsxs(g.Fragment,{children:[g.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:g.jsx("p",{className:"text-sm text-blue-800",children:"You can request a new invitation email below."})}),g.jsxs("div",{className:"space-y-2",children:[g.jsxs(he,{onClick:()=>f(!0),className:"w-full bg-blue-600 hover:bg-blue-700","data-testid":"button-request-new-invitation",children:[g.jsx($t,{className:"w-4 h-4 mr-2"}),"Request New Invitation"]}),g.jsx(he,{onClick:()=>n("/"),variant:"outline",className:"w-full","data-testid":"button-back-home",children:"Back to Home"})]})]})]})]})}):g.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-4",children:g.jsxs(Le,{className:"w-full max-w-md bg-white shadow-xl",children:[g.jsxs(Ze,{className:"text-center",children:[g.jsxs("div",{className:"text-2xl font-bold flex items-center justify-center gap-2 mb-2",children:[g.jsx("img",{src:Rt,alt:"SMB Sales Boost logo",className:"w-8 h-8 flex-shrink-0",loading:"eager"}),g.jsx("span",{className:"text-gray-900",children:"SMB Sales Boost"})]}),m?g.jsxs(g.Fragment,{children:[g.jsx(De,{className:"text-2xl text-gray-900",children:"Choose your password"}),Et&&g.jsxs("p",{className:"font-semibold text-gray-900 break-all","data-testid":"text-setup-account-email",children:["Account: ",Et]}),g.jsx("p",{className:"text-gray-700",children:"Your email address is confirmed. Choose the password you will use to sign in."})]}):g.jsxs(g.Fragment,{children:[g.jsx(De,{className:"text-2xl text-gray-900",children:"Set Your Password"}),Ge&&g.jsxs("p",{className:"font-semibold text-gray-900 break-all","data-testid":"text-session-account-email",children:["Account: ",Ge]}),g.jsx("p",{className:"text-gray-700",children:"Create a password to secure your account"}),Ge&&g.jsx("p",{className:"text-sm text-gray-500","data-testid":"text-session-not-your-account",children:"Not your account? Open the link from your email again."})]})]}),g.jsx(Ne,{children:g.jsxs("form",{onSubmit:xs,className:"space-y-4",children:[g.jsxs("div",{className:"space-y-2",children:[g.jsx(It,{htmlFor:"password",children:"Password"}),g.jsxs("div",{className:"relative",children:[g.jsx(Ds,{className:"absolute left-3 top-3 h-4 w-4 text-gray-400"}),g.jsx(Ut,{id:"password",type:r?"text":"password",placeholder:"Enter your password",value:t,onChange:O=>s(O.target.value),className:"pl-10 pr-10 border-2 border-gray-400","data-testid":"input-password"}),g.jsx("button",{type:"button",onClick:()=>i(!r),className:"absolute right-3 top-3 h-4 w-4 text-gray-400 hover:text-gray-600",children:r?g.jsx(Bs,{className:"h-4 w-4"}):g.jsx(qs,{className:"h-4 w-4"})})]}),g.jsx("p",{className:"text-sm text-gray-500",children:m?"8 to 72 characters. If you already chose a password when you signed up on another device or browser, you can enter it again here.":"At least 6 characters. You can reset it later if needed."})]}),g.jsx(he,{type:"submit",className:"w-full bg-blue-600 hover:bg-blue-700 border-2 border-gray-400",disabled:a,"data-testid":"button-setup-password",children:a?"Setting password...":"Set Password"}),m&&g.jsx("p",{className:"text-xs text-gray-500","data-testid":"text-setup-not-your-email",children:"Not your email address? Close this page and do not continue. If it is yours but you did not create this account, someone else may have entered it. Choosing a password here makes sure only you can sign in."})]})})]})})}export{Qi as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.