import{b as Rt,g as xt}from"./react-vendor-CqRd3GwO.js";import{_ as ue}from"./query-vendor-BLVqILA6.js";const It=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>ue(async()=>{const{default:s}=await Promise.resolve().then(()=>ne);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};class qe extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class Ut extends qe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class He extends qe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class ze extends qe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Pe;(function(n){n.Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2"})(Pe||(Pe={}));var Lt=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};class Dt{constructor(e,{headers:t={},customFetch:s,region:r=Pe.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=It(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Lt(this,void 0,void 0,function*(){try{const{headers:r,method:i,body:o}=t;let a={},{region:l}=t;l||(l=this.region);const c=new URL(`${this.url}/${e}`);l&&l!=="any"&&(a["x-region"]=l,c.searchParams.set("forceFunctionRegion",l));let h;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));const u=yield this.fetch(c.toString(),{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:h}).catch(v=>{throw new Ut(v)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new He(u);if(!u.ok)throw new ze(u);let f=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield u.json():f==="application/octet-stream"?g=yield u.blob():f==="text/event-stream"?g=u:f==="multipart/form-data"?g=yield u.formData():g=yield u.text(),{data:g,error:null,response:u}}catch(r){return{data:null,error:r,response:r instanceof ze||r instanceof He?r.context:void 0}}})}}var O={},z={},J={},G={},V={},Q={},Nt=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ie=Nt();const Bt=ie.fetch,gt=ie.fetch.bind(ie),pt=ie.Headers,qt=ie.Request,Mt=ie.Response,ne=Object.freeze(Object.defineProperty({__proto__:null,Headers:pt,Request:qt,Response:Mt,default:gt,fetch:Bt},Symbol.toStringTag,{value:"Module"})),Ft=Rt(ne);var fe={},Je;function _t(){if(Je)return fe;Je=1,Object.defineProperty(fe,"__esModule",{value:!0});class n extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}return fe.default=n,fe}var Ge;function vt(){if(Ge)return Q;Ge=1;var n=Q&&Q.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Q,"__esModule",{value:!0});const e=n(Ft),t=n(_t());class s{constructor(i){var o,a;this.shouldThrowOnError=!1,this.method=i.method,this.url=i.url,this.headers=new Headers(i.headers),this.schema=i.schema,this.body=i.body,this.shouldThrowOnError=(o=i.shouldThrowOnError)!==null&&o!==void 0?o:!1,this.signal=i.signal,this.isMaybeSingle=(a=i.isMaybeSingle)!==null&&a!==void 0?a:!1,i.fetch?this.fetch=i.fetch:typeof fetch>"u"?this.fetch=e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(i,o){return this.headers=new Headers(this.headers),this.headers.set(i,o),this}then(i,o){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const a=this.fetch;let l=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async c=>{var h,u,d,f;let g=null,v=null,p=null,S=c.status,T=c.statusText;if(c.ok){if(this.method!=="HEAD"){const m=await c.text();m===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((h=this.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?v=m:v=JSON.parse(m))}const b=(u=this.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),A=(d=c.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");b&&A&&A.length>1&&(p=parseInt(A[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(v)&&(v.length>1?(g={code:"PGRST116",details:`Results contain ${v.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},v=null,p=null,S=406,T="Not Acceptable"):v.length===1?v=v[0]:v=null)}else{const b=await c.text();try{g=JSON.parse(b),Array.isArray(g)&&c.status===404&&(v=[],g=null,S=200,T="OK")}catch{c.status===404&&b===""?(S=204,T="No Content"):g={message:b}}if(g&&this.isMaybeSingle&&(!((f=g?.details)===null||f===void 0)&&f.includes("0 rows"))&&(g=null,S=200,T="OK"),g&&this.shouldThrowOnError)throw new t.default(g)}return{error:g,data:v,count:p,status:S,statusText:T}});return this.shouldThrowOnError||(l=l.catch(c=>{var h,u,d;return{error:{message:`${(h=c?.name)!==null&&h!==void 0?h:"FetchError"}: ${c?.message}`,details:`${(u=c?.stack)!==null&&u!==void 0?u:""}`,hint:"",code:`${(d=c?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),l.then(i,o)}returns(){return this}overrideTypes(){return this}}return Q.default=s,Q}var Ve;function wt(){if(Ve)return V;Ve=1;var n=V&&V.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(V,"__esModule",{value:!0});const e=n(vt());class t extends e.default{select(r){let i=!1;const o=(r??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:i=!0,nullsFirst:o,foreignTable:a,referencedTable:l=a}={}){const c=l?`${l}.order`:"order",h=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${h?`${h},`:""}${r}.${i?"asc":"desc"}${o===void 0?"":o?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:i,referencedTable:o=i}={}){const a=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(a,`${r}`),this}range(r,i,{foreignTable:o,referencedTable:a=o}={}){const l=typeof a>"u"?"offset":`${a}.offset`,c=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${r}`),this.url.searchParams.set(c,`${i-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:r=!1,verbose:i=!1,settings:o=!1,buffers:a=!1,wal:l=!1,format:c="text"}={}){var h;const u=[r?"analyze":null,i?"verbose":null,o?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),d=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${c}; for="${d}"; options=${u};`),c==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}}return V.default=t,V}var Qe;function Me(){if(Qe)return G;Qe=1;var n=G&&G.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(G,"__esModule",{value:!0});const e=n(wt());class t extends e.default{eq(r,i){return this.url.searchParams.append(r,`eq.${i}`),this}neq(r,i){return this.url.searchParams.append(r,`neq.${i}`),this}gt(r,i){return this.url.searchParams.append(r,`gt.${i}`),this}gte(r,i){return this.url.searchParams.append(r,`gte.${i}`),this}lt(r,i){return this.url.searchParams.append(r,`lt.${i}`),this}lte(r,i){return this.url.searchParams.append(r,`lte.${i}`),this}like(r,i){return this.url.searchParams.append(r,`like.${i}`),this}likeAllOf(r,i){return this.url.searchParams.append(r,`like(all).{${i.join(",")}}`),this}likeAnyOf(r,i){return this.url.searchParams.append(r,`like(any).{${i.join(",")}}`),this}ilike(r,i){return this.url.searchParams.append(r,`ilike.${i}`),this}ilikeAllOf(r,i){return this.url.searchParams.append(r,`ilike(all).{${i.join(",")}}`),this}ilikeAnyOf(r,i){return this.url.searchParams.append(r,`ilike(any).{${i.join(",")}}`),this}is(r,i){return this.url.searchParams.append(r,`is.${i}`),this}in(r,i){const o=Array.from(new Set(i)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(r,`in.(${o})`),this}contains(r,i){return typeof i=="string"?this.url.searchParams.append(r,`cs.${i}`):Array.isArray(i)?this.url.searchParams.append(r,`cs.{${i.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(i)}`),this}containedBy(r,i){return typeof i=="string"?this.url.searchParams.append(r,`cd.${i}`):Array.isArray(i)?this.url.searchParams.append(r,`cd.{${i.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(i)}`),this}rangeGt(r,i){return this.url.searchParams.append(r,`sr.${i}`),this}rangeGte(r,i){return this.url.searchParams.append(r,`nxl.${i}`),this}rangeLt(r,i){return this.url.searchParams.append(r,`sl.${i}`),this}rangeLte(r,i){return this.url.searchParams.append(r,`nxr.${i}`),this}rangeAdjacent(r,i){return this.url.searchParams.append(r,`adj.${i}`),this}overlaps(r,i){return typeof i=="string"?this.url.searchParams.append(r,`ov.${i}`):this.url.searchParams.append(r,`ov.{${i.join(",")}}`),this}textSearch(r,i,{config:o,type:a}={}){let l="";a==="plain"?l="pl":a==="phrase"?l="ph":a==="websearch"&&(l="w");const c=o===void 0?"":`(${o})`;return this.url.searchParams.append(r,`${l}fts${c}.${i}`),this}match(r){return Object.entries(r).forEach(([i,o])=>{this.url.searchParams.append(i,`eq.${o}`)}),this}not(r,i,o){return this.url.searchParams.append(r,`not.${i}.${o}`),this}or(r,{foreignTable:i,referencedTable:o=i}={}){const a=o?`${o}.or`:"or";return this.url.searchParams.append(a,`(${r})`),this}filter(r,i,o){return this.url.searchParams.append(r,`${i}.${o}`),this}}return G.default=t,G}var Ye;function yt(){if(Ye)return J;Ye=1;var n=J&&J.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(J,"__esModule",{value:!0});const e=n(Me());class t{constructor(r,{headers:i={},schema:o,fetch:a}){this.url=r,this.headers=new Headers(i),this.schema=o,this.fetch=a}select(r,{head:i=!1,count:o}={}){const a=i?"HEAD":"GET";let l=!1;const c=(r??"*").split("").map(h=>/\s/.test(h)&&!l?"":(h==='"'&&(l=!l),h)).join("");return this.url.searchParams.set("select",c),o&&this.headers.append("Prefer",`count=${o}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(r,{count:i,defaultToNull:o=!0}={}){var a;const l="POST";if(i&&this.headers.append("Prefer",`count=${i}`),o||this.headers.append("Prefer","missing=default"),Array.isArray(r)){const c=r.reduce((h,u)=>h.concat(Object.keys(u)),[]);if(c.length>0){const h=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",h.join(","))}}return new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}upsert(r,{onConflict:i,ignoreDuplicates:o=!1,count:a,defaultToNull:l=!0}={}){var c;const h="POST";if(this.headers.append("Prefer",`resolution=${o?"ignore":"merge"}-duplicates`),i!==void 0&&this.url.searchParams.set("on_conflict",i),a&&this.headers.append("Prefer",`count=${a}`),l||this.headers.append("Prefer","missing=default"),Array.isArray(r)){const u=r.reduce((d,f)=>d.concat(Object.keys(f)),[]);if(u.length>0){const d=[...new Set(u)].map(f=>`"${f}"`);this.url.searchParams.set("columns",d.join(","))}}return new e.default({method:h,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}update(r,{count:i}={}){var o;const a="PATCH";return i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}delete({count:r}={}){var i;const o="DELETE";return r&&this.headers.append("Prefer",`count=${r}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}}return J.default=t,J}var Xe;function Wt(){if(Xe)return z;Xe=1;var n=z&&z.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(z,"__esModule",{value:!0});const e=n(yt()),t=n(Me());class s{constructor(i,{headers:o={},schema:a,fetch:l}={}){this.url=i,this.headers=new Headers(o),this.schemaName=a,this.fetch=l}from(i){const o=new URL(`${this.url}/${i}`);return new e.default(o,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(i){return new s(this.url,{headers:this.headers,schema:i,fetch:this.fetch})}rpc(i,o={},{head:a=!1,get:l=!1,count:c}={}){var h;let u;const d=new URL(`${this.url}/rpc/${i}`);let f;a||l?(u=a?"HEAD":"GET",Object.entries(o).filter(([v,p])=>p!==void 0).map(([v,p])=>[v,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([v,p])=>{d.searchParams.append(v,p)})):(u="POST",f=o);const g=new Headers(this.headers);return c&&g.set("Prefer",`count=${c}`),new t.default({method:u,url:d,headers:g,schema:this.schemaName,body:f,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch})}}return z.default=s,z}var Ze;function Kt(){if(Ze)return O;Ze=1;var n=O&&O.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(O,"__esModule",{value:!0}),O.PostgrestError=O.PostgrestBuilder=O.PostgrestTransformBuilder=O.PostgrestFilterBuilder=O.PostgrestQueryBuilder=O.PostgrestClient=void 0;const e=n(Wt());O.PostgrestClient=e.default;const t=n(yt());O.PostgrestQueryBuilder=t.default;const s=n(Me());O.PostgrestFilterBuilder=s.default;const r=n(wt());O.PostgrestTransformBuilder=r.default;const i=n(vt());O.PostgrestBuilder=i.default;const o=n(_t());return O.PostgrestError=o.default,O.default={PostgrestClient:e.default,PostgrestQueryBuilder:t.default,PostgrestFilterBuilder:s.default,PostgrestTransformBuilder:r.default,PostgrestBuilder:i.default,PostgrestError:o.default},O}var Ht=Kt();const zt=xt(Ht),{PostgrestClient:Jt,PostgrestQueryBuilder:Lr,PostgrestFilterBuilder:Dr,PostgrestTransformBuilder:Nr,PostgrestBuilder:Br,PostgrestError:qr}=zt;class Gt{static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"){const t=process.versions;if(t&&t.node){const s=t.node,r=parseInt(s.replace(/^v/,"").split(".")[0]);return r>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=` Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const s=this.getWebSocketConstructor();return new s(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Vt="2.15.5",Qt=`realtime-js/${Vt}`,Yt="1.0.0",$e=1e4,Xt=1e3,Zt=100;var ae;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(ae||(ae={}));var E;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(E||(E={}));var R;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(R||(R={}));var Ce;(function(n){n.websocket="websocket"})(Ce||(Ce={}));var W;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(W||(W={}));class es{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),i=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=s.decode(e.slice(o,o+r));o=o+r;const l=s.decode(e.slice(o,o+i));o=o+i;const c=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}}class bt{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var k;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(k||(k={}));const et=(n,e,t={})=>{var s;const r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((i,o)=>(i[o]=ts(o,n,e,r),i),{})},ts=(n,e,t,s)=>{const r=e.find(a=>a.name===n),i=r?.type,o=t[n];return i&&!s.includes(i)?mt(i,o):Re(o)},mt=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return ns(e,t)}switch(n){case k.bool:return ss(e);case k.float4:case k.float8:case k.int2:case k.int4:case k.int8:case k.numeric:case k.oid:return rs(e);case k.json:case k.jsonb:return is(e);case k.timestamp:return os(e);case k.abstime:case k.date:case k.daterange:case k.int4range:case k.int8range:case k.money:case k.reltime:case k.text:case k.time:case k.timestamptz:case k.timetz:case k.tsrange:case k.tstzrange:return Re(e);default:return Re(e)}},Re=n=>n,ss=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},rs=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},is=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n},ns=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,s=n[t];if(n[0]==="{"&&s==="}"){let i;const o=n.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>mt(e,a))}return n},os=n=>typeof n=="string"?n.replace(" ","T"):n,kt=n=>{let e=n;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class me{constructor(e,t,s={},r=$e){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var tt;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(tt||(tt={}));class le{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=le.syncState(this.state,r,i,o),this.pendingDiffs.forEach(l=>{this.state=le.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=le.syncDiff(this.state,r,i,o),a())}),this.onJoin((r,i,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:i,newPresences:o})}),this.onLeave((r,i,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const i=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(i,(c,h)=>{o[c]||(l[c]=h)}),this.map(o,(c,h)=>{const u=i[c];if(u){const d=h.map(p=>p.presence_ref),f=u.map(p=>p.presence_ref),g=h.filter(p=>f.indexOf(p.presence_ref)<0),v=u.filter(p=>d.indexOf(p.presence_ref)<0);g.length>0&&(a[c]=g),v.length>0&&(l[c]=v)}else a[c]=h}),this.syncDiff(i,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){const{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(i,(a,l)=>{var c;const h=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),h.length>0){const u=e[a].map(f=>f.presence_ref),d=h.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,h,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const h=l.map(u=>u.presence_ref);c=c.filter(u=>h.indexOf(u.presence_ref)<0),e[a]=c,r(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const r=e[s];return"metas"in r?t[s]=r.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[s]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var st;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(st||(st={}));var ce;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(ce||(ce={}));var U;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(U||(U={}));class Fe{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=E.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 me(this,R.join,this.params,this.timeout),this.rejoinTimer=new bt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=E.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=E.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=E.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=E.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=E.errored,this.rejoinTimer.scheduleTimeout())}),this._on(R.reply,{},(r,i)=>{this._trigger(this._replyEventName(i),r)}),this.presence=new le(this),this.broadcastEndpointURL=kt(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r,i;if(this.socket.isConnected()||this.socket.connect(),this.state==E.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,c=(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&r!==void 0?r:[],h=!!this.bindings[ce.PRESENCE]&&this.bindings[ce.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,u={},d={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:h}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(f=>e?.(U.CHANNEL_ERROR,f)),this._onClose(()=>e?.(U.CLOSED)),this.updateJoinPayload(Object.assign({config:d},u)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:f})=>{var g;if(this.socket.setAuth(),f===void 0){e?.(U.SUBSCRIBED);return}else{const v=this.bindings.postgres_changes,p=(g=v?.length)!==null&&g!==void 0?g:0,S=[];for(let T=0;T
{this.state=E.errored,e?.(U.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(U.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===E.joined&&e===ce.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){const{event:i,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=c.body)===null||r===void 0?void 0:r.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=E.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(R.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(r=>{s=new me(this,R.leave,{},e),s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=E.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const r=new AbortController,i=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new me(this,e,t,s);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>Zt){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,i;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:h}=R;if(s&&[a,l,c,h].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(f=>{var g,v,p;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((p=(v=f.filter)===null||v===void 0?void 0:v.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var g,v,p,S,T,_;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){const b=f.id,A=(g=f.filter)===null||g===void 0?void 0:g.event;return b&&((v=t.ids)===null||v===void 0?void 0:v.includes(b))&&(A==="*"||A?.toLocaleLowerCase()===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{const b=(T=(S=f?.filter)===null||S===void 0?void 0:S.event)===null||T===void 0?void 0:T.toLocaleLowerCase();return b==="*"||b===((_=t?.event)===null||_===void 0?void 0:_.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){const g=d.data,{schema:v,table:p,commit_timestamp:S,type:T,errors:_}=g;d=Object.assign(Object.assign({},{schema:v,table:p,commit_timestamp:S,eventType:T,new:{},old:{},errors:_}),this._getPayloadRecords(g))}f.callback(d,s)})}_isClosed(){return this.state===E.closed}_isJoined(){return this.state===E.joined}_isJoining(){return this.state===E.joining}_isLeaving(){return this.state===E.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(r=>{var i;return!(((i=r.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&Fe.isEqual(r.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(R.close,{},e)}_onError(e){this._on(R.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=E.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=et(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=et(e.columns,e.old_record)),t}}const ke=()=>{},ge={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},as=[1e3,2e3,5e3,1e4],ls=1e4,cs=`
addEventListener("message", (e) => {
if (e.data.event === "start") {
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
}
});`;class hs{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=$e,this.transport=null,this.heartbeatIntervalMs=ge.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ke,this.ref=0,this.reconnectTimer=null,this.logger=ke,this.conn=null,this.sendBuffer=[],this.serializer=new es,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=r=>{let i;return r?i=r:typeof fetch>"u"?i=(...o)=>ue(async()=>{const{default:a}=await Promise.resolve().then(()=>ne);return{default:a}},void 0).then(({default:a})=>a(...o)).catch(a=>{throw new Error(`Failed to load @supabase/node-fetch: ${a.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):i=fetch,(...o)=>i(...o)},!(!((s=t?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Ce.websocket}`,this.httpEndpoint=kt(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Gt.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}
To use Realtime in Node.js, you need to provide a WebSocket implementation:
Option 1: Use Node.js 22+ which has native WebSocket support
Option 2: Install and provide the "ws" package:
npm install ws
import ws from "ws"
const client = new RealtimeClient(url, {
...options,
transport: ws
})`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Yt}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},e?this.conn.close(e,t??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case ae.connecting:return W.Connecting;case ae.open:return W.Open;case ae.closing:return W.Closing;default:return W.Closed}}isConnected(){return this.connectionState()===W.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const s=`realtime:${e}`,r=this.getChannels().find(i=>i.topic===s);if(r)return r;{const i=new Fe(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){const{topic:t,event:s,payload:r,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${i})`,r),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){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(Xt,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},ge.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>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:s,event:r,payload:i,ref:o}=t,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${s} ${r} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(s)).forEach(c=>c._trigger(r,i,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(R.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_workerObjectUrl(e){let t;if(e)t=e;else{const s=new Blob([cs],{type:"application/javascript"});t=URL.createObjectURL(s)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;e?t=e:this.accessToken?t=await this.accessToken():t=this.accessTokenValue,this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(s=>{const r={access_token:t,version:Qt};t&&s.updateJoinPayload(r),s.joinedOnce&&s._isJoined()&&s._push(R.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t)}catch(r){this.log("error",`error in ${e} callback`,r)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new bt(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},ge.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,r,i,o,a,l,c,h;if(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e?.timeout)!==null&&s!==void 0?s:$e,this.heartbeatIntervalMs=(r=e?.heartbeatIntervalMs)!==null&&r!==void 0?r:ge.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:ke,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=e?.reconnectAfterMs)!==null&&l!==void 0?l:(u=>as[u-1]||ls),this.encode=(c=e?.encode)!==null&&c!==void 0?c:((u,d)=>d(JSON.stringify(u))),this.decode=(h=e?.decode)!==null&&h!==void 0?h:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}}class We extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function j(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class us extends We{constructor(e,t,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class xe extends We{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var ds=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const St=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>ue(async()=>{const{default:s}=await Promise.resolve().then(()=>ne);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},fs=()=>ds(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ue(()=>Promise.resolve().then(()=>ne),void 0)).Response:Response}),Ie=n=>{if(Array.isArray(n))return n.map(t=>Ie(t));if(typeof n=="function"||n!==Object(n))return n;const e={};return Object.entries(n).forEach(([t,s])=>{const r=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[r]=Ie(s)}),e},gs=n=>{if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)};var K=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const Se=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),ps=(n,e,t)=>K(void 0,void 0,void 0,function*(){const s=yield fs();n instanceof s&&!t?.noResolveJson?n.json().then(r=>{const i=n.status||500,o=r?.statusCode||i+"";e(new us(Se(r),i,o))}).catch(r=>{e(new xe(Se(r),r))}):e(new xe(Se(n),n))}),_s=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"||!s?r:(gs(s)?(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s)):r.body=s,e?.duplex&&(r.duplex=e.duplex),Object.assign(Object.assign({},r),t))};function de(n,e,t,s,r,i){return K(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,_s(e,s,r,i)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>ps(l,a,s))})})}function we(n,e,t,s){return K(this,void 0,void 0,function*(){return de(n,"GET",e,t,s)})}function x(n,e,t,s,r){return K(this,void 0,void 0,function*(){return de(n,"POST",e,s,r,t)})}function Ue(n,e,t,s,r){return K(this,void 0,void 0,function*(){return de(n,"PUT",e,s,r,t)})}function vs(n,e,t,s){return K(this,void 0,void 0,function*(){return de(n,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function Tt(n,e,t,s,r){return K(this,void 0,void 0,function*(){return de(n,"DELETE",e,s,r,t)})}var $=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const ws={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},rt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class ys{constructor(e,t={},s,r){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=s,this.fetch=St(r)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,r){return $(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},rt),r);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&s instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l))):(i=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),r?.headers&&(a=Object.assign(Object.assign({},a),r.headers));const c=this._removeEmptyFolders(t),h=this._getFinalPath(c),u=yield(e=="PUT"?Ue:x)(this.fetch,`${this.url}/object/${h}`,i,Object.assign({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(j(i))return{data:null,error:i};throw i}})}upload(e,t,s){return $(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return $(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:rt.upsert},r),h=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",c.cacheControl)):(l=s,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType);const u=yield Ue(this.fetch,a.toString(),l,{headers:h});return{data:{path:i,fullPath:u.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(j(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return $(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");const i=yield x(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new We("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(j(s))return{data:null,error:s};throw s}})}update(e,t,s){return $(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return $(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(j(r))return{data:null,error:r};throw r}})}copy(e,t,s){return $(this,void 0,void 0,function*(){try{return{data:{path:(yield x(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(j(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return $(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield x(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers});const o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(j(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return $(this,void 0,void 0,function*(){try{const r=yield x(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(j(r))return{data:null,error:r};throw r}})}download(e,t){return $(this,void 0,void 0,function*(){const r=typeof t?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(t?.transform||{}),o=i?`?${i}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield we(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(j(a))return{data:null,error:a};throw a}})}info(e){return $(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield we(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Ie(s),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(j(s))return{data:null,error:s};throw s}})}exists(e){return $(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield vs(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(j(s)&&s instanceof xe){const r=s.originalError;if([400,404].includes(r?.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],i=t?.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&r.push(i);const a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&r.push(l);let c=r.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${c}`)}}}remove(e){return $(this,void 0,void 0,function*(){try{return{data:yield Tt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(j(t))return{data:null,error:t};throw t}})}list(e,t,s){return $(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},ws),t),{prefix:e||""});return{data:yield x(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(j(r))return{data:null,error:r};throw r}})}listV2(e,t){return $(this,void 0,void 0,function*(){try{const s=Object.assign({},e);return{data:yield x(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(j(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const bs="2.12.1",ms={"X-Client-Info":`storage-js/${bs}`};var Y=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};class ks{constructor(e,t={},s,r){this.shouldThrowOnError=!1;const i=new URL(e);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),this.url=i.href,this.headers=Object.assign(Object.assign({},ms),t),this.fetch=St(s)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return Y(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(j(e))return{data:null,error:e};throw e}})}getBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(j(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Y(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(j(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Y(this,void 0,void 0,function*(){try{return{data:yield Ue(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(j(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(j(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield Tt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(j(t))return{data:null,error:t};throw t}})}}class Ss extends ks{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new ys(this.url,this.headers,e,this.fetch)}}const Ts="2.57.4";let oe="";typeof Deno<"u"?oe="deno":typeof document<"u"?oe="web":typeof navigator<"u"&&navigator.product==="ReactNative"?oe="react-native":oe="node";const Es={"X-Client-Info":`supabase-js-${oe}/${Ts}`},js={headers:Es},Os={schema:"public"},As={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ps={};var $s=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const Cs=n=>{let e;return n?e=n:typeof fetch>"u"?e=gt:e=fetch,(...t)=>e(...t)},Rs=()=>typeof Headers>"u"?pt:Headers,xs=(n,e,t)=>{const s=Cs(t),r=Rs();return(i,o)=>$s(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:n;let c=new r(o?.headers);return c.has("apikey")||c.set("apikey",n),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(i,Object.assign(Object.assign({},o),{headers:c}))})};var Is=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};function Us(n){return n.endsWith("/")?n:n+"/"}function Ls(n,e){var t,s;const{db:r,auth:i,realtime:o,global:a}=n,{db:l,auth:c,realtime:h,global:u}=e,d={db:Object.assign(Object.assign({},l),r),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},h),o),storage:{},global:Object.assign(Object.assign(Object.assign({},u),a),{headers:Object.assign(Object.assign({},(t=u?.headers)!==null&&t!==void 0?t:{}),(s=a?.headers)!==null&&s!==void 0?s:{})}),accessToken:()=>Is(this,void 0,void 0,function*(){return""})};return n.accessToken?d.accessToken=n.accessToken:delete d.accessToken,d}function Ds(n){const e=n?.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(Us(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const Et="2.71.1",se=30*1e3,Le=3,Te=Le*se,Ns="http://localhost:9999",Bs="supabase.auth.token",qs={"X-Client-Info":`gotrue-js/${Et}`},De="X-Supabase-Api-Version",jt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ms=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Fs=600*1e3;class Ke extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function w(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class Ws extends Ke{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function Ks(n){return w(n)&&n.name==="AuthApiError"}class Ot extends Ke{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class B extends Ke{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class D extends B{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Hs(n){return w(n)&&n.name==="AuthSessionMissingError"}class pe extends B{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class _e extends B{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ve extends B{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function zs(n){return w(n)&&n.name==="AuthImplicitGrantRedirectError"}class it extends B{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ne extends B{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Ee(n){return w(n)&&n.name==="AuthRetryableFetchError"}class nt extends B{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Be extends B{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ot=`
\r=`.split(""),Js=(()=>{const n=new Array(128);for(let e=0;e