PageSourceSearch

https://snappilot.ai/assets/js/supabase-vendor-eEOYocAC.js

js snappilot.ai collected 2026-10-05 12:39:07 UTC 157,650 bytes, 40 lines download raw bytes

1import{_ as y,t as gr,a as je}from"./ui-vendor-DeaCpvuz.js";import{g as $t}from"./react-vendor-BwON9l4R.js";function pr(i,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in i)){const n=Object.getOwnPropertyDescriptor(r,s);n&&Object.defineProperty(i,s,n.get?n:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}))}const wr="modulepreload",vr=function(i){return"/"+i},nt={},ne=function(e,t,r){let s=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");s=Promise.allSettled(t.map(l=>{if(l=vr(l),l in nt)return;nt[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":wr,c||(d.as="script"),d.crossOrigin="",d.href=l,a&&d.setAttribute("nonce",a),document.head.appendChild(d),c)return new Promise((h,f)=>{d.addEventListener("load",h),d.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${l}`)))})}))}function n(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&n(a.reason);return e().catch(n)})},_r=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>ne(async()=>{const{default:r}=await Promise.resolve().then(()=>G);return{default:r}},void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};class Ye extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class ot extends Ye{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class at extends Ye{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class lt extends Ye{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var qe;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(qe||(qe={}));class yr{constructor(e,{headers:t={},customFetch:r,region:s=qe.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=_r(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return y(this,arguments,void 0,function*(t,r={}){var s;try{const{headers:n,method:o,body:a,signal:l}=r;let c={},{region:u}=r;u||(u=this.region);const d=new URL(`${this.url}/${t}`);u&&u!=="any"&&(c["x-region"]=u,d.searchParams.set("forceFunctionRegion",u));let h;a&&(n&&!Object.prototype.hasOwnProperty.call(n,"Content-Type")||!n)?typeof Blob<"u"&&a instanceof Blob||a instanceof ArrayBuffer?(c["Content-Type"]="application/octet-stream",h=a):typeof a=="string"?(c["Content-Type"]="text/plain",h=a):typeof FormData<"u"&&a instanceof FormData?h=a:(c["Content-Type"]="application/json",h=JSON.stringify(a)):h=a;const f=yield this.fetch(d.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},c),this.headers),n),body:h,signal:l}).catch(_=>{throw _.name==="AbortError"?_:new ot(_)}),w=f.headers.get("x-relay-error");if(w&&w==="true")throw new at(f);if(!f.ok)throw new lt(f);let g=((s=f.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return g==="application/json"?p=yield f.json():g==="application/octet-stream"||g==="application/pdf"?p=yield f.blob():g==="text/event-stream"?p=f:g==="multipart/form-data"?p=yield f.formData():p=yield f.text(),{data:p,error:null,response:f}}catch(n){return n instanceof Error&&n.name==="AbortError"?{data:null,error:new ot(n)}:{data:null,error:n,response:n instanceof lt||n instanceof at?n.context:void 0}}})}}var I={};const oe=$t(gr);var we={},ve={},_e={},ye={},be={},br=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")},ie=br();const mr=ie.fetch,xt=ie.fetch.bind(ie),Ut=ie.Headers,Er=ie.Request,kr=ie.Response,G=Object.freeze(Object.defineProperty({__proto__:null,Headers:Ut,Request:Er,Response:kr,default:xt,fetch:mr},Symbol.toStringTag,{value:"Module"})),Sr=$t(G);var me={},ct;function Nt(){if(ct)return me;
1ct=1,Object.defineProperty(me,"__esModule",{value:!0});class i extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}return me.default=i,me}var ut;function Lt(){if(ut)return be;ut=1,Object.defineProperty(be,"__esModule",{value:!0});const i=oe,e=i.__importDefault(Sr),t=i.__importDefault(Nt());class r{constructor(n){var o,a;this.shouldThrowOnError=!1,this.method=n.method,this.url=n.url,this.headers=new Headers(n.headers),this.schema=n.schema,this.body=n.body,this.shouldThrowOnError=(o=n.shouldThrowOnError)!==null&&o!==void 0?o:!1,this.signal=n.signal,this.isMaybeSingle=(a=n.isMaybeSingle)!==null&&a!==void 0?a:!1,n.fetch?this.fetch=n.fetch:typeof fetch>"u"?this.fetch=e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(n,o){return this.headers=new Headers(this.headers),this.headers.set(n,o),this}then(n,o){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 a=this.fetch;let l=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async c=>{var u,d,h,f;let w=null,g=null,p=null,_=c.status,v=c.statusText;if(c.ok){if(this.method!=="HEAD"){const T=await c.text();T===""||(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"))?g=T:g=JSON.parse(T))}const S=(d=this.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),k=(h=c.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");S&&k&&k.length>1&&(p=parseInt(k[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(w={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,p=null,_=406,v="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{const S=await c.text();try{w=JSON.parse(S),Array.isArray(w)&&c.status===404&&(g=[],w=null,_=200,v="OK")}catch{c.status===404&&S===""?(_=204,v="No Content"):w={message:S}}if(w&&this.isMaybeSingle&&(!((f=w?.details)===null||f===void 0)&&f.includes("0 rows"))&&(w=null,_=200,v="OK"),w&&this.shouldThrowOnError)throw new t.default(w)}return{error:w,data:g,count:p,status:_,statusText:v}});return this.shouldThrowOnError||(l=l.catch(c=>{var u,d,h;return{error:{message:`${(u=c?.name)!==null&&u!==void 0?u:"FetchError"}: ${c?.message}`,details:`${(d=c?.stack)!==null&&d!==void 0?d:""}`,hint:"",code:`${(h=c?.code)!==null&&h!==void 0?h:""}`},data:null,count:null,status:0,statusText:""}})),l.then(n,o)}returns(){return this}overrideTypes(){return this}}return be.default=r,be}var ht;function Dt(){if(ht)return ye;ht=1,Object.defineProperty(ye,"__esModule",{value:!0});const e=oe.__importDefault(Lt());class t extends e.default{select(s){let n=!1;const o=(s??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:n=!0,nullsFirst:o,foreignTable:a,referencedTable:l=a}={}){const c=l?`${l}.order`:"order",u=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${u?`${u},`:""}${s}.${n?"asc":"desc"}${o===void 0?"":o?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:n,referencedTable:o=n}={}){const a=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(a,`${s}`),this}range(s,n,{foreignTable:o,referencedTable:a=o}={}){const l=typeof a>"u"?"offset":`${a}.offset`,c=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${s}`),this.url.searchParams.set(c,`${n-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
1explain({analyze:s=!1,verbose:n=!1,settings:o=!1,buffers:a=!1,wal:l=!1,format:c="text"}={}){var u;const d=[s?"analyze":null,n?"verbose":null,o?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),h=(u=this.headers.get("Accept"))!==null&&u!==void 0?u:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${c}; for="${h}"; options=${d};`),c==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}}return ye.default=t,ye}var dt;function Xe(){if(dt)return _e;dt=1,Object.defineProperty(_e,"__esModule",{value:!0});const e=oe.__importDefault(Dt()),t=new RegExp("[,()]");class r extends e.default{eq(n,o){return this.url.searchParams.append(n,`eq.${o}`),this}neq(n,o){return this.url.searchParams.append(n,`neq.${o}`),this}gt(n,o){return this.url.searchParams.append(n,`gt.${o}`),this}gte(n,o){return this.url.searchParams.append(n,`gte.${o}`),this}lt(n,o){return this.url.searchParams.append(n,`lt.${o}`),this}lte(n,o){return this.url.searchParams.append(n,`lte.${o}`),this}like(n,o){return this.url.searchParams.append(n,`like.${o}`),this}likeAllOf(n,o){return this.url.searchParams.append(n,`like(all).{${o.join(",")}}`),this}likeAnyOf(n,o){return this.url.searchParams.append(n,`like(any).{${o.join(",")}}`),this}ilike(n,o){return this.url.searchParams.append(n,`ilike.${o}`),this}ilikeAllOf(n,o){return this.url.searchParams.append(n,`ilike(all).{${o.join(",")}}`),this}ilikeAnyOf(n,o){return this.url.searchParams.append(n,`ilike(any).{${o.join(",")}}`),this}is(n,o){return this.url.searchParams.append(n,`is.${o}`),this}in(n,o){const a=Array.from(new Set(o)).map(l=>typeof l=="string"&&t.test(l)?`"${l}"`:`${l}`).join(",");return this.url.searchParams.append(n,`in.(${a})`),this}contains(n,o){return typeof o=="string"?this.url.searchParams.append(n,`cs.${o}`):Array.isArray(o)?this.url.searchParams.append(n,`cs.{${o.join(",")}}`):this.url.searchParams.append(n,`cs.${JSON.stringify(o)}`),this}containedBy(n,o){return typeof o=="string"?this.url.searchParams.append(n,`cd.${o}`):Array.isArray(o)?this.url.searchParams.append(n,`cd.{${o.join(",")}}`):this.url.searchParams.append(n,`cd.${JSON.stringify(o)}`),this}rangeGt(n,o){return this.url.searchParams.append(n,`sr.${o}`),this}rangeGte(n,o){return this.url.searchParams.append(n,`nxl.${o}`),this}rangeLt(n,o){return this.url.searchParams.append(n,`sl.${o}`),this}rangeLte(n,o){return this.url.searchParams.append(n,`nxr.${o}`),this}rangeAdjacent(n,o){return this.url.searchParams.append(n,`adj.${o}`),this}overlaps(n,o){return typeof o=="string"?this.url.searchParams.append(n,`ov.${o}`):this.url.searchParams.append(n,`ov.{${o.join(",")}}`),this}textSearch(n,o,{config:a,type:l}={}){let c="";l==="plain"?c="pl":l==="phrase"?c="ph":l==="websearch"&&(c="w");const u=a===void 0?"":`(${a})`;return this.url.searchParams.append(n,`${c}fts${u}.${o}`),this}match(n){return Object.entries(n).forEach(([o,a])=>{this.url.searchParams.append(o,`eq.${a}`)}),this}not(n,o,a){return this.url.searchParams.append(n,`not.${o}.${a}`),this}or(n,{foreignTable:o,referencedTable:a=o}={}){const l=a?`${a}.or`:"or";return this.url.searchParams.append(l,`(${n})`),this}filter(n,o,a){return this.url.searchParams.append(n,`${o}.${a}`),this}}return _e.default=r,_e}var ft;function Bt(){if(ft)return ve;
1ft=1,Object.defineProperty(ve,"__esModule",{value:!0});const e=oe.__importDefault(Xe());class t{constructor(s,{headers:n={},schema:o,fetch:a}){this.url=s,this.headers=new Headers(n),this.schema=o,this.fetch=a}select(s,n){const{head:o=!1,count:a}=n??{},l=o?"HEAD":"GET";let c=!1;const u=(s??"*").split("").map(d=>/\s/.test(d)&&!c?"":(d==='"'&&(c=!c),d)).join("");return this.url.searchParams.set("select",u),a&&this.headers.append("Prefer",`count=${a}`),new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(s,{count:n,defaultToNull:o=!0}={}){var a;const l="POST";if(n&&this.headers.append("Prefer",`count=${n}`),o||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const c=s.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){const u=[...new Set(c)].map(d=>`"${d}"`);this.url.searchParams.set("columns",u.join(","))}}return new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}upsert(s,{onConflict:n,ignoreDuplicates:o=!1,count:a,defaultToNull:l=!0}={}){var c;const u="POST";if(this.headers.append("Prefer",`resolution=${o?"ignore":"merge"}-duplicates`),n!==void 0&&this.url.searchParams.set("on_conflict",n),a&&this.headers.append("Prefer",`count=${a}`),l||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const d=s.reduce((h,f)=>h.concat(Object.keys(f)),[]);if(d.length>0){const h=[...new Set(d)].map(f=>`"${f}"`);this.url.searchParams.set("columns",h.join(","))}}return new e.default({method:u,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}update(s,{count:n}={}){var o;const a="PATCH";return n&&this.headers.append("Prefer",`count=${n}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}delete({count:s}={}){var n;const o="DELETE";return s&&this.headers.append("Prefer",`count=${s}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch})}}return ve.default=t,ve}var gt;function Or(){if(gt)return we;gt=1,Object.defineProperty(we,"__esModule",{value:!0});const i=oe,e=i.__importDefault(Bt()),t=i.__importDefault(Xe());class r{constructor(n,{headers:o={},schema:a,fetch:l}={}){this.url=n,this.headers=new Headers(o),this.schemaName=a,this.fetch=l}from(n){const o=new URL(`${this.url}/${n}`);return new e.default(o,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(n){return new r(this.url,{headers:this.headers,schema:n,fetch:this.fetch})}rpc(n,o={},{head:a=!1,get:l=!1,count:c}={}){var u;let d;const h=new URL(`${this.url}/rpc/${n}`);let f;a||l?(d=a?"HEAD":"GET",Object.entries(o).filter(([g,p])=>p!==void 0).map(([g,p])=>[g,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([g,p])=>{h.searchParams.append(g,p)})):(d="POST",f=o);const w=new Headers(this.headers);return c&&w.set("Prefer",`count=${c}`),new t.default({method:d,url:h,headers:w,schema:this.schemaName,body:f,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}}return we.default=r,we}Object.defineProperty(I,"__esModule",{value:!0});var qt=I.PostgrestError=Qt=I.PostgrestBuilder=Jt=I.PostgrestTransformBuilder=Ht=I.PostgrestFilterBuilder=Vt=I.PostgrestQueryBuilder=Ft=I.PostgrestClient=void 0;const ae=oe,Wt=ae.__importDefault(Or());var Ft=I.PostgrestClient=Wt.default;const Mt=ae.__importDefault(Bt());var Vt=I.PostgrestQueryBuilder=Mt.default;const Kt=ae.__importDefault(Xe());var Ht=I.PostgrestFilterBuilder=Kt.default;const zt=ae.__importDefault(Dt());var Jt=I.PostgrestTransformBuilder=zt.default;const Gt=ae.__importDefault(Lt());var Qt=I.PostgrestBuilder=Gt.default;const Yt=ae.__importDefault(Nt());qt=I.PostgrestError=Yt.default;var Xt=I.default={PostgrestClient:Wt.default,PostgrestQueryBuilder:Mt.default,PostgrestFilterBuilder:Kt.default,PostgrestTransformBuilder:zt.default,PostgrestBuilder:Gt.default,PostgrestError:Yt.default};const Tr=pr({__proto__:null,get PostgrestBuilder(){return Qt},get PostgrestClient(){return Ft},get PostgrestError(){return qt},get PostgrestFilterBuilder(){return Ht},get PostgrestQueryBuilder(){return Vt},get PostgrestTransformBuilder(){return Jt},default:Xt},[I]),{PostgrestClient:Ar}=Xt||Tr;class jr{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;
1if(t&&t.node){const r=t.node,s=parseInt(r.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
2import ws from "ws"
3new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`
4
5Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const r=this.getWebSocketConstructor();return new r(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Pr="2.78.0",Rr=`realtime-js/${Pr}`,Cr="1.0.0",We=1e4,Ir=1e3,$r=100;var ce;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(ce||(ce={}));var P;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(P||(P={}));var D;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(D||(D={}));var Fe;(function(i){i.websocket="websocket"})(Fe||(Fe={}));var H;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(H||(H={}));class xr{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const s=t.getUint8(1),n=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=r.decode(e.slice(o,o+s));o=o+s;const l=r.decode(e.slice(o,o+n));o=o+n;const c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}}class Zt{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 O;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(O||(O={}));const pt=(i,e,t={})=>{var r;const s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return e?Object.keys(e).reduce((n,o)=>(n[o]=Ur(o,i,e,s),n),{}):{}},Ur=(i,e,t,r)=>{const s=e.find(a=>a.name===i),n=s?.type,o=t[i];return n&&!r.includes(n)?er(n,o):Me(o)},er=(i,e)=>{if(i.charAt(0)==="_"){const t=i.slice(1,i.length);return Br(e,t)}switch(i){case O.bool:return Nr(e);case O.float4:case O.float8:case O.int2:case O.int4:case O.int8:case O.numeric:case O.oid:return Lr(e);case O.json:case O.jsonb:return Dr(e);case O.timestamp:return qr(e);case O.abstime:case O.date:case O.daterange:case O.int4range:case O.int8range:case O.money:case O.reltime:case O.text:case O.time:case O.timestamptz:case O.timetz:case O.tsrange:case O.tstzrange:return Me(e);default:return Me(e)}},Me=i=>i,Nr=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Lr=i=>{if(typeof i=="string"){const e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Dr=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Br=(i,e)=>
5{if(typeof i!="string")return i;const t=i.length-1,r=i[t];if(i[0]==="{"&&r==="}"){let n;const o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>er(e,a))}return i},qr=i=>typeof i=="string"?i.replace(" ","T"):i,tr=i=>{const e=new URL(i);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class Ce{constructor(e,t,r={},s=We){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var wt;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(wt||(wt={}));class ue{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ue.syncState(this.state,s,n,o),this.pendingDiffs.forEach(l=>{this.state=ue.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=ue.syncDiff(this.state,s,n,o),a())}),this.onJoin((s,n,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:n,newPresences:o})}),this.onLeave((s,n,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(c,u)=>{o[c]||(l[c]=u)}),this.map(o,(c,u)=>{const d=n[c];if(d){const h=u.map(p=>p.presence_ref),f=d.map(p=>p.presence_ref),w=u.filter(p=>f.indexOf(p.presence_ref)<0),g=d.filter(p=>h.indexOf(p.presence_ref)<0);w.length>0&&(a[c]=w),g.length>0&&(l[c]=g)}else a[c]=u}),this.syncDiff(n,{joins:a,leaves:l},r,s)}static syncDiff(e,t,r,s){const{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(a,l)=>{var c;const u=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),u.length>0){const d=e[a].map(f=>f.presence_ref),h=u.filter(f=>d.indexOf(f.presence_ref)<0);e[a].unshift(...h)}r(a,u,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const u=l.map(d=>d.presence_ref);c=c.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=c,s(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return"metas"in s?t[r]=s.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=s,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 vt;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(vt||(vt={}));var he;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes",i.SYSTEM="system"})(he||(he={}));var B;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(B||(B={}));class Ze{constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=P.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 Ce(this,D.join,this.params,this.timeout),this.rejoinTimer=new Zt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=P.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=P.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=P.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=P.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=P.errored,this.rejoinTimer.scheduleTimeout())}),this._on(D.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new ue(this),this.broadcastEndpointURL=tr(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((n=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||n===void 0)&&n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,n;if(this.socket.isConnected()||this.socket.connect(),this.state==P.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,c=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(f=>f.filter))!==null&&s!==void 0?s:[],u=!!this.bindings[he.PRESENCE]&&this.bindings[he.PRESENCE].length>0||((n=this.params.config.presence)===null||n===void 0?void 0:n.enabled)===!0,d={},h={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(f=>e?.(B.CHANNEL_ERROR,f)),this._onClose(()=>e?.(B.CLOSED)),this.updateJoinPayload(Object.assign({config:h},d)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:f})=>{var w;if(this.socket.setAuth(),f===void 0){e?.(B.SUBSCRIBED);return}else{const g=this.bindings.postgres_changes,p=(w=g?.length)!==null&&w!==void 0?w:0,_=[];for(let v=0;v<p;v++){const E=g[v],{filter:{event:S,schema:k,table:T,filter:Re}}=E,R=f&&f[v];if(R&&R.event===S&&R.schema===k&&R.table===T&&R.filter===Re)_.push(Object.assign(Object.assign({},E),{id:R.id}));
5else{this.unsubscribe(),this.state=P.errored,e?.(B.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e(B.SUBSCRIBED);return}}).receive("error",f=>{this.state=P.errored,e?.(B.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(B.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===P.joined&&e===he.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var s;const n=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(t==null)return Promise.reject("Payload is required for httpSend()");const o={method:"POST",headers:{Authorization:n,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{const c=await a.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,t={}){var r,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated 
5in the future. Please use httpSend() explicitly for REST delivery.");const{event:n,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=P.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(D.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new Ce(this,D.leave,{},e),r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=P.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,n=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Ce(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>$r){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:u}=D;if(r&&[a,l,c,u].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var w,g,p;return((w=f.filter)===null||w===void 0?void 0:w.event)==="*"||((p=(g=f.filter)===null||g===void 0?void 0:g.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(f=>f.callback(h,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var w,g,p,_,v,E;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){const S=f.id,k=(w=f.filter)===null||w===void 0?void 0:w.event;return S&&((g=t.ids)===null||g===void 0?void 0:g.includes(S))&&(k==="*"||k?.toLocaleLowerCase()===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{const S=(v=(_=f?.filter)===null||_===void 0?void 0:_.event)===null||v===void 0?void 0:v.toLocaleLowerCase();return S==="*"||S===((E=t?.event)===null||E===void 0?void 0:E.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof h=="object"&&"ids"in h){const w=h.data,{schema:g,table:p,commit_timestamp:_,type:v,errors:E}=w;h=Object.assign(Object.assign({},{schema:g,table:p,commit_timestamp:_,eventType:v,new:{},old:{},errors:E}),this._getPayloadRecords(w))}f.callback(h,r)})}_isClosed(){return this.state===P.closed}_isJoined(){return this.state===P.joined}_isJoining(){return this.state===P.joining}_isLeaving(){return this.state===P.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(s=>{var n;return!(((n=s.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&Ze.isEqual(s.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(D.close,{},e)}_onError(e){this._on(D.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=P.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=pt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=
5pt(e.columns,e.old_record)),t}}const Ie=()=>{},Ee={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Wr=[1e3,2e3,5e3,1e4],Fr=1e4,Mr=`
6  addEventListener("message", (e) => {
7    if (e.data.event === "start") {
8      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
9    }
10  });`;class Vr{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=We,this.transport=null,this.heartbeatIntervalMs=Ee.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ie,this.ref=0,this.reconnectTimer=null,this.logger=Ie,this.conn=null,this.sendBuffer=[],this.serializer=new xr,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=s=>{let n;return s?n=s:typeof fetch>"u"?n=(...o)=>ne(async()=>{const{default:a}=await Promise.resolve().then(()=>G);return{default:a}},void 0).then(({default:a})=>a(...o)).catch(a=>{throw new Error(`Failed to load @supabase/node-fetch: ${a.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):n=fetch,(...o)=>n(...o)},!(!((r=t?.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Fe.websocket}`,this.httpEndpoint=tr(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=jr.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}
11
12To use Realtime in Node.js, you need to provide a WebSocket implementation:
13
14Option 1: Use Node.js 22+ which has native WebSocket support
15Option 2: Install and provide the "ws" package:
16
17  npm install ws
18
19  import ws from "ws"
20  const client = new RealtimeClient(url, {
21    ...options,
22    transport: ws
23  })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Cr}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},e?this.conn.close(e,t??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case ce.connecting:return H.Connecting;case ce.open:return H.Open;case ce.closing:return H.Closing;default:return H.Closed}}isConnected(){return this.connectionState()===H.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(n=>n.topic===r);if(s)return s;{const n=new Ze(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:r,payload:s,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(Ir,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},Ee.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>
230&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:r,event:s,payload:n,ref:o}=t,a=o?`(${o})`:"",l=n.status||"";this.log("receive",`${l} ${r} ${s} ${a}`.trim(),n),this.channels.filter(c=>c._isMember(r)).forEach(c=>c._trigger(s,n,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(D.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{const r=new Blob([Mr],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;e?t=e:this.accessToken?t=await this.accessToken():t=this.accessTokenValue,this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(r=>{const s={access_token:t,version:Rr};t&&r.updateJoinPayload(s),r.joinedOnce&&r._isJoined()&&r._push(D.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new Zt(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Ee.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,n,o,a,l,c,u;if(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(r=e?.timeout)!==null&&r!==void 0?r:We,this.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Ee.HEARTBEAT_INTERVAL,this.worker=(n=e?.worker)!==null&&n!==void 0?n:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:Ie,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=e?.reconnectAfterMs)!==null&&l!==void 0?l:d=>Wr[d-1]||Fr,this.encode=(c=e?.encode)!==null&&c!==void 0?c:(d,h)=>h(JSON.stringify(d)),this.decode=(u=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?.workerUrl}}}
23class et extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function A(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}class Kr extends et{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Ve extends et{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const tt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>ne(async()=>{const{default:r}=await Promise.resolve().then(()=>G);return{default:r}},void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Hr=()=>y(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ne(()=>Promise.resolve().then(()=>G),void 0)).Response:Response}),Ke=i=>{if(Array.isArray(i))return i.map(t=>Ke(t));if(typeof i=="function"||i!==Object(i))return i;const e={};return Object.entries(i).forEach(([t,r])=>{const s=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[s]=Ke(r)}),e},zr=i=>{if(typeof i!="object"||i===null)return!1;const e=Object.getPrototypeOf(i);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in i)&&!(Symbol.iterator in i)},$e=i=>{var e;return i.msg||i.message||i.error_description||(typeof i.error=="string"?i.error:(e=i.error)===null||e===void 0?void 0:e.message)||JSON.stringify(i)},Jr=(i,e,t)=>y(void 0,void 0,void 0,function*(){const r=yield Hr();i instanceof r&&!t?.noResolveJson?i.json().then(s=>{const n=i.status||500,o=s?.statusCode||n+"";e(new Kr($e(s),n,o))}).catch(s=>{e(new Ve($e(s),s))}):e(new Ve($e(i),i))}),Gr=(i,e,t,r)=>{const s={method:i,headers:e?.headers||{}};return i==="GET"||!r?s:(zr(r)?(s.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(r)):s.body=r,e?.duplex&&(s.duplex=e.duplex),Object.assign(Object.assign({},s),t))};function pe(i,e,t,r,s,n){return y(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Gr(e,r,s,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Jr(l,a,r))})})}function de(i,e,t,r){return y(this,void 0,void 0,function*(){return pe(i,"GET",e,t,r)})}function L(i,e,t,r,s){return y(this,void 0,void 0,function*(){return pe(i,"POST",e,r,s,t)})}function He(i,e,t,r,s){return y(this,void 0,void 0,function*(){return pe(i,"PUT",e,r,s,t)})}function Qr(i,e,t,r){return y(this,void 0,void 0,function*(){return pe(i,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),r)})}function rt(i,e,t,r,s){return y(this,void 0,void 0,function*(){return pe(i,"DELETE",e,r,s,t)})}class Yr{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return y(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(A(e))return{data:null,error:e};throw e}})}}var rr;class Xr{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[rr]="BlobDownloadBuilder",this.promise=null}asStream(){return new Yr(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return y(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(A(e))return{data:null,error:e};throw e}})}}rr=Symbol.toStringTag;const Zr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_t={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class es{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=tt(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,r,s){return y(this,void 0,void 0,function*(){try{let n;const o=Object.assign(Object.assign({},_t),s);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l)),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l))):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),s?.headers&&(a=Object.assign(Object.assign({},a),s.headers));const c=this._removeEmptyFolders(t),u=this._getFinalPath(c),d=yield(e=="PUT"?He:L)(this.fetch,`${this.url}/object/${u}`,n,Object.assign({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:d.Id,fullPath:d.Key},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(A(n))return{data:null,error:n};throw n}})}upload(e,t,r){return y(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return y(this,void 0,void 0,function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:_t.upsert},s),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const d=yield He(this.fetch,a.toString(),l,{headers:u});return{data:{path:n,fullPath:d.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(A(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return y(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const s=Object.assign({},this.headers);t?.upsert&&(s["x-upsert"]="true");const n=yield L(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new et("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(A(r))return{data:null,error:r};throw r}})}update(e,t,r){return y(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return y(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,de
23stinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(A(s))return{data:null,error:s};throw s}})}copy(e,t,r){return y(this,void 0,void 0,function*(){try{return{data:{path:(yield L(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(A(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,r){return y(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=yield L(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(A(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return y(this,void 0,void 0,function*(){try{const s=yield L(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(A(s))return{data:null,error:s};throw s}})}download(e,t){const s=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"",a=this._getFinalPath(e),l=()=>de(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0});return new Xr(l,this.shouldThrowOnError)}info(e){return y(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const r=yield de(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Ke(r),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(A(r))return{data:null,error:r};throw r}})}exists(e){return y(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield Qr(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(A(r)&&r instanceof Ve){const s=r.originalError;if([400,404].includes(s?.status))return{data:!1,error:r}}throw r}})}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&s.push(n);const a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&s.push(l);let c=s.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return y(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}list(e,t,r){return y(this,void 0,void 0,function*(){try{const s=Object.assign(Object.assign(Object.assign({},Zr),t),{prefix:e||""});return{data:yield L(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(A(s))return{data:null,error:s};throw s}})}listV2(e,t){return y(this,void 0,void 0,function*(){try{const r=Object.assign({},e);return{data:yield L(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},t),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(A(r))return{data:null,error:r};throw r}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const sr="2.78.0",ir={"X-Client-Info":`storage-js/${sr}`};class ts{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const n=new URL(e);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},ir),t),this.fetch=tt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return y(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield de(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}getBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield de(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}createBucket(e){return y(this,arguments,void 0,function*(t,r={public:!1}){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{id:t,name:t,type:r.type,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(A(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return y(this,void 0,void 0,function*(){try{return{data:yield He(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(r){if(this.shouldThrowOnError)throw r;if(A(r))return{data:null,error:r};throw r}})}emptyBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}deleteBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}}class rs{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},ir),t),this.fetch=tt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}listBuckets(e){return y(this,void 0,void 0,function*(){try{const t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",e.limit.toString()),e?.offset!==void 0&&t.set("offset",e.offset.toString()),e?.sortColumn&&t.set("sortColumn",e.sortColumn),e?.sortOrder&&t.set("sortOrder",e.sortOrder),e?.search&&t.set("search",e.search);const r=t.toString(),s=r?`${this.url}/bucket?${r}`:`${this.url}/bucket`;return{data:yield de(this.fetch,s,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}deleteBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(A(t))return{data:null,error:t};throw t}})}}const st={"X-Client-Info":`storage-js/${sr}`,"Content-Type":"application/json"};
23class nr extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function $(i){return typeof i=="object"&&i!==null&&"__isStorageVectorsError"in i}class xe extends nr{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class ss extends nr{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var yt;(function(i){i.InternalError="InternalError",i.S3VectorConflictException="S3VectorConflictException",i.S3VectorNotFoundException="S3VectorNotFoundException",i.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",i.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",i.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"})(yt||(yt={}));const it=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>ne(async()=>{const{default:r}=await Promise.resolve().then(()=>G);return{default:r}},void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},is=i=>{if(typeof i!="object"||i===null)return!1;const e=Object.getPrototypeOf(i);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in i)&&!(Symbol.iterator in i)},bt=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),ns=(i,e,t)=>y(void 0,void 0,void 0,function*(){if(i&&typeof i=="object"&&"status"in i&&"ok"in i&&typeof i.status=="number"&&!t?.noResolveJson){const s=i.status||500,n=i;if(typeof n.json=="function")n.json().then(o=>{const a=o?.statusCode||o?.code||s+"";e(new xe(bt(o),s,a))}).catch(()=>{const o=s+"",a=n.statusText||`HTTP ${s} error`;e(new xe(a,s,o))});else{const o=s+"",a=n.statusText||`HTTP ${s} error`;e(new xe(a,s,o))}}else e(new ss(bt(i),i))}),os=(i,e,t,r)=>{const s={method:i,headers:e?.headers||{}};return r?(is(r)?(s.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(r)):s.body=r,Object.assign(Object.assign({},s),t)):s};function as(i,e,t,r,s,n){return y(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,os(e,r,s,n)).then(l=>{if(!l.ok)throw l;if(r?.noResolveJson)return l;const c=l.headers.get("content-type");return!c||!c.includes("application/json")?{}:l.json()}).then(l=>o(l)).catch(l=>ns(l,a,r))})})}function x(i,e,t,r,s){return y(this,void 0,void 0,function*(){return as(i,"POST",e,r,s,t)})}class ls{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},st),t),this.fetch=it(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return y(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}getIndex(e,t){return y(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($(r))return{data:null,error:r};throw r}})}listIndexes(e){return y(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}deleteIndex(e,t){return y(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if($(r))return{data:null,error:r};throw r}})}}class cs{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},st),t),this.fetch=it(r)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return y(this,void 0,void 0,function*(){try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:(yield x(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}getVectors(e){return y(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}listVectors(e){return y(this,void 0,void 0,function*(){try{if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");
23if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return{data:yield x(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}queryVectors(e){return y(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}deleteVectors(e){return y(this,void 0,void 0,function*(){try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:(yield x(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}}class us{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},st),t),this.fetch=it(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return y(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}getBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}listBuckets(){return y(this,arguments,void 0,function*(e={}){try{return{data:yield x(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}deleteBucket(e){return y(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if($(t))return{data:null,error:t};throw t}})}}class hs extends us{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new ds(this.url,this.headers,e,this.fetch)}}class ds extends ls{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return y(this,void 0,void 0,function*(){return t.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return y(this,arguments,void 0,function*(t={}){return e.listIndexes.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){const t=Object.create(null,{getIndex:{get:()=>super.getIndex}});return y(this,void 0,void 0,function*(){return t.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){const t=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return y(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new fs(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class fs extends cs{constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return y(this,void 0,void 0,function*(){return t.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){const t=Object.create(null,{getVectors:{get:()=>super.getVectors}});return y(this,void 0,void 0,function*(){return t.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return y(this,arguments,void 0,function*(t={}){return e.listVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){const t=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return y(this,void 0,void 0,function*(){return t.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){const t=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return y(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class gs extends ts{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new es(this.url,this.headers,e,this.fetch)}get vectors(){return new hs(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new rs(this.url+"/iceberg",this.headers,this.fetch)}}const ps="2.78.0";let le="";typeof Deno<"u"?le="deno":typeof document<"u"?le="web":typeof navigator<"u"&&navigator.product==="ReactNative"?le="react-native":le="node";const ws={"X-Client-Info":`supabase-js-${le}/${ps}`},vs={headers:ws},_s={schema:"public"},ys={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},bs={},ms=i=>{let e;return i?e=i:typeof fetch>"u"?e=xt:e=fetch,(...t)=>e(...t)},Es=()=>typeof Headers>"u"?Ut:Headers,ks=(i,e,t)=>{const r=ms(t),s=Es();return async(n,o)=>{var a;const l=(a=await e())!==null&&a!==void 0?a:i;let c=new s(o?.headers);return c.has("apikey")||c.set("apikey",i),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:c}))}};function Ss(i){return i.endsWith("/")?i:i+"/"}function Os(i,e){var t,r;const{db:s,auth:n,realtime:o,global:a}=i,{db:l,auth:c,realtime:u,global:d}=e,h={db:Object.assign(Object.assign({},l),s),auth:Object.assign(Object.assign({},c),n),realtime:Object.assign(Object.assign({},u),o),storage:{},global:Object.assign(Object.assign(Object.assign({},d),a),{headers:Object.assign(Object.assign({},(t=d?.headers)!==null&&t!==void 0?t:{}),(r=a?.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return i.accessToken?h.accessToken=i.accessToken:delete h.accessToken,h}function Ts(i){const e=i?.trim();if(!e)throw new Error("supabaseUrl is required.");
23if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Ss(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const or="2.78.0",te=30*1e3,ze=3,Ue=ze*te,As="http://localhost:9999",js="supabase.auth.token",Ps={"X-Client-Info":`gotrue-js/${or}`},Je="X-Supabase-Api-Version",ar={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Rs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Cs=10*60*1e3;class fe extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function b(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}class Is extends fe{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function $s(i){return b(i)&&i.name==="AuthApiError"}class z extends fe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class F extends fe{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class U extends F{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function xs(i){return b(i)&&i.name==="AuthSessionMissingError"}class Q extends F{constructor(){super("Auth session or user missing","AuthInvalidToken
23ResponseError",500,void 0)}}class ke extends F{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Se extends F{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 Us(i){return b(i)&&i.name==="AuthImplicitGrantRedirectError"}class mt extends F{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 Ge extends F{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Ne(i){return b(i)&&i.name==="AuthRetryableFetchError"}class Et extends F{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class Qe extends F{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Oe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),kt=` 	
24\r=`.split(""),Ns=(()=>{const i=new Array(128);for(let e=0;e<i.length;e+=1)i[e]=-1;for(let e=0;e<kt.length;e+=1)i[kt[e].charCodeAt(0)]=-2;for(let e=0;e<Oe.length;e+=1)i[Oe[e].charCodeAt(0)]=e;return i})();function St(i,e,t){if(i!==null)for(e.queue=e.queue<<8|i,e.queuedBits+=8;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(Oe[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(Oe[r]),e.queuedBits-=6}}function lr(i,e,t){const r=Ns[i];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(i)}"`)}}function Ot(i){const e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},n=o=>{Bs(o,r,t)};for(let o=0;o<i.length;o+=1)lr(i.charCodeAt(o),s,n);return e.join("")}function Ls(i,e){if(i<=127){e(i);return}else if(i<=2047){e(192|i>>6),e(128|i&63);return}else if(i<=65535){e(224|i>>12),e(128|i>>6&63),e(128|i&63);return}else if(i<=1114111){e(240|i>>18),e(128|i>>12&63),e(128|i>>6&63),e(128|i&63);return}throw new Error(`Unrecognized Unicode codepoint: ${i.toString(16)}`)}function Ds(i,e){for(let t=0;t<i.length;t+=1){let r=i.charCodeAt(t);if(r>55295&&r<=56319){const s=(r-55296)*1024&65535;r=(i.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}Ls(r,e)}}function Bs(i,e,t){if(e.utf8seq===0){if(i<=127){t(i);return}for(let r=1;r<6;r+=1)if(!(i>>7-r&1)){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=i&31;else if(e.utf8seq===3)e.codepoint=i&15;else if(e.utf8seq===4)e.codepoint=i&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(i<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|i&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function se(i){const e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;s<i.length;s+=1)lr(i.charCodeAt(s),t,r);return new Uint8Array(e)}function qs(i){const e=[];return Ds(i,t=>e.push(t)),new Uint8Array(e)}function J(i){const e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return i.forEach(s=>St(s,t,r)),St(null,t,r),e.join("")}function Ws(i){return Math.round(Date.now()/1e3)+i}function Fs(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){const e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}const C=()=>typeof window<"u"&&typeof document<"u",M={tested:!1,writable:!1},cr=()=>{if(!C())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(M.tested)return M.writable;const i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),M.tested=!0,M.writable=!0}catch{M.tested=!0,M.writable=!1}return M.writable};function Ms(i){const e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,n)=>{e[n]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}const ur=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>ne(async()=>{const{default:r}=await Promise.resolve().then(()=>G);return{default:r}},void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Vs=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",re=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},V=async(i,e)=>{const t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},q=async(i,e)=>{await i.removeItem(e)};class Pe{constructor(){this.promise=new Pe.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Pe.promiseConstructor=Promise;function Le(i){const e=i.split(".");if(e.length!==3)throw new Qe("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!Rs.test(e[r]))throw new Qe("JWT not in base64url format");return{header:JSON.parse(Ot(e[0])),payload:JSON.parse(Ot(e[1])),signature:se(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ks(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Hs(i,e){return new Promise((r,s)=>{(async()=>{for(let n=0;n<1/0;n++)try{const o=await i(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){s(o);return}}})()})}function zs(i){return("0"+i.toString(16)).substr(-2)}function Js(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length;let s="";for(let n=0;n<56;n++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,zs).join("")}async function Gs(i){const t=new TextEncoder().encode(i),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(n=>String.fromCharCode(n)).join("")}async function Qs(i){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code 
24challenge method will default to use plain instead of sha256."),i;const t=await Gs(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Y(i,e,t=!1){const r=Js();let s=r;t&&(s+="/PASSWORD_RECOVERY"),await re(i,`${e}-code-verifier`,s);const n=await Qs(r);return[n,r===n?"plain":"s256"]}const Ys=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Xs(i){const e=i.headers.get(Je);if(!e||!e.match(Ys))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Zs(i){if(!i)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(i<=e)throw new Error("JWT has expired")}function ei(i){switch(i){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const ti=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function X(i){if(!ti.test(i))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function De(){const i={};return new Proxy(i,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function ri(i,e){return new Proxy(i,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)"||n==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="string"&&(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."),e.value=!0),Reflect.get(t,r,s)}})}function Tt(i){return JSON.parse(JSON.stringify(i))}const K=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),si=[502,503,504];async function At(i){var e;if(!Vs(i))throw new Ge(K(i),0);if(si.includes(i.status))throw new Ge(K(i),i.status);let t;try{t=await i.json()}catch(n){throw new z(K(n),n)}let r;const s=Xs(i);if(s&&s.getTime()>=ar["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Et(K(t),i.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new U}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new Et(K(t),i.status,t.weak_password.reasons);throw new Is(K(t),i.status||500,r)}const ii=(i,e,t,r)=>{const s={method:i,headers:e?.headers||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function m(i,e,t,r){var s;const n=Object.assign({},r?.headers);n[Je]||(n[Je]=ar["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);const o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await ni(i,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function ni(i,e,t,r,s,n){const o=ii(e,r,s,n);let a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new Ge(K(l),0)}if(a.ok||await At(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await At(l)}}function N(i){var e;let t=null;li(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Ws(i.expires_in)));const r=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:r},error:null}}function jt(i){const e=N(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=i.weak_password),e}function W(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function oi(i){return{data:i,error:null}}function ai(i){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n}=i,o=je(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Pt(i){return i}function li(i){return i.access_token&&i.refresh_token&&i.expires_in}const Be=["global","local","others"];class ci{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ur(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=Be[0]){if(Be.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Be.join(", ")}`);try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:W})}catch(r){if(b(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=je(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:ai,redirectTo:t?.redirectTo})}catch(t){if(b(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:W})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,n,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},u=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&n!==void 0?n:""},xform:Pt});if(u.error)throw u.error;const d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(w=>{const g=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(w.split(";")[1].split("=")[1]);c[`${p}Page`]=g}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(b(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){X(e);try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:W})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){X(e);try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:W})}catch(r){if(b(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){X(e);
24try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:W})}catch(r){if(b(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){X(e.userId);try{const{data:t,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _deleteFactor(e){X(e.userId),X(e.id);try{return{data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,n,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},u=await m(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&n!==void 0?n:""},xform:Pt});if(u.error)throw u.error;const d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(w=>{const g=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(w.split(";")[1].split("=")[1]);c[`${p}Page`]=g}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(b(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await m(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await m(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(b(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await m(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}}function Rt(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}const Z={debug:!!(globalThis&&cr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class hr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ui extends hr{}async function hi(i,e,t){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Z.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,s.name);try{return await t()}finally{Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,s.name)}}else{if(e===0)throw Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new ui(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(Z.debug)try{const n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null,"  "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}function di(){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)}}function dr(i){if(!/^0x[a-fA-F0-9]{40}$/.test(i))throw new Error(`@supabase/auth-js: Address "${i}
24" is invalid.`);return i.toLowerCase()}function fi(i){return parseInt(i,16)}function gi(i){const e=new TextEncoder().encode(i);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function pi(i){var e;const{chainId:t,domain:r,expirationTime:s,issuedAt:n=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:h}=i;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(!((e=i.statement)===null||e===void 0)&&e.includes(`
25`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${i.statement}`)}const f=dr(i.address),w=u?`${u}://${r}
25`:r,g=i.statement?`${i.statement}
26`:"",p=`${w} wants you to sign in with your Ethereum account:
27${f}
28
29${g}`;let _=`URI: ${d}
30Version: ${h}
31Chain ID: ${t}${o?`
32Nonce: ${o}`:""}
33Issued At: ${n.toISOString()}`;if(s&&(_+=`
34Expiration Time: ${s.toISOString()}`),a&&(_+=`
35Not Before: ${a.toISOString()}`),l&&(_+=`
36Request ID: ${l}`),c){let v=`
37Resources:`;for(const E of c){if(!E||typeof E!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${E}`);v+=`
38- ${E}`}_+=v}return`${p}
39${_}`}class j extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(n=s??(r instanceof Error?r.name:void 0))!==null&&n!==void 0?n:"Unknown Error",this.code=t}}class Te extends j{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function wi({error:i,options:e}){var t,r,s;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(i.name==="AbortError"){if(e.signal instanceof AbortSignal)return new j({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:i})}else if(i.name==="ConstraintError"){if(((t=n.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new j({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:i});if(e.mediation==="conditional"&&((r=n.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new j({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:i});if(((s=n.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new j({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:i})}else{if(i.name==="InvalidStateError")return new j({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:i});if(i.name==="NotAllowedError")return new j({message:i.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i});if(i.name==="NotSupportedError")return n.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new j({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:i}):new j({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:i});if(i.name==="SecurityError"){const o=window.location.hostname;if(fr(o)){if(n.rp.id!==o)return new j({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:i})}else return new j({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:i})}else if(i.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new j({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:i})}else if(i.name==="UnknownError")return new j({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:i})}return new j({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i})}function vi({error:i,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(i.name==="AbortError"){if(e.signal instanceof AbortSignal)return new j({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:i})}else{if(i.name==="NotAllowedError")return new j({message:i.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i});if(i.name==="SecurityError"){const r=window.location.hostname;if(fr(r)){if(t.rpId!==r)return new j({message:`The RP ID "${t.rpId}
39" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:i})}else return new j({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:i})}else if(i.name==="UnknownError")return new j({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:i})}return new j({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i})}class _i{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const yi=new _i;function bi(i){if(!i)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(i);const{challenge:e,user:t,excludeCredentials:r}=i,s=je(i,["challenge","user","excludeCredentials"]),n=se(e).buffer,o=Object.assign(Object.assign({},t),{id:se(t.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:n,user:o});if(r&&r.length>0){a.excludeCredentials=new Array(r.length);for(let l=0;l<r.length;l++){const c=r[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:se(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function mi(i){if(!i)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(i);const{challenge:e,allowCredentials:t}=i,r=je(i,["challenge","allowCredentials"]),s=se(e).buffer,n=Object.assign(Object.assign({},r),{challenge:s});if(t&&t.length>0){n.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){const a=t[o];n.allowCredentials[o]=Object.assign(Object.assign({},a),{id:se(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return n}function Ei(i){var e;if("toJSON"in i&&typeof i.toJSON=="function")return i.toJSON();const t=i;return{id:i.id,rawId:i.id,response:{attestationObject:J(new Uint8Array(i.response.attestationObject)),clientDataJSON:J(new Uint8Array(i.response.clientDataJSON))},type:"public-key",clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ki(i){var e;if("toJSON"in i&&typeof i.toJSON=="function")return i.toJSON();const t=i,r=i.getClientExtensionResults(),s=i.response;return{id:i.id,rawId:i.id,response:{authenticatorData:J(new Uint8Array(s.authenticatorData)),clientDataJSON:J(new Uint8Array(s.clientDataJSON)),signature:J(new Uint8Array(s.signature)),userHandle:s.userHandle?J(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function fr(i){return i==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(i)}function Ct(){var i,e;return!!(C()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((i=navigator?.credentials)===null||i===void 0?void 0:i.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Si(i){try{const e=await navigator.credentials.create(i);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Te("Browser returned unexpected credential type",e)}:{data:null,error:new Te("Empty credential response",e)}}catch(e){return{data:null,error:wi({error:e,options:i})}}}async function Oi(i){try{const e=await navigator.credentials.get(i);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Te("Browser returned unexpected credential type",e)}:{data:null,error:new Te("Empty credential response",e)}}catch(e){return{data:null,error:vi({error:e,options:i})}}}const Ti={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"none"},Ai={userVerification:"preferred",hints:["security-key"]};function Ae(...i){const e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(const s of i)if(s)for(const n in s){const o=s[n];if(o!==void 0)if(Array.isArray(o))r[n]=o;else if(t(o))r[n]=o;else if(e(o)){const a=r[n];e(a)?r[n]=Ae(a,o):r[n]=Ae(o)}else r[n]=o}return r}function ji(i,e){return Ae(Ti,i,e||{})}function Pi(i,e){return Ae(Ai,i,e||{})}class Ri{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},n){try{const{data:o,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:a};const l=s??yi.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:c}=o.webauthn.credential_options.publicKey;c.name||(c.name=`${c.id}:${r}`),c.displayName||(c.displayName=c.name)}switch(o.webauthn.type){case"create":{const c=ji(o.webauthn.credential_options.publicKey,n?.create),{data:u,error:d}=await Si({publicKey:c,signal:l});return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}case"request":{const c=Pi(o.webauthn.credential_options.publicKey,n?.request),{data:u,error:d}=await Oi(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:c,signal:l}));return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}}}catch(o){return b(o)?{data:null,error:o}:{data:null,error:new z("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}},n){if(!t)return{data:null,error:new fe("rpId is required for WebAuthn authentication")};try{if(!Ct())return{data:null,error:new z("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:n});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:t,rpOrigins:r,credential_response:l.credential_response}})}catch(o){return b(o)?{data:null,error:o}:{data:null,error:new z("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s},n){if(!t)return{data:null,error:new fe("rpId is required for WebAuthn registration")};try{if(!Ct())return{data:null,error:new z("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===e&&h.status!=="unverified")}).then(u=>
39u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};const{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:n});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:t,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return b(o)?{data:null,error:o}:{data:null,error:new z("Unexpected error in register",o)}}}}di();const Ci={url:As,storageKey:js,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ps,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function It(i,e,t){return await t()}const ee={};class ge{get jwks(){var e,t;return(t=(e=ee[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){ee[this.storageKey]=Object.assign(Object.assign({},ee[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=ee[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ee[this.storageKey]=Object.assign(Object.assign({},ee[this.storageKey]),{cachedAt:e})}constructor(e){var t,r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=ge.nextInstanceID,ge.nextInstanceID+=1,this.instanceID>0&&C()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const s=Object.assign(Object.assign({},Ci),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new ci({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=ur(s.fetch),this.lock=s.lock||It,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:C()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=hi:this.lock=It,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),webauthn:new Ri(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:cr()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Rt(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Rt(this.memoryStorage)),C()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${or}) ${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=Ms(window.location.href);let r="none";if(this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce"),C()&&this.detectSessionInUrl&&r!=="none"){const{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),Us(n)){const l=(e=n.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:n}}return await this._removeSession(),{error:n}}const{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return b(t)?{error:t}:{error:new z("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:N}),{data:o,error:a}=n;
39if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(b(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,s;try{let n;if("email"in e){const{email:u,password:d,options:h}=e;let f=null,w=null;this.flowType==="pkce"&&([f,w]=await Y(this.storage,this.storageKey)),n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h?.emailRedirectTo,body:{email:u,password:d,data:(t=h?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:f,code_challenge_method:w},xform:N})}else if("phone"in e){const{phone:u,password:d,options:h}=e;n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(r=h?.data)!==null&&r!==void 0?r:{},channel:(s=h?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:N})}else throw new ke("You must provide either an email or phone number and a password");const{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(b(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:jt})}else if("phone"in e){const{phone:n,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:jt})}else throw new ke("You must provide either an email or phone number and a password");const{data:r,error:s}=t;return s?{data:{user:null,session:null},error:s}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Q}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,n,o,a,l,c,u,d,h;let f,w;if("message"in e)f=e.message,w=e.signature;else{const{wallet:g,statement:p,options:_}=e;let v;if(C())if(typeof g=="object")v=g;else{const R=window;if("ethereum"in R&&typeof R.ethereum=="object"&&"request"in R.ethereum&&typeof R.ethereum.request=="function")v=R.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof g!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=g}const E=new URL((t=_?.url)!==null&&t!==void 0?t:window.location.href),S=await v.request({method:"eth_requestAccounts"}).then(R=>R).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!S||S.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const k=dr(S[0]);let T=(r=_?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!T){const R=await v.request({method:"eth_chainId"});T=fi(R)}const Re={domain:E.host,address:k,statement:p,uri:E.href,version:"1",chainId:T,nonce:(s=_?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(n=_?.signInWithEthereum)===null||n===void 0?void 0:n.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=_?.
39signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=_?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=_?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=_?.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=pi(Re),w=await v.request({method:"personal_sign",params:[gi(f),k]})}try{const{data:g,error:p}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:w},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:N});if(p)throw p;return!g||!g.session||!g.user?{data:{user:null,session:null},error:new Q}:(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),{data:Object.assign({},g),error:p})}catch(g){if(b(g))return{data:{user:null,session:null},error:g};throw g}}async signInWithSolana(e){var t,r,s,n,o,a,l,c,u,d,h,f;let w,g;if("message"in e)w=e.message,g=e.signature;else{const{wallet:p,statement:_,options:v}=e;let E;if(C())if(typeof p=="object")E=p;
39else{const k=window;if("solana"in k&&typeof k.solana=="object"&&("signIn"in k.solana&&typeof k.solana.signIn=="function"||"signMessage"in k.solana&&typeof k.solana.signMessage=="function"))E=k.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 p!="object"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=p}const S=new URL((t=v?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in E&&E.signIn){const k=await E.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},v?.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),_?{statement:_}:null));let T;if(Array.isArray(k)&&k[0]&&typeof k[0]=="object")T=k[0];else if(k&&t
39ypeof k=="object"&&"signedMessage"in k&&"signature"in k)T=k;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in T&&"signature"in T&&(typeof T.signedMessage=="string"||T.signedMessage instanceof Uint8Array)&&T.signature instanceof Uint8Array)w=typeof T.signedMessage=="string"?T.signedMessage:new TextDecoder().decode(T.signedMessage),g=T.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in E)||typeof E.signMessage!="function"||!("publicKey"in E)||typeof E!="object"||!E.publicKey||!("toBase58"in E.publicKey)||typeof E.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");w=[`${S.host} wants you to sign in with your Solana account:`,E.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(s=(r=v?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((n=v?.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${v.signInWithSolana.notBefore}
39`]:[],...!((o=v?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${v.signInWithSolana.expirationTime}`]:[],...!((a=v?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${v.signInWithSolana.chainId}`]:[],...!((l=v?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${v.signInWithSolana.nonce}`]:[],...!((c=v?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${v.signInWithSolana.requestId}`]:[],...!((d=(u=v?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...v.signInWithSolana.resources.map(T=>`- ${T}`)]:[]].join(`
40`);const k=await E.signMessage(new TextEncoder().encode(w),"utf8");if(!k||!(k instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=k}}try{const{data:p,error:_}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:w,signature:J(g)},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:N});if(_)throw _;return!p||!p.session||!p.user?{data:{user:null,session:null},error:new Q}:(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session)),{data:Object.assign({},p),error:_})}catch(p){if(b(p))return{data:{user:null,session:null},error:p};throw p}}async _exchangeCodeForSession(e){const t=await V(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(t??"").split("/");try{const{data:n,error:o}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:N});if(await q(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Q}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:s??null}),error:o})}catch(n){if(b(n))return{data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:n,nonce:o}=e,a=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:N}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Q}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,s,n,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Y(this.storage,this.storageKey));const{error:d}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:u}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:u}}throw new ke("You must provide either an email or phone number.")}catch(a){if(b(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:N});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(s){if(b(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,r,s;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Y(this.storage,this.storageKey)),await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:oi})}catch(n){if(b(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new U;const{error:s}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(b(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:n}=e,{error:o}=await m(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:r,type:s,options:n}=e,{data:o,error:a}=await m(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new ke("You must provide either an email or phone number and a type")}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await V(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
40id"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()<Ue:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const o=await V(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=De()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=ri(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:s},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 m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:W}):await this._useSession(async t=>{var r,s,n;const{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new U}:await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0,xform:W})})}catch(t){if(b(t))return xs(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 r=>{const{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new U;const o=s.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Y(this.storage,this.storageKey));const{data:c,error:u}=await m(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:W});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(b(r))return{data:{user:null},error:r};throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new U;const t=Date.now()/1e3;let r=t,s=!0,n=null;const{payload:o}=Le(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){const{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(b(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new U;const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(b(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!C())throw new Se("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Se(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 mt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Se("Not a valid implicit grant flow url.");break}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new mt("No code detected.");const{data:v,error:E}=await this._exchangeCodeForSession(e.code);
40if(E)throw E;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:v.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!n||!a||!o||!c)throw new Se("No session defined in URL");const u=Math.round(Date.now()/1e3),d=parseInt(a);let h=u+d;l&&(h=parseInt(l));const f=h-u;f*1e3<=te&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${d}s`);const w=h-d;u-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,h,u):u-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",w,h,u);const{data:g,error:p}=await this._getUser(n);if(p)throw p;const _={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:d,expires_at:h,refresh_token:o,token_type:c,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:_,redirectType:e.type},error:null}}catch(r){if(b(r))return{data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await V(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return{error:n};const o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!($s(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await q(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=Fs(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await Y(this.storage,this.storageKey,!0));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(b(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async n=>{var o,a,l,c,u;const{data:d,error:h}=n;if(h)throw h;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await m(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(s)throw s;return C()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(b(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:n}}=t;if(s)throw s;const{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=n?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:N}),{data:h,error:f}=d;return f?{data:{user:null,session:null},error:f}:!h||!h.session||!h.user?{data:{user:null,session:null},error:new Q}
40:(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),{data:h,error:f})}catch(s){if(b(s))return{data:{user:null,session:null},error:s};throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:o}=t;if(o)throw o;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await Hs(async s=>(s>0&&await Ks(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:N})),(s,n)=>{const o=200*Math.pow(2,s);return n&&Ne(n)&&Date.now()+o-r<te})}catch(r){if(this._debug(t,"error",r),b(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),C()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const s=await V(this.storage,this.storageKey);if(s&&this.userStorage){let o=await V(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await re(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o?.user)!==null&&e!==void 0?e:De()}else if(s&&!s.user&&!s.user){const o=await V(this.storage,this.storageKey+"-user");o&&o?.user?(s.user=o.user,await q(this.storage,this.storageKey+"-user"),await re(this.storage,this.storageKey,s)):s.user=De()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),s!==null&&await this._removeSession();return}const n=((t=s.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Ue;if(this._debug(r,`session has${n?"":" not"} expired with margin of ${Ue}s`),n){if(this.autoRefreshToken&&s.refresh_token){const{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Ne(o)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(s.access_token);!a&&o?.user?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(r,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(r,"error",s),console.error(s);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new U;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Pe;const{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new U;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);const a={data:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(s,"error",n),b(n)){const o={data:null,error:n};return Ne(n)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&t.user&&await re(this.userStorage,this.storageKey+"-user",{user:t.user});const s=Object.assign({},t);delete s.user;const n=Tt(s);await re(this.storage,this.storageKey,n)}else{const s=Tt(t);await re(this.storage,this.storageKey,s)}}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&&C()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}
40catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),te);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((r.expires_at*1e3-e)/te);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${te}ms, refresh threshold is ${ze} ticks`),s<=ze&&await this._callRefreshToken(r.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 hr)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!C()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[n,o]=await Y(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r?.queryParams){const n=new URLSearchParams(r.queryParams);s.push(n.toString())}return r?.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:o}=t;if(o)return{data:null,error:o};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await m(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&l.type==="totp"&&(!((s=l?.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return{data:null,error:n};const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Ei(e.webauthn.credential_response):ki(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(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:l})})}catch(t){if(b(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return{data:null,error:n};const o=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:bi(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:mi(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(b(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const n of(e=t?.factors)!==null&&e!==void 0?e:[])s.all.push(n),n.status==="verified"&&s[n.factor_type].push(n);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:s}
40=await this.getSession();if(s)return{data:null,error:s};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:n}=Le(r.access_token);let o=null;n.aal&&(o=n.aal);let a=o;((t=(e=r.user.factors)===null||e===void 0?void 0:e.filter(u=>u.status==="verified"))!==null&&t!==void 0?t:[]).length>0&&(a="aal2");const c=n.amr||[];return{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:c},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?{data:null,error:s}:r?await m(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):{data:null,error:new U}})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return{data:null,error:n};if(!s)return{data:null,error:new U};const o=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&C()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(b(r))return{data:null,error:r};throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return{data:null,error:n};if(!s)return{data:null,error:new U};const o=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&C()&&!t?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(r){if(b(r))return{data:null,error:r};throw r}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(a=>a.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(a=>a.kid===e),r&&this.jwks_cached_at+Cs>s)return r;const{data:n,error:o}=await m(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!n.keys||n.keys.length===0||(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(a=>a.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){const{data:f,error:w}
40=await this.getSession();if(w||!f.session)return{data:null,error:w};r=f.session.access_token}const{header:s,payload:n,signature:o,raw:{header:a,payload:l}}=Le(r);t?.allowExpired||Zs(n.exp);const c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:n,header:s,signature:o},error:null}}const u=ei(s.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,qs(`${a}.${l}`)))throw new Qe("Invalid JWT signature");return{data:{claims:n,header:s,signature:o},error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}}}ge.nextInstanceID=0;const Ii=ge;class $i extends Ii{constructor(e){super(e)}}class xi{constructor(e,t,r){var s,n,o;this.supabaseUrl=e,this.supabaseKey=t;const a=Ts(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const l=`sb-${a.hostname.split(".")[0]}-auth-token`,c={db:_s,realtime:bs,auth:Object.assign(Object.assign({},ys),{storageKey:l}),global:vs},u=Os(r??{},c);this.storageKey=(s=u.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=u.global.headers)!==null&&n!==void 0?n:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=ks(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 Ar(new URL("rest/v1",a).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this.storage=new gs(this.storageUrl.href,this.headers,this.fetch,r?.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new yr(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();const{data:r}=await this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:o,flowType:a,lock:l,debug:c},u,d){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new $i({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),u),storageKey:o,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:l,debug:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Vr(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Di=(i,e,t)=>new xi(i,e,t);function Ui(){if(typeof window<"u"||typeof process>"u")return!1;const i=process.version;if(i==null)return!1;const e=i.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}Ui()&&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
40ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");export{ne as _,Di as c};

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.