26 lines
118 KiB
JavaScript
26 lines
118 KiB
JavaScript
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<p;T++){const _=v[T],{filter:{event:b,schema:A,table:m,filter:P}}=_,H=f&&f[T];if(H&&H.event===b&&H.schema===A&&H.table===m&&H.filter===P)S.push(Object.assign(Object.assign({},_),{id:H.id}));else{this.unsubscribe(),this.state=E.errored,e?.(U.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=S,e&&e(U.SUBSCRIBED);return}}).receive("error",f=>{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<n.length;e+=1)n[e]=-1;for(let e=0;e<ot.length;e+=1)n[ot[e].charCodeAt(0)]=-2;for(let e=0;e<ye.length;e+=1)n[ye[e].charCodeAt(0)]=e;return n})();function at(n,e,t){if(n!==null)for(e.queue=e.queue<<8|n,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(ye[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(ye[s]),e.queuedBits-=6}}function At(n,e,t){const s=Js[n];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function lt(n){const e=[],t=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},r={queue:0,queuedBits:0},i=o=>{Qs(o,s,t)};for(let o=0;o<n.length;o+=1)At(n.charCodeAt(o),r,i);return e.join("")}function Gs(n,e){if(n<=127){e(n);return}else if(n<=2047){e(192|n>>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function Vs(n,e){for(let t=0;t<n.length;t+=1){let s=n.charCodeAt(t);if(s>55295&&s<=56319){const r=(s-55296)*1024&65535;s=(n.charCodeAt(t+1)-56320&65535|r)+65536,t+=1}Gs(s,e)}}function Qs(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let s=1;s<6;s+=1)if((n>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function Ys(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};for(let r=0;r<n.length;r+=1)At(n.charCodeAt(r),t,s);return new Uint8Array(e)}function Xs(n){const e=[];return Vs(n,t=>e.push(t)),new Uint8Array(e)}function Zs(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};return n.forEach(r=>at(r,t,s)),at(null,t,s),e.join("")}function er(n){return Math.round(Date.now()/1e3)+n}function tr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n=="x"?e:e&3|8).toString(16)})}const C=()=>typeof window<"u"&&typeof document<"u",q={tested:!1,writable:!1},Pt=()=>{if(!C())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(q.tested)return q.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),q.tested=!0,q.writable=!0}catch{q.tested=!0,q.writable=!1}return q.writable};function sr(n){const e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,i)=>{e[i]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}const $t=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)},rr=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",re=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},M=async(n,e)=>{const t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},L=async(n,e)=>{await n.removeItem(e)};class be{constructor(){this.promise=new be.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}be.promiseConstructor=Promise;function je(n){const e=n.split(".");if(e.length!==3)throw new Be("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Ms.test(e[s]))throw new Be("JWT not in base64url format");return{header:JSON.parse(lt(e[0])),payload:JSON.parse(lt(e[1])),signature:Ys(e[2]),raw:{header:e[0],payload:e[1]}}}async function ir(n){return await new Promise(e=>{setTimeout(()=>e(null),n)})}function nr(n,e){return new Promise((s,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await n(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){r(o);return}}})()})}function or(n){return("0"+n.toString(16)).substr(-2)}function ar(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let r="";for(let i=0;i<56;i++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,or).join("")}async function lr(n){const t=new TextEncoder().encode(n),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(i=>String.fromCharCode(i)).join("")}async function cr(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return n;const t=await lr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function X(n,e,t=!1){const s=ar();let r=s;t&&(r+="/PASSWORD_RECOVERY"),await re(n,`${e}-code-verifier`,r);const i=await cr(s);return[i,s===i?"plain":"s256"]}const hr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ur(n){const e=n.headers.get(De);if(!e||!e.match(hr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function dr(n){if(!n)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function fr(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const gr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Z(n){if(!gr.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Oe(){const n={};return new Proxy(n,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const s=t.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function ct(n){return JSON.parse(JSON.stringify(n))}var pr=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};const F=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),_r=[502,503,504];async function ht(n){var e;if(!rr(n))throw new Ne(F(n),0);if(_r.includes(n.status))throw new Ne(F(n),n.status);let t;try{t=await n.json()}catch(i){throw new Ot(F(i),i)}let s;const r=ur(n);if(r&&r.getTime()>=jt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new nt(F(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new D}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new nt(F(t),n.status,t.weak_password.reasons);throw new Ws(F(t),n.status||500,s)}const vr=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function y(n,e,t,s){var r;const i=Object.assign({},s?.headers);i[De]||(i[De]=jt["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await wr(n,e,t+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function wr(n,e,t,s,r,i){const o=vr(e,s,r,i);let a;try{a=await n(t,Object.assign({},o))}catch(l){throw new Ne(F(l),0)}if(a.ok||await ht(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await ht(l)}}function I(n){var e;let t=null;kr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=er(n.expires_in)));const s=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:s},error:null}}function ut(n){const e=I(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=n.weak_password),e}function N(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function yr(n){return{data:n,error:null}}function br(n){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:i}=n,o=pr(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function mr(n){return n}function kr(n){return n.access_token&&n.refresh_token&&n.expires_in}const Ae=["global","local","others"];var Sr=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};class Tr{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=$t(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t=Ae[0]){if(Ae.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ae.join(", ")}`);try{return await y(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(w(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await y(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:N})}catch(s){if(w(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=Sr(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await y(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:br,redirectTo:t?.redirectTo})}catch(t){if(w(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await y(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:N})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,i,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},h=await y(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&i!==void 0?i:""},xform:mr});if(h.error)throw h.error;const u=await h.json(),d=(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=>{const v=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(g.split(";")[1].split("=")[1]);c[`${p}Page`]=v}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(w(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){Z(e);try{return await y(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:N})}catch(t){if(w(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Z(e);try{return await y(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:N})}catch(s){if(w(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){Z(e);try{return await y(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:N})}catch(s){if(w(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Z(e.userId);try{const{data:t,error:s}=await y(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(w(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Z(e.userId),Z(e.id);try{return{data:await y(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}}function dt(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}function Er(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const ee={debug:!!(globalThis&&Pt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Ct extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class jr extends Ct{}async function Or(n,e,t){ee.debug;const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),ee.debug},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(n,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){ee.debug;try{return await t()}finally{ee.debug}}else{if(e===0)throw ee.debug,new jr(`Acquiring an exclusive Navigator LockManager lock "${n}" immediately failed`);if(ee.debug)try{const i=await globalThis.navigator.locks.query()}catch{}return await t()}}))}Er();const Ar={url:Ns,storageKey:Bs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:qs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function ft(n,e,t){return await t()}const te={};class he{constructor(e){var t,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=he.nextInstanceID,he.nextInstanceID+=1,this.instanceID>0&&C();const r=Object.assign(Object.assign({},Ar),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new Tr({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=$t(r.fetch),this.lock=r.lock||ft,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:C()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Or:this.lock=ft,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?(r.storage?this.storage=r.storage:Pt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=dt(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=dt(this.memoryStorage)),C()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch{}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}get jwks(){var e,t;return(t=(e=te[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){te[this.storageKey]=Object.assign(Object.assign({},te[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=te[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){te[this.storageKey]=Object.assign(Object.assign({},te[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Et}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const t=sr(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),C()&&this.detectSessionInUrl&&s!=="none"){const{data:r,error:i}=await this._getSessionFromURL(t,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),zs(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:a}=r;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return w(t)?{error:t}:{error:new Ot("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:I}),{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(w(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,s,r;try{let i;if("email"in e){const{email:h,password:u,options:d}=e;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await X(this.storage,this.storageKey)),i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:h,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:g},xform:I})}else if("phone"in e){const{phone:h,password:u,options:d}=e;i=await y(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:I})}else throw new _e("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(w(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:i,password:o,options:a}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ut})}else if("phone"in e){const{phone:i,password:o,options:a}=e;t=await y(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ut})}else throw new _e("You must provide either an email or phone number and a password");const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new pe}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(w(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;if(t==="solana")return await this.signInWithSolana(e);throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}async signInWithSolana(e){var t,s,r,i,o,a,l,c,h,u,d,f;let g,v;if("message"in e)g=e.message,v=e.signature;else{const{chain:p,wallet:S,statement:T,options:_}=e;let b;if(C())if(typeof S=="object")b=S;else{const m=window;if("solana"in m&&typeof m.solana=="object"&&("signIn"in m.solana&&typeof m.solana.signIn=="function"||"signMessage"in m.solana&&typeof m.solana.signMessage=="function"))b=m.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof S!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=S}const A=new URL((t=_?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in b&&b.signIn){const m=await b.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),T?{statement:T}:null));let P;if(Array.isArray(m)&&m[0]&&typeof m[0]=="object")P=m[0];else if(m&&typeof m=="object"&&"signedMessage"in m&&"signature"in m)P=m;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)g=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),v=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in b)||typeof b.signMessage!="function"||!("publicKey"in b)||typeof b!="object"||!b.publicKey||!("toBase58"in b.publicKey)||typeof b.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${A.host} wants you to sign in with your Solana account:`,b.publicKey.toBase58(),...T?["",T,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(r=(s=_?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&r!==void 0?r:new Date().toISOString()}`,...!((i=_?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((o=_?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((c=_?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((u=(h=_?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||u===void 0)&&u.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
`);const m=await b.signMessage(new TextEncoder().encode(g),"utf8");if(!m||!(m instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=m}}try{const{data:p,error:S}=await y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:Zs(v)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:I});if(S)throw S;return!p||!p.session||!p.user?{data:{user:null,session:null},error:new pe}:(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session)),{data:Object.assign({},p),error:S})}catch(p){if(w(p))return{data:{user:null,session:null},error:p};throw p}}async _exchangeCodeForSession(e){const t=await M(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/");try{const{data:i,error:o}=await y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:I});if(await L(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new pe}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:r??null}),error:o})}catch(i){if(w(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:i,nonce:o}=e,a=await y(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:I}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new pe}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(w(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,h=null;this.flowType==="pkce"&&([c,h]=await X(this.storage,this.storageKey));const{error:u}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:h}=await y(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:h}}throw new _e("You must provide either an email or phone number.")}catch(a){if(w(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,i;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:I});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(r){if(w(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await X(this.storage,this.storageKey)),await y(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:yr})}catch(i){if(w(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new D;const{error:r}=await y(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(w(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:i}=e,{error:o}=await y(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:s,type:r,options:i}=e,{data:o,error:a}=await y(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new _e("You must provide either an email or phone number and a type")}catch(t){if(w(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await M(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Te:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const o=await M(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=Oe()}if(this.storage.isServer&&e.user){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,h)=>(!o&&c==="user"&&(o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,c,h))})}return{data:{session:e},error:null}}const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:N}):await this._useSession(async t=>{var s,r,i;const{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new D}:await y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0,xform:N})})}catch(t){if(w(t))return Hs(t)&&(await this._removeSession(),await L(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:r,error:i}=s;if(i)throw i;if(!r.session)throw new D;const o=r.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await X(this.storage,this.storageKey));const{data:c,error:h}=await y(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:N});if(h)throw h;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(w(s))return{data:{user:null},error:s};throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new D;const t=Date.now()/1e3;let s=t,r=!0,i=null;const{payload:o}=je(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){const{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(w(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new D;const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(w(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!C())throw new ve("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ve(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new it("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ve("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new it("No code detected.");const{data:T,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;const b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:T.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new ve("No session defined in URL");const h=Math.round(Date.now()/1e3),u=parseInt(a);let d=h+u;l&&(d=parseInt(l)),(d-h)*1e3<=se;const g=d-u;h-g>=120||h-g<0;const{data:v,error:p}=await this._getUser(i);if(p)throw p;const S={provider_token:s,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:o,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:S,redirectType:e.type},error:null}}catch(s){if(w(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await M(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;const{data:r,error:i}=t;if(i)return{error:i};const o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(Ks(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await L(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=tr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{const{data:{session:i},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await X(this.storage,this.storageKey,!0));try{return await y(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(w(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{const{data:s,error:r}=await this._useSession(async i=>{var o,a,l,c,h;const{data:u,error:d}=i;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await y(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(r)throw r;return C()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(w(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;const{data:i,error:o}=t;if(o)throw o;return await y(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await nr(async r=>(r>0&&await ir(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:I})),(r,i)=>{const o=200*Math.pow(2,r);return i&&Ee(i)&&Date.now()+o-s<se})}catch(s){if(this._debug(t,"error",s),w(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),C()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,t;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const r=await M(this.storage,this.storageKey);if(r&&this.userStorage){let o=await M(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:r.user},await re(this.userStorage,this.storageKey+"-user",o)),r.user=(e=o?.user)!==null&&e!==void 0?e:Oe()}else if(r&&!r.user&&!r.user){const o=await M(this.storage,this.storageKey+"-user");o&&o?.user?(r.user=o.user,await L(this.storage,this.storageKey+"-user"),await re(this.storage,this.storageKey,r)):r.user=Oe()}if(this._debug(s,"session from storage",r),!this._isValidSession(r)){this._debug(s,"session is not valid"),r!==null&&await this._removeSession();return}const i=((t=r.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Te;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Te}s`),i){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(Ee(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(r.user&&r.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(r.access_token);!a&&o?.user?(r.user=o.user,await this._saveSession(r),await this._notifyAllSubscribers("SIGNED_IN",r)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(s,"error",r);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new D;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new be;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new D;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const a={session:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(r,"error",i),w(i)){const o={session:null,error:i};return Ee(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1);throw i[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),s=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&t.user&&await re(this.userStorage,this.storageKey+"-user",{user:t.user});const r=Object.assign({},t);delete r.user;const i=ct(r);await re(this.storage,this.storageKey,i)}else{const r=ct(t);await re(this.storage,this.storageKey,r)}}async _removeSession(){this._debug("#_removeSession()"),await L(this.storage,this.storageKey),await L(this.storage,this.storageKey+"-code-verifier"),await L(this.storage,this.storageKey+"-user"),this.userStorage&&await L(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&C()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch{}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),se);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const r=Math.floor((s.expires_at*1e3-e)/se);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${se}ms, refresh threshold is ${Le} ticks`),r<=Le&&await this._callRefreshToken(s.refresh_token)})}catch{}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ct)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!C()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch{}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){const r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,o]=await X(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){const i=new URLSearchParams(s.queryParams);r.push(i.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await y(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;const{data:i,error:o}=t;if(o)return{data:null,error:o};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:l,error:c}=await y(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&(!((r=l?.totp)===null||r===void 0)&&r.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(w(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;if(i)return{data:null,error:i};const{data:o,error:a}=await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(w(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await y(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(w(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const s=e?.factors||[],r=s.filter(o=>o.factor_type==="totp"&&o.status==="verified"),i=s.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:s,totp:r,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:r},error:i}=e;if(i)return{data:null,error:i};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=je(r.access_token);let a=null;o.aal&&(a=o.aal);let l=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");const h=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:h},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(a=>a.kid===e);if(s)return s;const r=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+Fs>r)return s;const{data:i,error:o}=await y(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=r,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,t={}){try{let s=e;if(!s){const{data:f,error:g}=await this.getSession();if(g||!f.session)return{data:null,error:g};s=f.session.access_token}const{header:r,payload:i,signature:o,raw:{header:a,payload:l}}=je(s);t?.allowExpired||dr(i.exp);const c=!r.alg||r.alg.startsWith("HS")||!r.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(r.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:r,signature:o},error:null}}const h=fr(r.alg),u=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,u,o,Xs(`${a}.${l}`)))throw new Be("Invalid JWT signature");return{data:{claims:i,header:r,signature:o},error:null}}catch(s){if(w(s))return{data:null,error:s};throw s}}}he.nextInstanceID=0;const Pr=he;class $r extends Pr{constructor(e){super(e)}}var Cr=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 Rr{constructor(e,t,s){var r,i,o;this.supabaseUrl=e,this.supabaseKey=t;const a=Ds(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const l=`sb-${a.hostname.split(".")[0]}-auth-token`,c={db:Os,realtime:Ps,auth:Object.assign(Object.assign({},As),{storageKey:l}),global:js},h=Ls(s??{},c);this.storageKey=(r=h.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=h.auth)!==null&&o!==void 0?o:{},this.headers,h.global.fetch),this.fetch=xs(t,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new Jt(new URL("rest/v1",a).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),this.storage=new Ss(this.storageUrl.href,this.headers,this.fetch,s?.storage),h.accessToken||this._listenForAuthEvents()}get functions(){return new Dt(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Cr(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,userStorage:i,storageKey:o,flowType:a,lock:l,debug:c},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new $r({url:this.authUrl.href,headers:Object.assign(Object.assign({},d),h),storageKey:o,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,userStorage:i,flowType:a,lock:l,debug:c,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new hs(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?this.changedAccessToken=s:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Mr=(n,e,t)=>new Rr(n,e,t);function xr(){if(typeof window<"u"||typeof process>"u")return!1;const n=process.version;if(n==null)return!1;const e=n.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}xr();export{Mr as c};
|