PageSourceSearch

https://axentiqcapital.com/chunk-HXNCLXEW.js

js axentiqcapital.com collected 2026-10-09 22:57:57 UTC 175,356 bytes, 43 lines download raw bytes

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

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.