/** * Minified by jsDelivr using Terser v5.39.0. * Original file: /npm/@supabase/supabase-js@2.105.1/dist/umd/supabase.js * * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files */ var supabase=function(e){function t(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);ie?(...t)=>e(...t):(...e)=>fetch(...e))(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return function(e,t,r,s){function i(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||=Promise)((function(r,a){function n(e){try{h(s.next(e))}catch(e){a(e)}}function o(e){try{h(s.throw(e))}catch(e){a(e)}}function h(e){e.done?r(e.value):i(e.value).then(n,o)}h((s=s.apply(e,t||[])).next())}))}(this,arguments,void 0,(function*(e,t={}){let r,s;try{let{headers:o,method:h,body:l,signal:c,timeout:u}=t,d={},{region:p}=t;p||=this.region;let f,g=new URL(`${this.url}/${e}`);p&&"any"!==p&&(d["x-region"]=p,g.searchParams.set("forceFunctionRegion",p)),l&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",f=l):"string"==typeof l?(d["Content-Type"]="text/plain",f=l):typeof FormData<"u"&&l instanceof FormData?f=l:(d["Content-Type"]="application/json",f=JSON.stringify(l)):f=!l||"string"==typeof l||typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer||typeof FormData<"u"&&l instanceof FormData?l:JSON.stringify(l);let m=c;u&&(s=new AbortController,r=setTimeout((()=>s.abort()),u),c?(m=s.signal,c.addEventListener("abort",(()=>s.abort()))):m=s.signal);let y=yield this.fetch(g.toString(),{method:h||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:f,signal:m}).catch((e=>{throw new i(e)})),b=y.headers.get("x-relay-error");if(b&&"true"===b)throw new a(y);if(!y.ok)throw new n(y);let w,_=(y.headers.get("Content-Type")??"text/plain").split(";")[0].trim();return w="application/json"===_?yield y.json():"application/octet-stream"===_||"application/pdf"===_?yield y.blob():"text/event-stream"===_?y:"multipart/form-data"===_?yield y.formData():yield y.text(),{data:w,error:null,response:y}}catch(e){return{data:null,error:e,response:e instanceof n||e instanceof a?e.context:void 0}}finally{r&&clearTimeout(r)}}))}};let h=e=>Math.min(1e3*2**e,3e4),l=[520,503],c=["GET","HEAD","OPTIONS"];var u=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function d(e,t){return new Promise((r=>{if(t?.aborted)return void r();let s=setTimeout((()=>{t?.removeEventListener("abort",i),r()}),e);function i(){clearTimeout(s),r()}t?.addEventListener("abort",i)}))}function p(e,t,r,s){return!(!s||r>=3||!c.includes(e)||!l.includes(t))}var f=class{constructor(e){this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.shouldStripNulls=e.shouldStripNulls??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,this.retryEnabled=e.retry??!0,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if("text/csv"===this.headers.get("Accept"))throw Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let e=this.headers.get("Accept");"application/vnd.pgrst.object+json"===e?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!e||"application/json"===e)&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let s=this.fetch,i=(async()=>{let e=0;for(;;){let t,i=new Headers(r.headers);e>0&&i.set("X-Retry-Count",String(e));try{t=await s(r.url.toString(),{method:r.method,headers:i,body:JSON.stringify(r.body,((e,t)=>"bigint"==typeof t?t.toString():t)),signal:r.signal})}catch(t){if("AbortError"===t?.name||"ABORT_ERR"===t?.code||!c.includes(r.method))throw t;if(r.retryEnabled&&e<3){let t=h(e);e++,await d(t,r.signal);continue}throw t}if(!p(r.method,t.status,e,r.retryEnabled))return await r.processResponse(t);{let s=t.headers?.get("Retry-After")??null,i=null===s?h(e):1e3*Math.max(0,parseInt(s,10)||0);await t.text(),e++,await d(i,r.signal)}}})();return this.shouldThrowOnError||(i=i.catch((e=>{let t="",r="",s="",i=e?.cause;if(i){let r=i?.message??"",s=i?.code??"";t=`${e?.name??"FetchError"}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??"Error"}: ${r}`,s&&(t+=` (${s})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??"";let a=this.url.toString().length;return"AbortError"===e?.name||"ABORT_ERR"===e?.code?(s="",r="Request was aborted (timeout or manual cancellation)",a>this.urlLengthLimit&&(r+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):("HeadersOverflowError"===i?.name||"UND_ERR_HEADERS_OVERFLOW"===i?.code)&&(s="",r="HTTP headers exceeded server limits (typically 16KB)",a>this.urlLengthLimit&&(r+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${e?.name??"FetchError"}: ${e?.message}`,details:t,hint:r,code:s},data:null,count:null,status:0,statusText:""}}))),i.then(e,t)}async processResponse(e){var t=this;let r=null,s=null,i=null,a=e.status,n=e.statusText;if(e.ok){if("HEAD"!==t.method){let r=await e.text();""===r||(s="text/csv"===t.headers.get("Accept")||t.headers.get("Accept")&&t.headers.get("Accept")?.includes("application/vnd.pgrst.plan+text")?r:JSON.parse(r))}let o=t.headers.get("Prefer")?.match(/count=(exact|planned|estimated)/),h=e.headers.get("content-range")?.split("/");o&&h&&h.length>1&&(i=parseInt(h[1])),t.isMaybeSingle&&Array.isArray(s)&&(s.length>1?(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,i=null,a=406,n="Not Acceptable"):s=1===s.length?s[0]:null)}else{let i=await e.text();try{r=JSON.parse(i),Array.isArray(r)&&404===e.status&&(s=[],r=null,a=200,n="OK")}catch{404===e.status&&""===i?(a=204,n="No Content"):r={message:i}}if(r&&t.shouldThrowOnError)throw new u(r)}return{success:null===r,error:r,data:s,count:i,status:a,statusText:n}}returns(){return this}overrideTypes(){return this}},g=class extends f{select(e){let t=!1,r=(e??"*").split("").map((e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e))).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){let a=i?`${i}.order`:"order",n=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${n?`${n},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let i=void 0===s?"offset":`${s}.offset`,a=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:a="text"}={}){let n=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),o=this.headers.get("Accept")??"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${o}"; options=${n};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};let m=RegExp("[,()]");var y=class extends g{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map((e=>"string"==typeof e&&m.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map((e=>"string"==typeof e&&m.test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");let a=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).forEach((([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)})),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},b=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:i=8e3,retry:a}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=i,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=t??{},i=r?"HEAD":"GET",a=!1,n=(e??"*").split("").map((e=>/\s/.test(e)&&!a?"":('"'===e&&(a=!a),e))).join(""),{url:o,headers:h}=this.cloneRequestState();return o.searchParams.set("select",n),s&&h.append("Prefer",`count=${s}`),new y({method:i,url:o,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){let{url:s,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){let e=[...new Set(t)].map((e=>`"${e}"`));s.searchParams.set("columns",e.join(","))}}return new y({method:"POST",url:s,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){let{url:a,headers:n}=this.cloneRequestState();if(n.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&n.append("Prefer",`count=${s}`),i||n.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){let e=[...new Set(t)].map((e=>`"${e}"`));a.searchParams.set("columns",e.join(","))}}return new y({method:"POST",url:a,headers:n,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){let{url:r,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new y({method:"PATCH",url:r,headers:s,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){let{url:t,headers:r}=this.cloneRequestState();return e&&r.append("Prefer",`count=${e}`),new y({method:"DELETE",url:t,headers:r,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function w(e){return w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},w(e)}function _(e){var t=function(e,t){if("object"!=w(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=w(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==w(t)?t:t+""}function k(e,t,r){return(t=_(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function v(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,s)}return r}function S(e){for(var t=1;t0?(e,t)=>{let r=new AbortController,s=setTimeout((()=>r.abort()),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(s),o(e,t);let i=()=>{clearTimeout(s),r.abort()};return a.addEventListener("abort",i,{once:!0}),o(e,S(S({},t),{},{signal:r.signal})).finally((()=>{clearTimeout(s),a.removeEventListener("abort",i)}))}return o(e,S(S({},t),{},{signal:r.signal})).finally((()=>clearTimeout(s)))}:o,this.retry=n}from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new b(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){let a,n,o=new URL(`${this.url}/rpc/${e}`),h=e=>"object"==typeof e&&!!e&&(!Array.isArray(e)||e.some(h)),l=r&&Object.values(t).some(h);l?(a="POST",n=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter((([e,t])=>void 0!==t)).map((([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`])).forEach((([e,t])=>{o.searchParams.append(e,t)}))):(a="POST",n=t);let c=new Headers(this.headers);return l?c.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&c.set("Prefer",`count=${i}`),new y({method:a,url:o,headers:c,schema:this.schemaName,body:n,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},E=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)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"&&navigator.userAgent?.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."};let e=globalThis.process;if(e){let t=e.versions;if(t&&t.node){let e=t.node,r=parseInt(e.replace(/^v/,"").split(".")[0]);return r>=22?void 0===globalThis.WebSocket?{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"native",constructor:globalThis.WebSocket}:{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:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch{return!1}}};let R={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},A={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},O={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var P,j=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){return this._isArrayBuffer(e.payload?.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){let t=e.payload?.payload??new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,t)}_encodeJsonUserBroadcastPush(e){let t=e.payload?.payload??{},r=(new TextEncoder).encode(JSON.stringify(t)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,r)}_encodeUserBroadcastPush(e,t,r){let s=e.topic,i=e.ref??"",a=e.join_ref??"",n=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(o).length?"":JSON.stringify(o);if(a.length>255)throw Error(`joinRef length ${a.length} exceeds maximum of 255`);if(i.length>255)throw Error(`ref length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`topic length ${s.length} exceeds maximum of 255`);if(n.length>255)throw Error(`userEvent length ${n.length} exceeds maximum of 255`);if(h.length>255)throw Error(`metadata length ${h.length} exceeds maximum of 255`);let l=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+i.length+s.length+n.length+h.length,c=new ArrayBuffer(this.HEADER_LENGTH+l),u=new DataView(c),d=0;u.setUint8(d++,this.KINDS.userBroadcastPush),u.setUint8(d++,a.length),u.setUint8(d++,i.length),u.setUint8(d++,s.length),u.setUint8(d++,n.length),u.setUint8(d++,h.length),u.setUint8(d++,t),Array.from(a,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(i,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(s,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(n,(e=>u.setUint8(d++,e.charCodeAt(0)))),Array.from(h,(e=>u.setUint8(d++,e.charCodeAt(0))));var p=new Uint8Array(c.byteLength+r.byteLength);return p.set(new Uint8Array(c),0),p.set(new Uint8Array(r),c.byteLength),p.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,i,a,n]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:a,payload:n})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),n=t.getUint8(4),o=this.HEADER_LENGTH+4,h=r.decode(e.slice(o,o+s));o+=s;let l=r.decode(e.slice(o,o+i));o+=i;let c=r.decode(e.slice(o,o+a));o+=a;let u=e.slice(o,e.byteLength),d=n===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:l,payload:d};return a>0&&(p.meta=JSON.parse(c)),{join_ref:null,ref:null,topic:h,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter((([e])=>t.includes(e)))):{}}};!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(P||={});let C=(e,t,r={})=>{let s=r.skipTypes??[];return t?Object.keys(t).reduce(((r,i)=>(r[i]=$(i,e,t,s),r)),{}):{}},$=(e,t,r,s)=>{let i=t.find((t=>t.name===e))?.type,a=r[e];return i&&!s.includes(i)?I(i,a):x(a)},I=(e,t)=>{if("_"===e.charAt(0))return D(t,e.slice(1,e.length));switch(e){case P.bool:return N(t);case P.float4:case P.float8:case P.int2:case P.int4:case P.int8:case P.numeric:case P.oid:return L(t);case P.json:case P.jsonb:return U(t);case P.timestamp:return B(t);case P.abstime:case P.date:case P.daterange:case P.int4range:case P.int8range:case P.money:case P.reltime:case P.text:case P.time:case P.timestamptz:case P.timetz:case P.tsrange:case P.tstzrange:default:return x(t)}},x=e=>e,N=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},L=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},U=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e},D=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map((e=>I(t,e)))}return e},B=e=>"string"==typeof e?e.replace(" ","T"):e,q=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname+="/api/broadcast",t.href};var M,H=e=>"function"==typeof e?e:function(){return e},W=typeof self<"u"?self:null,K=typeof window<"u"?window:null,F=W||K||globalThis,J=0,G=1,V=2,z=3,Y={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},X={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Q="longpoll",Z="websocket",ee=4,te="base64url.bearer.phx.",re=class{constructor(e,t,r,s){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),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()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter((t=>t.status===e)).forEach((e=>e.callback(t)))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)})),this.timeoutTimer=setTimeout((()=>{this.trigger("timeout",{})}),this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},se=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout((()=>{this.tries+=1,this.callback()}),this.timerCalc(this.tries+1))}},ie=class{constructor(e,t,r){this.state=Y.closed,this.topic=e,this.params=H(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new re(this,X.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new se((()=>{this.socket.isConnected()&&this.rejoin()}),this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError((()=>this.rejoinTimer.reset()))),this.stateChangeRefs.push(this.socket.onOpen((()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()}))),this.joinPush.receive("ok",(()=>{this.state=Y.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((e=>e.send())),this.pushBuffer=[]})),this.joinPush.receive("error",(e=>{this.state=Y.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.onClose((()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Y.closed,this.socket.remove(this)})),this.onError((e=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=Y.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.joinPush.receive("timeout",(()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new re(this,X.leave,H({}),this.timeout).send(),this.state=Y.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.on(X.reply,((e,t)=>{this.trigger(this.replyEventName(t),e)}))}join(e=this.timeout){if(this.joinedOnce)throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach((e=>e.destroy())),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Y.closed,this.bindings=[]}onClose(e){this.on(X.close,e)}onError(e){return this.on(X.error,(t=>e(t)))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter((r=>!(r.event===e&&(void 0===t||t===r.ref))))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t||={},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new re(this,e,(function(){return t}),r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Y.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(X.close,"leave")},r=new re(this,X.leave,H({}),e);return r.receive("ok",(()=>t())).receive("timeout",(()=>t())),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,s){return this.topic===e&&(!s||s===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:s}),!1))}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Y.joining,this.joinPush.resend(e))}trigger(e,t,r,s){let i=this.onMessage(e,t,r,s);if(t&&!i)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let a=this.bindings.filter((s=>s.event===e&&this.filterBindings(s,t,r)));for(let e=0;eh.abort()),i),o.signal=h.signal),F.fetch(t,o).then((e=>e.text())).then((e=>this.parseJSON(e))).then((e=>n&&n(e))).catch((e=>{"AbortError"===e.name&&a?a():n&&n(null)})),h}static xdomainRequest(e,t,r,s,i,a,n){return e.timeout=i,e.open(t,r),e.onload=()=>{let t=this.parseJSON(e.responseText);n&&n(t)},a&&(e.ontimeout=a),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,r,s,i,a,n,o){e.open(t,r,!0),e.timeout=a;for(let[t,r]of Object.entries(s))e.setRequestHeader(t,r);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{e.readyState===ee&&o&&o(this.parseJSON(e.responseText))},n&&(e.ontimeout=n),e.send(i),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=t?`${t}[${s}]`:s,a=e[s];"object"==typeof a?r.push(this.serialize(a,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(a))}return r.join("&")}static appendParams(e,t){return 0===Object.keys(t).length?e:`${e}${e.match(/\?/)?"&":"?"}${this.serialize(t)}`}},ne=class{constructor(e,t){t&&2===t.length&&t[1].startsWith(te)&&(this.authToken=atob(t[1].slice(21))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=J,setTimeout((()=>this.poll()),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+Z),"$1/"+Q)}endpointURL(){return ae.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=J}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===G||this.readyState===J}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,(()=>this.ontimeout()),(e=>{if(e){var{status:t,token:r,messages:s}=e;if(410===t&&null!==this.token)return this.onerror(410),void this.closeAndRetry(3410,"session_gone",!1);this.token=r}else t=0;switch(t){case 200:s.forEach((e=>{setTimeout((()=>this.onmessage({data:e})),0)})),this.poll();break;case 204:this.poll();break;case 410:this.readyState=G,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw Error(`unhandled poll status ${t}`)}}))}send(e){"string"!=typeof e&&(e=(e=>{let t="",r=new Uint8Array(e),s=r.byteLength;for(let e=0;e{this.batchSend(this.currentBatch),this.currentBatch=null}),0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join("\n"),(()=>this.onerror("timeout")),(e=>{this.awaitingBatchAck=!1,e&&200===e.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))}))}close(e,t,r){for(let e of this.reqs)e.abort();this.readyState=z;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,i){let a;a=ae.request(e,this.endpointURL(),t,r,this.timeout,(()=>{this.reqs.delete(a),s()}),(e=>{this.reqs.delete(a),this.isActive()&&i(e)})),this.reqs.add(a)}},oe=class e{constructor(t,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,(t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.joinRef=this.channel.joinRef(),this.state=e.syncState(this.state,t,r,s),this.pendingDiffs.forEach((t=>{this.state=e.syncDiff(this.state,t,r,s)})),this.pendingDiffs=[],i()})),this.channel.on(s.diff,(t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,r,s),i())}))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,r,s){let i=this.clone(e),a={},n={};return this.map(i,((e,r)=>{t[e]||(n[e]=r)})),this.map(t,((e,t)=>{let r=i[e];if(r){let s=t.metas.map((e=>e.phx_ref)),i=r.metas.map((e=>e.phx_ref)),o=t.metas.filter((e=>i.indexOf(e.phx_ref)<0)),h=r.metas.filter((e=>s.indexOf(e.phx_ref)<0));o.length>0&&(a[e]=t,a[e].metas=o),h.length>0&&(n[e]=this.clone(r),n[e].metas=h)}else a[e]=t})),this.syncDiff(i,{joins:a,leaves:n},r,s)}static syncDiff(e,t,r,s){let{joins:i,leaves:a}=this.clone(t);return r||=function(){},s||=function(){},this.map(i,((t,s)=>{let i=e[t];if(e[t]=this.clone(s),i){let r=e[t].metas.map((e=>e.phx_ref)),s=i.metas.filter((e=>r.indexOf(e.phx_ref)<0));e[t].metas.unshift(...s)}r(t,i,s)})),this.map(a,((t,r)=>{let i=e[t];if(!i)return;let a=r.metas.map((e=>e.phx_ref));i.metas=i.metas.filter((e=>a.indexOf(e.phx_ref)<0)),s(t,i,r),0===i.metas.length&&delete e[t]})),e}static list(e,t){return t||=function(e,t){return t},this.map(e,((e,r)=>t(e,r)))}static map(e,t){return Object.getOwnPropertyNames(e).map((r=>t(r,e[r])))}static clone(e){return JSON.parse(JSON.stringify(e))}},he={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[r,s,i,a,n]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:a,payload:n})}},binaryEncode(e){let{join_ref:t,ref:r,event:s,topic:i,payload:a}=e,n=this.META_LENGTH+t.length+r.length+i.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+n),h=new DataView(o),l=0;h.setUint8(l++,this.KINDS.push),h.setUint8(l++,t.length),h.setUint8(l++,r.length),h.setUint8(l++,i.length),h.setUint8(l++,s.length),Array.from(t,(e=>h.setUint8(l++,e.charCodeAt(0)))),Array.from(r,(e=>h.setUint8(l++,e.charCodeAt(0)))),Array.from(i,(e=>h.setUint8(l++,e.charCodeAt(0)))),Array.from(s,(e=>h.setUint8(l++,e.charCodeAt(0))));var c=new Uint8Array(o.byteLength+a.byteLength);return c.set(new Uint8Array(o),0),c.set(new Uint8Array(a),o.byteLength),c.buffer},binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),n=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(e.slice(n,n+s));n+=s;let h=r.decode(e.slice(n,n+i));n+=i;let l=r.decode(e.slice(n,n+a));return n+=a,{join_ref:o,ref:null,topic:h,event:l,payload:e.slice(n,e.byteLength)}},decodeReply(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),n=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,h=r.decode(e.slice(o,o+s));o+=s;let l=r.decode(e.slice(o,o+i));o+=i;let c=r.decode(e.slice(o,o+a));o+=a;let u=r.decode(e.slice(o,o+n));o+=n;let d={status:u,response:e.slice(o,e.byteLength)};return{join_ref:h,ref:l,topic:c,event:X.reply,payload:d}},decodeBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,n=r.decode(e.slice(a,a+s));a+=s;let o=r.decode(e.slice(a,a+i));return a+=i,{join_ref:null,ref:null,topic:n,event:o,payload:e.slice(a,e.byteLength)}}},le=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||1e4,this.transport=t.transport||F.WebSocket||ne,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||F&&F.sessionStorage,this.establishedConnections=0,this.defaultEncoder=he.encode.bind(he),this.defaultDecoder=he.decode.bind(he),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport===ne?(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder):(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder);let r=null;K&&K.addEventListener&&(K.addEventListener("pagehide",(e=>{this.conn&&(this.disconnect(),r=this.connectClock)})),K.addEventListener("pageshow",(e=>{r===this.connectClock&&(r=null,this.connect())})),K.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown((()=>this.connect())))}))),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,r)=>{console.log(`${e}: ${t}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=H(t.params||{}),this.endPoint=`${e}/${Z}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new se((()=>{if(this.pageHidden)return this.log("Not reconnecting as page is hidden!"),void this.teardown();this.teardown((async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()}))}),this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return ne}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&=(this.conn.close(),null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=ae.appendParams(ae.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"===e.charAt(0)?"/"===e.charAt(1)?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`:e}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown((()=>{this.disconnecting=!1,e&&e()}),t,r)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=H(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==ne?this.connectWithFallback(ne,this.longPollFallbackMs):this.transportConnect())}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return null!==this.logger}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage((i=>{i.ref===t&&(this.off([s]),e(Date.now()-r))}));return!0}transportName(e){return e===ne?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix",`${te}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let r,s=!1,i=!0,a=this.transportName(e),n=t=>{this.log("transport",`falling back to ${a}...`,t),this.off([void 0,r]),i=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return n("memorized");this.fallbackTimer=setTimeout(n,t),r=this.onError((e=>{this.log("transport","error",e),i&&!s&&(clearTimeout(this.fallbackTimer),n(e))})),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen((()=>{if(s=!0,!i){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,"true"),this.log("transport",`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(n,t),this.ping((e=>{this.log("transport","connected to primary after",e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)}))})),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown((()=>this.reconnectTimer.scheduleTimeout()),1e3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout((()=>this.sendHeartbeat()),this.heartbeatIntervalMs))}teardown(e,t,r){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,(()=>{t?s.close(t,r||""):s.close(),this.waitForSocketClosed(s,(()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()}))}))}waitForBufferDone(e,t,r=1){5!==r&&e.bufferedAmount?setTimeout((()=>{this.waitForBufferDone(e,t,r+1)}),150*r):t()}waitForSocketClosed(e,t,r=1){5!==r&&e.readyState!==z?setTimeout((()=>{this.waitForSocketClosed(e,t,r+1)}),150*r):t()}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",e,t,r),(t===this.transport||r>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach((t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(X.error,e)}))}connectionState(){switch(this.conn&&this.conn.readyState){case J:return"connecting";case G:return"open";case V:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter((t=>t!==e))}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter((([t])=>-1===e.indexOf(t)))}channel(e,t={}){let r=new ie(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:s,ref:i,join_ref:a}=e;this.log("push",`${t} ${r} (${a}, ${i})`,s)}this.isConnected()?this.encode(e,(e=>this.conn.send(e))):this.sendBuffer.push((()=>this.encode(e,(e=>this.conn.send(e)))))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(this.isConnected())if(this.pendingHeartbeatRef)this.heartbeatTimeout();else{this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout((()=>this.heartbeatTimeout()),this.heartbeatIntervalMs)}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,(e=>{let{topic:t,event:r,payload:s,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){let t=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===s.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout((()=>this.sendHeartbeat()),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${r} ${i&&"("+i+")"||""}`.trim(),s);for(let e=0;e{try{s(...t)}catch(t){this.log("error",`error in ${e} callback`,t)}}))}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}leaveOpenTopic(e){let t=this.channels.find((t=>t.topic===e&&(t.isJoined()||t.isJoining())));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}},ce=class e{constructor(t,r){let s=function(e){return e?.events&&{events:e.events}}(r);this.presence=new oe(t.getChannel(),s),this.presence.onJoin(((r,s,i)=>{let a=e.onJoinPayload(r,s,i);t.getChannel().trigger("presence",a)})),this.presence.onLeave(((r,s,i)=>{let a=e.onLeavePayload(r,s,i);t.getChannel().trigger("presence",a)})),this.presence.onSync((()=>{t.getChannel().trigger("presence",{event:"sync"})}))}get state(){return e.transformState(this.presence.state)}static transformState(e){return e=function(e){return JSON.parse(JSON.stringify(e))}(e),Object.getOwnPropertyNames(e).reduce(((t,r)=>{let s=e[r];return t[r]=ue(s),t}),{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:de(t),newPresences:ue(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:de(t),leftPresences:ue(r)}}};function ue(e){return e.metas.map((e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)))}function de(e){return e?.metas?ue(e):[]}!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(M||={});var pe=class{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new ce(this.channel.channelAdapter,t)}};var fe,ge,me,ye=class{constructor(e,t,r){let s=function(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}(r);this.channel=e.getSocket().channel(t,s),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,t,r){let s;try{s=this.channel.push(e,t,r)}catch{throw Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload())}return s}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===R.joined}isJoined(){return this.state===R.joined}isJoining(){return this.state===R.joining}isClosed(){return this.state===R.closed}isLeaving(){return this.state===R.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(fe||={}),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(ge||={}),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(me||={});let be=R;var we=class e{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},r){if(this.topic=e,this.params=t,this.socket=r,this.bindings={},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.channelAdapter=new ye(this.socket.socketAdapter,e,this.params),this.presence=new pe(this),this._onClose((()=>{this.socket._remove(this)})),this._updateFilterTransform(),this.broadcastEndpointURL=q(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&this.params.config?.broadcast?.replay)throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,t=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:r,presence:s,private:i}}=this.params,a=this.bindings.postgres_changes?.map((e=>e.filter))??[],n=!!this.bindings[ge.PRESENCE]&&this.bindings[ge.PRESENCE].length>0||!0===this.params.config.presence?.enabled,o={},h={broadcast:r,presence:Object.assign(Object.assign({},s),{enabled:n}),postgres_changes:a,private:i};this.socket.accessTokenValue&&(o.access_token=this.socket.accessTokenValue),this._onError((t=>{e?.(me.CHANNEL_ERROR,function(e){if(e instanceof Error)return e;if("string"==typeof e)return Error(e);if(e&&"object"==typeof e){let t=e;if("number"==typeof t.code){let r="string"==typeof t.reason&&t.reason?` (${t.reason})`:"";return Error(`socket closed: ${t.code}${r}`,{cause:e})}return Error("channel error: transport failure",{cause:e})}return Error("channel error: connection lost")}(t))})),this._onClose((()=>e?.(me.CLOSED))),this.updateJoinPayload(Object.assign({config:h},o)),this._updateFilterMessage(),this.channelAdapter.subscribe(t).receive("ok",(async({postgres_changes:t})=>{this.socket._isManualToken()||this.socket.setAuth(),void 0!==t?this._updatePostgresBindings(t,e):e?.(me.SUBSCRIBED)})).receive("error",(t=>{this.state=R.errored;let r=Object.values(t).join(", ")||"error";e?.(me.CHANNEL_ERROR,Error(r,{cause:t}))})).receive("timeout",(()=>{e?.(me.TIMED_OUT)}))}return this}_updatePostgresBindings(t,r){let s=this.bindings.postgres_changes,i=s?.length??0,a=[];for(let n=0;n{let s=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);"broadcast"===e.type&&!this.params?.config?.broadcast?.ack&&r("ok"),s.receive("ok",(()=>r("ok"))),s.receive("error",(()=>r("error"))),s.receive("timeout",(()=>r("timed out")))}));{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:r,payload:s}=e,i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:r,payload:s,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,t.timeout??this.timeout);return await(e.body?.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise((t=>{this.channelAdapter.unsubscribe(e).receive("ok",(()=>t("ok"))).receive("timeout",(()=>t("timed out"))).receive("error",(()=>t("error")))}))}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,r){let s=new AbortController,i=setTimeout((()=>s.abort()),r),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),a}_on(e,t,r){let s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:r,ref:this.channelAdapter.on(e,r)};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings(((e,t,r)=>{let s=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(s,r))return!1;let i=this.bindings[s]?.find((t=>t.ref===e.ref));if(!i)return!0;if(["broadcast","presence","postgres_changes"].includes(s)){if("id"in i){let e=i.id,r=i.filter?.event;return e&&t.ids?.includes(e)&&("*"===r||r?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}{let e=(i?.filter?.event)?.toLocaleLowerCase();return"*"===e||e===(t?.event)?.toLocaleLowerCase()}}return i.type.toLocaleLowerCase()===s}))}_notThisChannelEvent(e,t){let{close:r,error:s,leave:i,join:a}=A;return t&&[r,s,i,a].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform(((e,t,r)=>{if("object"==typeof t&&"ids"in t){let e=t.data,{schema:r,table:s,commit_timestamp:i,type:a,errors:n}=e,o={schema:r,table:s,commit_timestamp:i,eventType:a,new:{},old:{},errors:n};return Object.assign(Object.assign({},o),this._getPayloadRecords(e))}return t}))}copyBindings(e){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let t in e.bindings)for(let r of e.bindings[t])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=C(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=C(e.columns,e.old_record)),t}},_e=class{constructor(e,t){this.socket=new le(e,t)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,r,s=1e4){return new Promise((i=>{setTimeout((()=>i("timeout")),s),this.socket.disconnect((()=>{e(),i("ok")}),t,r)}))}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==O.connecting}isDisconnecting(){return this.socket.connectionState()==O.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};let ke=25e3,ve=[1e3,2e3,5e3,1e4];var Se=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new j,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!t?.params?.apikey)throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.socketAdapter=new _e(e,this._initializeOptions(t)),this.httpEndpoint=q(e),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let t=e.message;throw t.includes("Node.js")?Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`):Error(`WebSocket not available: ${t}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect((()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()}),e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return"ok"===t&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map((async e=>{let t=await e.unsubscribe();return e.teardown(),t})),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}connectionState(){return this.socketAdapter.connectionState()||O.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let r=`realtime:${e}`,s=this.getChannels().find((e=>e.topic===r));if(s)return s;{let r=new we(`realtime:${e}`,t,this);return this._cancelPendingDisconnect(),this.channels.push(r),r}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter((t=>t.topic!==e.topic)),0===this.channels.length&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),0===this._disconnectOnEmptyChannelsAfterMs)return this.log("transport","disconnecting immediately - no channels"),void this.disconnect();this._pendingDisconnectTimer=setTimeout((()=>{this._pendingDisconnectTimer=null,0===this.channels.length&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())}),this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){null!==this._pendingDisconnectTimer&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach((e=>{let r={access_token:t,version:"realtime-js/2.105.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(A.access_token,{access_token:t})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch((t=>{this.log("error",`Error setting auth in ${e}`,t)}))}_setupConnectionHandlers(){this.socketAdapter.onOpen((()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch((e=>{this.log("error","error waiting for auth on connect",e)})),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()})),this.socketAdapter.onClose((()=>{this.worker&&this.workerRef&&this._terminateWorker()})),this.socketAdapter.onMessage((e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)}))}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,r)=>{"sent"==t&&this._setAuthSafely(),e&&e(t,r)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&=(this.log("worker","terminating worker"),void this.workerRef.terminate())}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_initializeOptions(e){this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null;let t={};t.timeout=e?.timeout??1e4,t.heartbeatIntervalMs=e?.heartbeatIntervalMs??ke,this._disconnectOnEmptyChannelsAfterMs=e?.disconnectOnEmptyChannelsAfterMs??2*(e?.heartbeatIntervalMs??ke),t.transport=e?.transport??E.getWebSocketConstructor(),t.params=e?.params,t.logger=e?.logger,t.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),t.reconnectAfterMs=e?.reconnectAfterMs??(e=>ve[e-1]||1e4);let r,s,i=e?.vsn??"2.0.0";switch(i){case"1.0.0":r=(e,t)=>t(JSON.stringify(e)),s=(e,t)=>t(JSON.parse(e));break;case"2.0.0":r=this.serializer.encode.bind(this.serializer),s=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${t.vsn}`)}if(t.vsn=i,t.encode=e?.encode??r,t.decode=e?.decode??s,t.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,t.params=Object.assign(Object.assign({},t.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,t.autoSendHeartbeat=!this.worker}return t}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}},Te=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function Ee(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:i,body:a,headers:n}){let o=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,i),h=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),l=await t(o,{method:r,headers:{...a?{"Content-Type":"application/json"}:{},...h,...n},body:a?JSON.stringify(a):void 0}),c=await l.text(),u=(l.headers.get("content-type")||"").includes("application/json"),d=u&&c?JSON.parse(c):c;if(!l.ok){let e=u?d:void 0,t=e?.error;throw new Te(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:d}}}}function Re(e){return e.join("")}var Ae=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Re(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map((e=>({namespace:e})))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Re(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Re(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Re(e.namespace)}`}),!0}catch(e){if(e instanceof Te&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Te&&409===e.status)return;throw e}}};function Oe(e){return e.join("")}var Pe=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Oe(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Oe(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Oe(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Oe(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Oe(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Oe(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Te&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Te&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},je=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`),this.client=Ee({baseUrl:e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new Ae(this.client,t),this.tableOps=new Pe(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};function Ce(e){return Ce="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ce(e)}function $e(e){var t=function(e,t){if("object"!=Ce(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=Ce(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Ce(t)?t:t+""}function Ie(e,t,r){return(t=$e(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function xe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,s)}return r}function Ne(e){for(var t=1;t{if(Array.isArray(e))return e.map((e=>Me(e)));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach((([e,r])=>{let s=e.replace(/([-_][a-z])/gi,(e=>e.toUpperCase().replace(/[-_]/g,"")));t[s]=Me(r)})),t},He=e=>e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:e.error?.message)||JSON.stringify(e),We=(e,t,r,s)=>{let i={method:e,headers:t?.headers||{}};if("GET"===e||"HEAD"===e||!s)return Ne(Ne({},i),r);if((e=>{if("object"!=typeof e||!e)return!1;let t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)){let e,r=t?.headers||{};for(let[t,s]of Object.entries(r))"content-type"===t.toLowerCase()&&(e=s);i.headers=qe(r,"Content-Type",e??"application/json"),i.body=JSON.stringify(s)}else i.body=s;return t?.duplex&&(i.duplex=t.duplex),Ne(Ne({},i),r)};async function Ke(e,t,r,s,i,a,n){return new Promise(((o,h)=>{e(r,We(t,s,i,a)).then((e=>{if(!e.ok)throw e;if(s?.noResolveJson)return e;if("vectors"===n){let t=e.headers.get("content-type");if("0"===e.headers.get("content-length")||204===e.status||!t||!t.includes("application/json"))return{}}return e.json()})).then((e=>o(e))).catch((e=>(async(e,t,r,s)=>{if("object"==typeof e&&e&&"function"==typeof e.json){let r=e,i=parseInt(r.status,10);Number.isFinite(i)||(i=500),r.json().then((e=>{let r=e?.statusCode||e?.code||i+"";t(new De(He(e),i,r,s))})).catch((()=>{let e=i+"";t(new De(r.statusText||`HTTP ${i} error`,i,e,s))}))}else t(new Be(He(e),e,s))})(e,h,0,n)))}))}function Fe(e="storage"){return{get:async(t,r,s,i)=>Ke(t,"GET",r,s,i,void 0,e),post:async(t,r,s,i,a)=>Ke(t,"POST",r,i,a,s,e),put:async(t,r,s,i,a)=>Ke(t,"PUT",r,i,a,s,e),head:async(t,r,s,i)=>Ke(t,"HEAD",r,Ne(Ne({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,s,i,a)=>Ke(t,"DELETE",r,i,a,s,e)}}let{get:Je,post:Ge,put:Ve,head:ze,remove:Ye}=Fe("storage"),Xe=Fe("vectors");var Qe=class{constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=function(e){let t={};for(let[r,s]of Object.entries(e))t[r.toLowerCase()]=s;return t}(t),this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=qe(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Ue(e))return{data:null,error:e};throw e}}},Ze=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Ue(e))return{data:null,error:e};throw e}}};let et;et=Symbol.toStringTag;var tt=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[et]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ze(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||=this.execute(),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Ue(e))return{data:null,error:e};throw e}}};let rt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},st={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var it=class extends Qe{constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,s){var i=this;return i.handleOperation((async()=>{let a,n=Ne(Ne({},st),s),o=Ne(Ne({},i.headers),"POST"===e&&{"x-upsert":String(n.upsert)}),h=n.metadata;if(typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",n.cacheControl),h&&a.append("metadata",i.encodeMetadata(h)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",n.cacheControl),h&&!a.has("metadata")&&a.append("metadata",i.encodeMetadata(h))):(a=r,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType,h&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(h))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&"object"==typeof a&&"pipe"in a&&"function"==typeof a.pipe)&&!n.duplex&&(n.duplex="half")),s?.headers)for(let[e,t]of Object.entries(s.headers))o=qe(o,e,t);let l=i._removeEmptyFolders(t),c=i._getFinalPath(l),u=await("PUT"==e?Ve:Ge)(i.fetch,`${i.url}/object/${c}`,a,Ne({headers:o},n?.duplex?{duplex:n.duplex}:{}));return{path:l,id:u.Id,fullPath:u.Key}}))}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var i=this;let a=i._removeEmptyFolders(e),n=i._getFinalPath(a),o=new URL(i.url+`/object/upload/sign/${n}`);return o.searchParams.set("token",t),i.handleOperation((async()=>{let e,t=Ne(Ne({},st),s),n=Ne(Ne({},i.headers),{"x-upsert":String(t.upsert)}),h=t.metadata;if(typeof Blob<"u"&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),h&&e.append("metadata",i.encodeMetadata(h)),e.append("",r)):typeof FormData<"u"&&r instanceof FormData?(e=r,e.has("cacheControl")||e.append("cacheControl",t.cacheControl),h&&!e.has("metadata")&&e.append("metadata",i.encodeMetadata(h))):(e=r,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType,h&&(n["x-metadata"]=i.toBase64(i.encodeMetadata(h))),(typeof ReadableStream<"u"&&e instanceof ReadableStream||e&&"object"==typeof e&&"pipe"in e&&"function"==typeof e.pipe)&&!t.duplex&&(t.duplex="half")),s?.headers)for(let[e,t]of Object.entries(s.headers))n=qe(n,e,t);return{path:a,fullPath:(await Ve(i.fetch,o.toString(),e,Ne({headers:n},t?.duplex?{duplex:t.duplex}:{}))).Key}}))}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation((async()=>{let s=r._getFinalPath(e),i=Ne({},r.headers);t?.upsert&&(i["x-upsert"]="true");let a=await Ge(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),n=new URL(r.url+a.url),o=n.searchParams.get("token");if(!o)throw new Le("No token returned by API");return{signedUrl:n.toString(),path:e,token:o}}))}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation((async()=>await Ge(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:s.headers})))}async copy(e,t,r){var s=this;return s.handleOperation((async()=>({path:(await Ge(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key})))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation((async()=>{let i=s._getFinalPath(e),a="object"==typeof r?.transform&&null!==r.transform&&Object.keys(r.transform).length>0,n=await Ge(s.fetch,`${s.url}/object/sign/${i}`,Ne({expiresIn:t},a?{transform:r.transform}:{}),{headers:s.headers}),o=new URLSearchParams;r?.download&&o.set("download",!0===r.download?"":r.download),null!=r?.cacheNonce&&o.set("cacheNonce",String(r.cacheNonce));let h=o.toString();return{signedUrl:encodeURI(`${s.url}${n.signedURL}${h?`&${h}`:""}`)}}))}async createSignedUrls(e,t,r){var s=this;return s.handleOperation((async()=>{let i=await Ge(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),a=new URLSearchParams;r?.download&&a.set("download",!0===r.download?"":r.download),null!=r?.cacheNonce&&a.set("cacheNonce",String(r.cacheNonce));let n=a.toString();return i.map((e=>Ne(Ne({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${n?`&${n}`:""}`):null})))}))}download(e,t,r){let s="object"==typeof t?.transform&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;t?.transform&&this.applyTransformOptsToQuery(i,t.transform),null!=t?.cacheNonce&&i.set("cacheNonce",String(t.cacheNonce));let a=i.toString(),n=this._getFinalPath(e);return new tt((()=>Je(this.fetch,`${this.url}/${s}/${n}${a?`?${a}`:""}`,{headers:this.headers,noResolveJson:!0},r)),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation((async()=>Me(await Je(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers}))))}async exists(e){var t=this;let r=t._getFinalPath(e);try{return await ze(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ue(e)){let t=e instanceof De?e.status:e instanceof Be?e.originalError?.status:void 0;if(void 0!==t&&[400,404].includes(t))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=new URLSearchParams;t?.download&&s.set("download",!0===t.download?"":t.download),t?.transform&&this.applyTransformOptsToQuery(s,t.transform),null!=t?.cacheNonce&&s.set("cacheNonce",String(t.cacheNonce));let i=s.toString(),a="object"==typeof t?.transform&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}`)+(i?`?${i}`:"")}}}async remove(e){var t=this;return t.handleOperation((async()=>await Ye(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers})))}async list(e,t,r){var s=this;return s.handleOperation((async()=>{let i=Ne(Ne(Ne({},rt),t),{},{prefix:e||""});return await Ge(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)}))}async listV2(e,t){var r=this;return r.handleOperation((async()=>{let s=Ne({},e);return await Ge(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t)}))}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,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("quality",t.quality.toString()),e}};let at={"X-Client-Info":"storage-js/2.105.1"};var nt=class extends Qe{constructor(e,t={},r,s){let i=new URL(e);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),super(i.href.replace(/\/$/,""),Ne(Ne({},at),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation((async()=>{let r=t.listBucketOptionsToQueryString(e);return await Je(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})}))}async getBucket(e){var t=this;return t.handleOperation((async()=>await Je(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers})))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation((async()=>await Ge(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers})))}async updateBucket(e,t){var r=this;return r.handleOperation((async()=>await Ve(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers})))}async emptyBucket(e){var t=this;return t.handleOperation((async()=>await Ge(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers})))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Ye(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers})))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},ot=class extends Qe{constructor(e,t={},r){super(e.replace(/\/$/,""),Ne(Ne({},at),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation((async()=>await Ge(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers})))}async listBuckets(e){var t=this;return t.handleOperation((async()=>{let r=new URLSearchParams;void 0!==e?.limit&&r.set("limit",e.limit.toString()),void 0!==e?.offset&&r.set("offset",e.offset.toString()),e?.sortColumn&&r.set("sortColumn",e.sortColumn),e?.sortOrder&&r.set("sortOrder",e.sortOrder),e?.search&&r.set("search",e.search);let s=r.toString(),i=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return await Je(t.fetch,i,{headers:t.headers})}))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Ye(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers})))}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new Le("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new je({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"==typeof r?async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}:r}})}},ht=class extends Qe{constructor(e,t={},r){super(e.replace(/\/$/,""),Ne(Ne({},at),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{}))}async getIndex(e,t){var r=this;return r.handleOperation((async()=>await Xe.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})))}async listIndexes(e){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers})))}async deleteIndex(e,t){var r=this;return r.handleOperation((async()=>await Xe.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{}))}},lt=class extends Qe{constructor(e,t={},r){super(e.replace(/\/$/,""),Ne(Ne({},at),{},{"Content-Type":"application/json"},t),r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{}))}async getVectors(e){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers})))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers})))}async queryVectors(e){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers})))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{}))}},ct=class extends Qe{constructor(e,t={},r){super(e.replace(/\/$/,""),Ne(Ne({},at),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{}))}async getBucket(e){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers})))}async listBuckets(e={}){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers})))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Xe.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{}))}},ut=class extends ct{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new dt(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},dt=class extends ht{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,Ne(Ne({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,Ne(Ne({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new pt(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},pt=class extends lt{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,Ne(Ne({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,Ne(Ne({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,Ne(Ne({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,Ne(Ne({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,Ne(Ne({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},ft=class extends nt{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new it(this.url,this.headers,e,this.fetch)}get vectors(){return new ut(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new ot(this.url+"/iceberg",this.headers,this.fetch)}};let gt="";gt=typeof Deno<"u"?"deno":typeof document<"u"?"web":typeof navigator<"u"&&"ReactNative"===navigator.product?"react-native":"node";let mt={headers:{"X-Client-Info":`supabase-js-${gt}/2.105.1`}},yt={schema:"public"},bt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},wt={},_t=(e,t,r)=>{let s=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),i=Headers;return async(r,a)=>{let n=await t()??e,o=new i(a?.headers);return o.has("apikey")||o.set("apikey",e),o.has("Authorization")||o.set("Authorization",`Bearer ${n}`),s(r,{...a,headers:o})}};let kt="2.105.1",vt=3e4,St=3*vt,Tt={"X-Client-Info":`gotrue-js/${kt}`},Et="X-Supabase-Api-Version",Rt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},At=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;var Ot=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function Pt(e){return"object"==typeof e&&!!e&&"__isAuthError"in e}var jt=class extends Ot{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Ct(e){return Pt(e)&&"AuthApiError"===e.name}var $t=class extends Ot{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},It=class extends Ot{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},xt=class extends It{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Nt(e){return Pt(e)&&"AuthSessionMissingError"===e.name}var Lt=class extends It{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ut=class extends It{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Dt=class extends It{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function Bt(e){return Pt(e)&&"AuthImplicitGrantRedirectError"===e.name}var qt=class extends It{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Mt=class extends It{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};var Ht=class extends It{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Wt(e){return Pt(e)&&"AuthRetryableFetchError"===e.name}var Kt=class extends It{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}};var Ft=class extends It{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};let Jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Gt=" \t\n\r=".split(""),Vt=(()=>{let e=Array(128);for(let t=0;t=6;)r(Jt[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue<<=6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(Jt[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function Yt(e,t,r){let s=Vt[e];if(!(s>-1)){if(-2===s)return;throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function Xt(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw Error("Invalid UTF-8 sequence");t.codepoint=7&e}--t.utf8seq}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,--t.utf8seq,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Zt(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t55295&&s<=56319){let t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}Qt(s,t)}}(e,(e=>t.push(e))),new Uint8Array(t)}function tr(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach((e=>zt(e,r,s))),zt(null,r,s),t.join("")}let rr=()=>typeof window<"u"&&typeof document<"u",sr={tested:!1,writable:!1},ir=()=>{if(!rr())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch{return!1}if(sr.tested)return sr.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),sr.tested=!0,sr.writable=!0}catch{sr.tested=!0,sr.writable=!1}return sr.writable};let ar=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),nr=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},or=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},hr=async(e,t)=>{await e.removeItem(t)};var lr=class e{constructor(){this.promise=new e.promiseConstructor(((e,t)=>{this.resolve=e,this.reject=t}))}};function cr(e){let t=e.split(".");if(3!==t.length)throw new Ft("Invalid JWT structure");for(let e=0;eString.fromCharCode(e))).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pr(e,t,r=!1){let s=function(){let e=new Uint32Array(56);if(typeof crypto>"u"){let e="";for(let t=0;t<56;t++)e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".charAt(Math.floor(66*Math.random()));return e}return crypto.getRandomValues(e),Array.from(e,ur).join("")}(),i=s;r&&(i+="/recovery"),await nr(e,`${t}-code-verifier`,i);let a=await dr(s);return[a,s===a?"plain":"s256"]}lr.promiseConstructor=Promise;let fr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;let gr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function mr(e){if(!gr.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function yr(e){if(!e.passkey)throw Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function br(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw 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 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 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 wr(e){return JSON.parse(JSON.stringify(e))}let _r=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),kr=[502,503,504,520,521,522,523,524,530];async function vr(e){if(!(e=>"object"==typeof e&&!!e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json)(e))throw new Ht(_r(e),0);if(kr.includes(e.status))throw new Ht(_r(e),e.status);let t;try{t=await e.json()}catch(e){throw new $t(_r(e),e)}let r,s=function(e){let t=e.headers.get(Et);if(!t||!t.match(fr))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}(e);if(s&&s.getTime()>=Rt["2024-01-01"].timestamp&&"object"==typeof t&&t&&"string"==typeof t.code?r=t.code:"object"==typeof t&&t&&"string"==typeof t.error_code&&(r=t.error_code),r){if("weak_password"===r)throw new Kt(_r(t),e.status,t.weak_password?.reasons||[]);if("session_not_found"===r)throw new xt}else if("object"==typeof t&&t&&"object"==typeof t.weak_password&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce(((e,t)=>e&&"string"==typeof t),!0))throw new Kt(_r(t),e.status,t.weak_password.reasons);throw new jt(_r(t),e.status||500,r)}async function Sr(e,t,r,s){let i=Object.assign({},s?.headers);i[Et]||(i[Et]=Rt["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let a=s?.query??{};s?.redirectTo&&(a.redirect_to=s.redirectTo);let n=await async function(e,t,r,s,i,a){let n,o=((e,t,r,s)=>{let i={method:e,headers:t?.headers||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))})(t,s,i,a);try{n=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new Ht(_r(e),0)}if(n.ok||await vr(n),s?.noResolveJson)return n;try{return await n.json()}catch(e){await vr(e)}}(e,t,r+(Object.keys(a).length?"?"+new URLSearchParams(a).toString():""),{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(n):{data:Object.assign({},n),error:null}}function Tr(e){let t=null;return function(e){return e.access_token&&e.refresh_token&&e.expires_in}(e)&&(t=Object.assign({},e),e.expires_at||(t.expires_at=function(e){return Math.round(Date.now()/1e3)+e}(e.expires_in))),{data:{session:t,user:e.user??e},error:null}}function Er(e){let t=Tr(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce(((e,t)=>e&&"string"==typeof t),!0)&&(t.data.weak_password=e.weak_password),t}function Rr(e){return{data:{user:e.user??e},error:null}}function Ar(e){return{data:e,error:null}}function Or(e){let{action_link:r,email_otp:s,hashed_token:i,redirect_to:a,verification_type:n}=e,o=t(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:r,email_otp:s,hashed_token:i,redirect_to:a,verification_type:n},user:Object.assign({},o)},error:null}}function Pr(e){return e}let jr=["global","local","others"];var Cr=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=ar(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=jr[0]){if(jr.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${jr.join(", ")}`);try{return await Sr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await Sr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Rr})}catch(e){if(Pt(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:r}=e,s=t(e,["options"]),i=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await Sr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Or,redirectTo:r?.redirectTo})}catch(e){if(Pt(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await Sr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Rr})}catch(e){if(Pt(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},r=await Sr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:Pr});if(r.error)throw r.error;let s=await r.json(),i=r.headers.get("x-total-count")??0,a=r.headers.get("link")?.split(",")??[];return a.length>0&&(a.forEach((e=>{let r=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);t[`${s}Page`]=r})),t.total=parseInt(i)),{data:Object.assign(Object.assign({},s),t),error:null}}catch(e){if(Pt(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){mr(e);try{return await Sr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Rr})}catch(e){if(Pt(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){mr(e);try{return await Sr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Rr})}catch(e){if(Pt(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){mr(e);try{return await Sr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Rr})}catch(e){if(Pt(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){mr(e.userId);try{let{data:t,error:r}=await Sr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _deleteFactor(e){mr(e.userId),mr(e.id);try{return{data:await Sr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},r=await Sr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:Pr});if(r.error)throw r.error;let s=await r.json(),i=r.headers.get("x-total-count")??0,a=r.headers.get("link")?.split(",")??[];return a.length>0&&(a.forEach((e=>{let r=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);t[`${s}Page`]=r})),t.total=parseInt(i)),{data:Object.assign(Object.assign({},s),t),error:null}}catch(e){if(Pt(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await Sr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await Sr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await Sr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await Sr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await Sr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await Sr(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>({data:{providers:e?.providers??[]},error:null})})}catch(e){if(Pt(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await Sr(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await Sr(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await Sr(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await Sr(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){yr(this.experimental),mr(e.userId);try{return await Sr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Pt(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){yr(this.experimental),mr(e.userId),mr(e.passkeyId);try{return await Sr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Pt(e))return{data:null,error:e};throw e}}};function $r(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let Ir={debug:!!(globalThis&&ir()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};var xr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Nr=class extends xr{},Lr=class extends xr{};async function Ur(e,t,r){Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s,i=new globalThis.AbortController;t>0&&(s=setTimeout((()=>{i.abort(),Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)}),t)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:i.signal},(async i=>{if(!i){if(0===t)throw Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new Nr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(Ir.debug)try{let e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(s),await r()}clearTimeout(s),Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await r()}finally{Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}))}catch(a){if(t>0&&clearTimeout(s),"AbortError"===a?.name&&t>0){if(i.signal.aborted)return Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e),console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then((()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},(async t=>{if(!t)return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r();Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,t.name);try{return await r()}finally{Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,t.name)}}))));throw Ir.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e),new Nr(`Lock "${e}" was released because another request stole it`)}throw a}}let Dr={};function Br(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function qr(e){let t=(new TextEncoder).encode(e);return"0x"+Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("")}var Mr=class extends Error{constructor({message:e,code:t,cause:r,name:s}){super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=s??(r instanceof Error?r.name:void 0)??"Unknown Error",this.code=t}},Hr=class extends Mr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function Wr({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Mr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===r.authenticatorSelection?.requireResidentKey)return new Mr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===r.authenticatorSelection?.userVerification)return new Mr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===r.authenticatorSelection?.userVerification)return new Mr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new Mr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new Mr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===r.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new Mr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new Mr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){let t=window.location.hostname;if(!Yr(t))return new Mr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rp.id!==t)return new Mr({message:`The RP ID "${r.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(r.user.id.byteLength<1||r.user.id.byteLength>64)return new Mr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new Mr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Mr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Kr({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Mr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new Mr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){let t=window.location.hostname;if(!Yr(t))return new Mr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new Mr({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new Mr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Mr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}let Fr=new class{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Jr(e){if(!e)throw Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:r,user:s,excludeCredentials:i}=e,a=t(e,["challenge","user","excludeCredentials"]),n=Zt(r).buffer,o=Object.assign(Object.assign({},s),{id:Zt(s.id).buffer}),h=Object.assign(Object.assign({},a),{challenge:n,user:o});if(i&&i.length>0){h.excludeCredentials=Array(i.length);for(let e=0;e0){n.allowCredentials=Array(s.length);for(let e=0;e"object"==typeof e&&!!e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(let i of e)if(i)for(let e in i){let a=i[e];if(void 0!==a)if(Array.isArray(a))s[e]=a;else if(r(a))s[e]=a;else if(t(a)){let r=s[e];t(r)?s[e]=rs(r,a):s[e]=rs(a)}else s[e]=a}return s}function ss(e,t){return rs(es,e,t||{})}var is=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){try{let{data:a,error:n}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!a)return{data:null,error:n};let o=s??Fr.createNewAbortSignal();if("create"===a.webauthn.type){let{user:e}=a.webauthn.credential_options.publicKey;if(!e.name){let t=r;if(t)e.name=`${e.id}:${t}`;else{let t=(await this.client.getUser()).data.user,r=t?.user_metadata?.name||t?.email||t?.id||"User";e.name=`${e.id}:${r}`}}e.displayName||=e.name}switch(a.webauthn.type){case"create":{let{data:t,error:r}=await Qr({publicKey:ss(a.webauthn.credential_options.publicKey,i?.create),signal:o});return t?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:t}},error:null}:{data:null,error:r}}case"request":{let t=function(e,t){return rs(ts,e,t||{})}(a.webauthn.credential_options.publicKey,i?.request),{data:r,error:s}=await Zr(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:t,signal:o}));return r?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(e){return Pt(e)?{data:null,error:e}:{data:null,error:new $t("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=(typeof window<"u"?window.location.hostname:void 0),rpOrigins:r=(typeof window<"u"?[window.location.origin]:void 0),signal:s}={}},i){if(!t)return{data:null,error:new Ot("rpId is required for WebAuthn authentication")};try{if(!Xr())return{data:null,error:new $t("Browser does not support WebAuthn",null)};let{data:a,error:n}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!a)return{data:null,error:n};let{webauthn:o}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){return Pt(e)?{data:null,error:e}:{data:null,error:new $t("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=(typeof window<"u"?window.location.hostname:void 0),rpOrigins:r=(typeof window<"u"?[window.location.origin]:void 0),signal:s}={}},i){if(!t)return{data:null,error:new Ot("rpId is required for WebAuthn registration")};try{if(!Xr())return{data:null,error:new $t("Browser does not support WebAuthn",null)};let{data:a,error:n}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then((t=>t.data?.all.find((t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)))).then((e=>e?this.client.mfa.unenroll({factorId:e?.id}):void 0)),{data:null,error:n};let{data:o,error:h}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});return o?this._verify({factorId:a.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:h}}catch(e){return Pt(e)?{data:null,error:e}:{data:null,error:new $t("Unexpected error in register",e)}}}};!function(){if("object"!=typeof globalThis)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)}}();let as={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Tt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function ns(e,t,r){return await r()}let os={};var hs=class e{get jwks(){return os[this.storageKey]?.jwks??{keys:[]}}set jwks(e){os[this.storageKey]=Object.assign(Object.assign({},os[this.storageKey]),{jwks:e})}get jwks_cached_at(){return os[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){os[this.storageKey]=Object.assign(Object.assign({},os[this.storageKey]),{cachedAt:e})}constructor(t){var r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let s=Object.assign(Object.assign({},as),t);if(this.storageKey=s.storageKey,this.instanceID=e.nextInstanceID[this.storageKey]??0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,"function"==typeof s.debug&&(this.logger=s.debug),this.instanceID>0&&rr()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.experimental=s.experimental??{},this.admin=new Cr({url:s.url,headers:s.headers,fetch:s.fetch,experimental:this.experimental}),this.url=s.url,this.headers=s.headers,this.fetch=ar(s.fetch),this.lock=s.lock||ns,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&rr()&&(null==globalThis?void 0:globalThis.navigator)?.locks?this.lock=Ur:this.lock=ns,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=-(2**53-1)),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new is(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:ir()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=$r(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=$r(this.memoryStorage)),rr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null==(r=this.broadcastChannel)||r.addEventListener("message",(async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}}))}s.skipAutoInitialize||this.initialize().catch((e=>{this._debug("#initialize()","error",e)}))}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${kt}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||=(async()=>await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._initialize())))(),await this.initializePromise}async _initialize(){try{let e={},t="none";if(rr()&&(e=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach(((e,r)=>{t[r]=e}))}catch{}return r.searchParams.forEach(((e,r)=>{t[r]=e})),t}(window.location.href),this._isImplicitGrantCallback(e)?t="implicit":await this._isPKCECallback(e)&&(t="pkce")),rr()&&this.detectSessionInUrl&&"none"!==t){let{data:r,error:s}=await this._getSessionFromURL(e,t);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),Bt(s)){let e=s.details?.code;if("identity_already_exists"===e||"identity_not_found"===e||"single_identity_not_deletable"===e)return{error:s}}return{error:s}}let{session:i,redirectType:a}=r;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout((async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)}),0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return Pt(e)?this._returnResult({error:e}):this._returnResult({error:new $t("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){try{let{data:t,error:r}=await Sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:Tr});if(r||!t)return this._returnResult({data:{user:null,session:null},error:r});let s=t.session,i=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",s)),this._returnResult({data:{user:i,session:s},error:null})}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e,a=null,n=null;"pkce"===this.flowType&&([a,n]=await pr(this.storage,this.storageKey)),t=await Sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:i?.emailRedirectTo,body:{email:r,password:s,data:i?.data??{},gotrue_meta_security:{captcha_token:i?.captchaToken},code_challenge:a,code_challenge_method:n},xform:Tr})}else{if(!("phone"in e))throw new Ut("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:i}=e;t=await Sr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:r,password:s,data:i?.data??{},channel:i?.channel??"sms",gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Tr})}}let{data:r,error:s}=t;if(s||!r)return await hr(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:s});let i=r.session,a=r.user;return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",i)),this._returnResult({data:{user:a,session:i},error:null})}catch(e){if(await hr(this.storage,`${this.storageKey}-code-verifier`),Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e;t=await Sr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Er})}else{if(!("phone"in e))throw new Ut("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:i}=e;t=await Sr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Er})}}let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new Lt;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){return await this._handleProviderSignIn(e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:e.options?.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,(async()=>this._exchangeCodeForSession(e)))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){let t,r;if("message"in e)t=e.message,r=e.signature;else{let s,{chain:i,wallet:a,statement:n,options:o}=e;if(rr())if("object"==typeof a)s=a;else{let e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");s=e.ethereum}else{if("object"!=typeof a||!o?.url)throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");s=a}let h=new URL(o?.url??window.location.href),l=await s.request({method:"eth_requestAccounts"}).then((e=>e)).catch((()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")}));if(!l||0===l.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let c=Br(l[0]),u=o?.signInWithEthereum?.chainId;u||=function(e){return parseInt(e,16)}(await s.request({method:"eth_chainId"})),t=function(e){let{chainId:t,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:a,notBefore:n,requestId:o,resources:h,scheme:l,uri:c,version:u}=e;if(!Number.isInteger(t))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!c)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==u)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${u}`);if(e.statement?.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let d=`${l?`${l}://${r}`:r} wants you to sign in with your Ethereum account:\n${Br(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`,p=`URI: ${c}\nVersion: ${u}\nChain ID: ${t}${a?`\nNonce: ${a}`:""}\nIssued At: ${i.toISOString()}`;if(s&&(p+=`\nExpiration Time: ${s.toISOString()}`),n&&(p+=`\nNot Before: ${n.toISOString()}`),o&&(p+=`\nRequest ID: ${o}`),h){let e="\nResources:";for(let t of h){if(!t||"string"!=typeof t)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${d}\n${p}`}({domain:h.host,address:c,statement:n,uri:h.href,version:"1",chainId:u,nonce:o?.signInWithEthereum?.nonce,issuedAt:o?.signInWithEthereum?.issuedAt??new Date,expirationTime:o?.signInWithEthereum?.expirationTime,notBefore:o?.signInWithEthereum?.notBefore,requestId:o?.signInWithEthereum?.requestId,resources:o?.signInWithEthereum?.resources}),r=await s.request({method:"personal_sign",params:[qr(t),c]})}try{let{data:s,error:i}=await Sr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:t,signature:r},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Tr});if(i)throw i;if(!s||!s.session||!s.user){let e=new Lt;return this._returnResult({data:{user:null,session:null},error:e})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({},s),error:i})}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){let t,r;if("message"in e)t=e.message,r=e.signature;else{let s,{chain:i,wallet:a,statement:n,options:o}=e;if(rr())if("object"==typeof a)s=a;else{let e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw 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.");s=e.solana}else{if("object"!=typeof a||!o?.url)throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");s=a}let h=new URL(o?.url??window.location.href);if("signIn"in s&&s.signIn){let e,i=await s.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},o?.signInWithSolana),{version:"1",domain:h.host,uri:h.href}),n?{statement:n}:null));if(Array.isArray(i)&&i[0]&&"object"==typeof i[0])e=i[0];else{if(!(i&&"object"==typeof i&&"signedMessage"in i&&"signature"in i))throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");e=i}if(!("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");t="string"==typeof e.signedMessage?e.signedMessage:(new TextDecoder).decode(e.signedMessage),r=e.signature}else{if(!("signMessage"in s&&"function"==typeof s.signMessage&&"publicKey"in s&&"object"==typeof s&&s.publicKey&&"toBase58"in s.publicKey&&"function"==typeof s.publicKey.toBase58))throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");t=[`${h.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...n?["",n,""]:[""],"Version: 1",`URI: ${h.href}`,`Issued At: ${o?.signInWithSolana?.issuedAt??(new Date).toISOString()}`,...o?.signInWithSolana?.notBefore?[`Not Before: ${o.signInWithSolana.notBefore}`]:[],...o?.signInWithSolana?.expirationTime?[`Expiration Time: ${o.signInWithSolana.expirationTime}`]:[],...o?.signInWithSolana?.chainId?[`Chain ID: ${o.signInWithSolana.chainId}`]:[],...o?.signInWithSolana?.nonce?[`Nonce: ${o.signInWithSolana.nonce}`]:[],...o?.signInWithSolana?.requestId?[`Request ID: ${o.signInWithSolana.requestId}`]:[],...o?.signInWithSolana?.resources?.length?["Resources",...o.signInWithSolana.resources.map((e=>`- ${e}`))]:[]].join("\n");let e=await s.signMessage((new TextEncoder).encode(t),"utf8");if(!(e&&e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");r=e}}try{let{data:s,error:i}=await Sr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:t,signature:tr(r)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Tr});if(i)throw i;if(!s||!s.session||!s.user){let e=new Lt;return this._returnResult({data:{user:null,session:null},error:e})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({},s),error:i})}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let[t,r]=(await or(this.storage,`${this.storageKey}-code-verifier`)??"").split("/");try{if(!t&&"pkce"===this.flowType)throw new Mt;let{data:s,error:i}=await Sr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:Tr});if(await hr(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let e=new Lt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("recovery"===r?"PASSWORD_RECOVERY":"SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:r??null}),error:i})}catch(e){if(await hr(this.storage,`${this.storageKey}-code-verifier`),Pt(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:a}=e,{data:n,error:o}=await Sr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:Tr});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!n||!n.session||!n.user){let e=new Lt;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:n,error:o})}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){try{if("email"in e){let{email:t,options:r}=e,s=null,i=null;"pkce"===this.flowType&&([s,i]=await pr(this.storage,this.storageKey));let{error:a}=await Sr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:t,data:r?.data??{},create_user:r?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:r?.captchaToken},code_challenge:s,code_challenge_method:i},redirectTo:r?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){let{phone:t,options:r}=e,{data:s,error:i}=await Sr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:r?.data??{},create_user:r?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:r?.captchaToken},channel:r?.channel??"sms"}});return this._returnResult({data:{user:null,session:null,messageId:s?.message_id},error:i})}throw new Ut("You must provide either an email or phone number.")}catch(e){if(await hr(this.storage,`${this.storageKey}-code-verifier`),Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){try{let t,r;"options"in e&&(t=e.options?.redirectTo,r=e.options?.captchaToken);let{data:s,error:i}=await Sr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:r}}),redirectTo:t,xform:Tr});if(i)throw i;if(!s)throw Error("An error occurred on token verification.");let a=s.session,n=s.user;return a?.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:n,session:a},error:null})}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){try{let t=null,r=null;"pkce"===this.flowType&&([t,r]=await pr(this.storage,this.storageKey));let s=await Sr(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:e.options?.redirectTo??void 0}),e?.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:t,code_challenge_method:r}),headers:this.headers,xform:Ar});return s.data?.url&&rr()&&!e.options?.skipBrowserRedirect&&window.location.assign(s.data.url),this._returnResult(s)}catch(e){if(await hr(this.storage,`${this.storageKey}-code-verifier`),Pt(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._reauthenticate()))}async _reauthenticate(){try{return await this._useSession((async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new xt;let{error:s}=await Sr(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})}))}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:i}=e,{error:a}=await Sr(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){let{phone:r,type:s,options:i}=e,{data:a,error:n}=await Sr(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:n})}throw new Ut("You must provide either an email or phone number and a type")}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>this._useSession((async e=>e))))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,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;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch{}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}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{return await e(await this.__loadSession())}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,t=await or(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=!!e.expires_at&&1e3*e.expires_at-Date.now(){if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){let t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,s)}return!t.value&&"string"==typeof r&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(e,r,s)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._getUser()));return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await Sr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Rr}):await this._useSession((async e=>{let{data:t,error:r}=e;if(r)throw r;return t.session?.access_token||this.hasCustomAuthorizationHeader?await Sr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:Rr}):{data:{user:null},error:new xt}}))}catch(e){if(Pt(e))return Nt(e)&&(await this._removeSession(),await hr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._updateUser(e,t)))}async _updateUser(e,t={}){try{return await this._useSession((async r=>{let{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new xt;let a=s.session,n=null,o=null;"pkce"===this.flowType&&null!=e.email&&([n,o]=await pr(this.storage,this.storageKey));let{data:h,error:l}=await Sr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:n,code_challenge_method:o}),jwt:a.access_token,xform:Rr});if(l)throw l;return a.user=h.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})}))}catch(e){if(await hr(this.storage,`${this.storageKey}-code-verifier`),Pt(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._setSession(e)))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new xt;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:a}=cr(e.access_token);if(a.exp&&(r=a.exp,s=r<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:s,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(Pt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._refreshSession(e)))}async _refreshSession(e){try{return await this._useSession((async t=>{if(!e){let{data:r,error:s}=t;if(s)throw s;e=r.session??void 0}if(!e?.refresh_token)throw new xt;let{data:r,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):r?this._returnResult({data:{user:r.user,session:r},error:null}):this._returnResult({data:{user:null,session:null},error:null})}))}catch(e){if(Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!rr())throw new Dt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Dt(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("pkce"===this.flowType)throw new qt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new Dt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new qt("No code detected.");let{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;let s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:t.redirectType??null},error:null}}let{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:a,expires_in:n,expires_at:o,token_type:h}=e;if(!(i&&n&&a&&h))throw new Dt("No session defined in URL");let l=Math.round(Date.now()/1e3),c=parseInt(n),u=l+c;o&&(u=parseInt(o));let d=u-l;1e3*d<=vt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${c}s`);let p=u-c;l-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,l):l-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,l);let{data:f,error:g}=await this._getUser(i);if(g)throw g;let m={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:c,expires_at:u,refresh_token:a,token_type:h,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:m,redirectType:e.type},error:null})}catch(e){if(Pt(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!(!e.access_token&&!e.error_description)}async _isPKCECallback(e){let t=await or(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>await this._signOut(e)))}async _signOut({scope:e}={scope:"global"}){return await this._useSession((async t=>{let{data:r,error:s}=t;if(s&&!Nt(s))return this._returnResult({error:s});let i=r.session?.access_token;if(i){let{error:t}=await this.admin.signOut(i,e);if(t&&(!Ct(t)||404!==t.status&&401!==t.status&&403!==t.status)&&!Nt(t))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await hr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})}))}onAuthStateChange(e){let t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>{this._emitInitialSession(t)}))})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession((async t=>{try{let{data:{session:r},error:s}=t;if(s)throw s;await(this.stateChangeEmitters.get(e)?.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(t){await(this.stateChangeEmitters.get(e)?.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),Nt(t)?console.warn(t):console.error(t)}}))}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await pr(this.storage,this.storageKey,!0));try{return await Sr(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await hr(this.storage,`${this.storageKey}-code-verifier`),Pt(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){try{let{data:e,error:t}=await this.getUser();if(t)throw t;return this._returnResult({data:{identities:e.user.identities??[]},error:null})}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){try{let{data:t,error:r}=await this._useSession((async t=>{let{data:r,error:s}=t;if(s)throw s;let i=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:!0});return await Sr(this.fetch,"GET",i,{headers:this.headers,jwt:r.session?.access_token??void 0})}));if(r)throw r;return rr()&&!e.options?.skipBrowserRedirect&&window.location.assign(t?.url),this._returnResult({data:{provider:e.provider,url:t?.url},error:null})}catch(t){if(Pt(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession((async t=>{try{let{error:r,data:{session:s}}=t;if(r)throw r;let{options:i,provider:a,token:n,access_token:o,nonce:h}=e,{data:l,error:c}=await Sr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:s?.access_token??void 0,body:{provider:a,id_token:n,access_token:o,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Tr});return c?this._returnResult({data:{user:null,session:null},error:c}):l&&l.session&&l.user?(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("USER_UPDATED",l.session)),this._returnResult({data:l,error:c})):this._returnResult({data:{user:null,session:null},error:new Lt})}catch(e){if(await hr(this.storage,`${this.storageKey}-code-verifier`),Pt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}))}async unlinkIdentity(e){try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)throw s;return await Sr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:r.session?.access_token??void 0})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await function(e,t){return new Promise(((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let s=await e(i);if(!t(i,null,s))return void r(s)}catch(e){if(!t(i,e))return void s(e)}})()}))}((async r=>(r>0&&await async function(e){return await new Promise((t=>{setTimeout((()=>t(null)),e)}))}(200*2**(r-1)),this._debug(t,"refreshing attempt",r),await Sr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Tr}))),((e,t)=>{let s=200*2**e;return t&&Wt(t)&&Date.now()+s-r{try{await r.callback(e,t)}catch(e){s.push(e)}}));if(await Promise.all(i),s.length>0){for(let e=0;ethis._autoRefreshTokenTick()),vt);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():typeof Deno<"u"&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout((async()=>{await this.initializePromise,await this._autoRefreshTokenTick()}),0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():typeof Deno<"u"&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}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{let e=Date.now();try{return await this._useSession((async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/vt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)}))}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}))}catch(e){if(!(e.isAcquireTimeout||e instanceof xr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!rr()||null==window||!window.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,(async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")})))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){let[e,t]=await pr(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(r?.queryParams){let e=new URLSearchParams(r.queryParams);s.push(e.toString())}return r?.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession((async t=>{let{data:r,error:s}=t;return s?this._returnResult({data:null,error:s}):await Sr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:r?.session?.access_token})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:n}=await Sr(this.fetch,"POST",`${this.url}/factors`,{body:i,headers:this.headers,jwt:r?.session?.access_token});return n?this._returnResult({data:null,error:n}):("totp"===e.factorType&&"totp"===a.type&&a?.totp?.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,(async()=>{try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Vr(e.webauthn.credential_response):zr(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:n}=await Sr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:r?.session?.access_token});return n?this._returnResult({data:null,error:n}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:n}))}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}))}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,(async()=>{try{return await this._useSession((async t=>{let{data:r,error:s}=t;if(s)return this._returnResult({data:null,error:s});let i=await Sr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:r?.session?.access_token});if(i.error)return i;let{data:a}=i;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Jr(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Gr(a.webauthn.credential_options.publicKey)})})}),error:null}}}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}))}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r={all:[],phone:[],totp:[],webauthn:[]};for(let t of e?.factors??[])r.all.push(t),"verified"===t.status&&r[t.factor_type].push(t);return{data:r,error:null}}async _getAuthenticatorAssuranceLevel(e){if(e)try{let{payload:t}=cr(e),r=null;t.aal&&(r=t.aal);let s=r,{data:{user:i},error:a}=await this.getUser(e);return a?this._returnResult({data:null,error:a}):(((i?.factors)?.filter((e=>"verified"===e.status))??[]).length>0&&(s="aal2"),{data:{currentLevel:r,nextLevel:s,currentAuthenticationMethods:t.amr||[]},error:null})}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:t},error:r}=await this.getSession();if(r)return this._returnResult({data:null,error:r});if(!t)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:s}=cr(t.access_token),i=null;s.aal&&(i=s.aal);let a=i;return(t.user.factors?.filter((e=>"verified"===e.status))??[]).length>0&&(a="aal2"),{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:s.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession((async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await Sr(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new xt})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession((async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new xt});let a=await Sr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&rr()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession((async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new xt});let a=await Sr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&rr()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession((async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await Sr(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new xt})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession((async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await Sr(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new xt})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find((t=>t.kid===e));if(r)return r;let s=Date.now();if(r=this.jwks.keys.find((t=>t.kid===e)),r&&this.jwks_cached_at+6e5>s)return r;let{data:i,error:a}=await Sr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return i.keys&&0!==i.keys.length&&(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find((t=>t.kid===e)),r)?r:null}async getClaims(e,t={}){try{let r=e;if(!r){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}let{header:s,payload:i,signature:a,raw:{header:n,payload:o}}=cr(r);t?.allowExpired||function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(i.exp);let h=s.alg&&!s.alg.startsWith("HS")&&s.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(s.kid,t?.keys?{keys:t.keys}:t?.jwks):null;if(!h){let{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:i,header:s,signature:a},error:null}}let l=function(e){switch(e){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 Error("Invalid alg claim")}}(s.alg),c=await crypto.subtle.importKey("jwk",h,l,!0,["verify"]);if(!await crypto.subtle.verify(l,c,a,er(`${n}.${o}`)))throw new Ft("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){yr(this.experimental);try{if(!Xr())return this._returnResult({data:null,error:new $t("Browser does not support WebAuthn",null)});let{data:t,error:r}=await this._startPasskeyAuthentication({options:{captchaToken:e?.options?.captchaToken}});if(r||!t)return this._returnResult({data:null,error:r});let{data:s,error:i}=await Zr({publicKey:Gr(t.options),signal:e?.options?.signal??Fr.createNewAbortSignal()});if(i||!s)return this._returnResult({data:null,error:i??new $t("WebAuthn ceremony failed",null)});let a=zr(s);return this._verifyPasskeyAuthentication({challengeId:t.challenge_id,credential:a})}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){yr(this.experimental);try{if(!Xr())return this._returnResult({data:null,error:new $t("Browser does not support WebAuthn",null)});let{data:t,error:r}=await this._startPasskeyRegistration();if(r||!t)return this._returnResult({data:null,error:r});let{data:s,error:i}=await Qr({publicKey:Jr(t.options),signal:e?.options?.signal??Fr.createNewAbortSignal()});if(i||!s)return this._returnResult({data:null,error:i??new $t("WebAuthn ceremony failed",null)});let a=Vr(s);return this._verifyPasskeyRegistration({challengeId:t.challenge_id,credential:a})}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){yr(this.experimental);try{return await this._useSession((async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new xt});let{data:s,error:i}=await Sr(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){yr(this.experimental);try{return await this._useSession((async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new xt});let{data:i,error:a}=await Sr(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){yr(this.experimental);try{let{data:t,error:r}=await Sr(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:e?.options?.captchaToken}}});return r?this._returnResult({data:null,error:r}):this._returnResult({data:t,error:null})}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){yr(this.experimental);try{let{data:t,error:r}=await Sr(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Tr});return r?this._returnResult({data:null,error:r}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){yr(this.experimental);try{return await this._useSession((async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new xt});let{data:s,error:i}=await Sr(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){yr(this.experimental);try{return await this._useSession((async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new xt});let{data:i,error:a}=await Sr(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){yr(this.experimental);try{return await this._useSession((async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new xt});let{error:i}=await Sr(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})}))}catch(e){if(Pt(e))return this._returnResult({data:null,error:e});throw e}}};hs.nextInstanceID={};var ls=hs,cs=Cr,us=ls,ds=class extends us{constructor(e){super(e)}},ps=class{constructor(e,t,r){this.supabaseUrl=e,this.supabaseKey=t;let s=function(e){let t=e?.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(function(e){return e.endsWith("/")?e:e+"/"}(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a=function(e,t){let{db:r,auth:s,realtime:i,global:a}=e,{db:n,auth:o,realtime:h,global:l}=t,c={db:{...n,...r},auth:{...o,...s},realtime:{...h,...i},storage:{},global:{...l,...a,headers:{...l?.headers??{},...a?.headers??{}}},accessToken:async()=>""};return e.accessToken?c.accessToken=e.accessToken:delete c.accessToken,c}(r??{},{db:yt,realtime:wt,auth:{...bt,storageKey:i},global:mt});this.storageKey=a.auth.storageKey??"",this.headers=a.global.headers??{},a.accessToken?(this.accessToken=a.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(a.auth??{},this.headers,a.global.fetch),this.fetch=_t(t,this._getAccessToken.bind(this),a.global.fetch),this.realtime=this._initRealtimeClient({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch,...a.realtime}),this.accessToken&&Promise.resolve(this.accessToken()).then((e=>this.realtime.setAuth(e))).catch((e=>console.warn("Failed to set initial Realtime auth token:",e))),this.rest=new T(new URL("rest/v1",s).href,{headers:this.headers,schema:a.db.schema,fetch:this.fetch,timeout:a.db.timeout,urlLengthLimit:a.db.urlLengthLimit}),this.storage=new ft(this.storageUrl.href,this.headers,this.fetch,r?.storage),a.accessToken||this._listenForAuthEvents()}get functions(){return new o(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){if(this.accessToken)return await this.accessToken();let{data:e}=await this.auth.getSession();return e.session?.access_token??this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:a,flowType:n,lock:o,debug:h,throwOnError:l,experimental:c},u,d){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ds({url:this.authUrl.href,headers:{...p,...u},storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:n,lock:o,debug:h,throwOnError:l,experimental:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some((e=>"authorization"===e.toLowerCase()))})}_initRealtimeClient(e){return new Se(this.realtimeUrl.href,{...e,params:{apikey:this.supabaseKey,...e?.params}})}_listenForAuthEvents(){return this.auth.onAuthStateChange(((e,t)=>{this._handleTokenChanged(e,"CLIENT",t?.access_token)}))}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};return function(){if(typeof window<"u")return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18}()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217"),e.AuthAdminApi=cs,e.AuthApiError=jt,e.AuthClient=us,e.AuthError=Ot,e.AuthImplicitGrantRedirectError=Dt,e.AuthInvalidCredentialsError=Ut,e.AuthInvalidJwtError=Ft,e.AuthInvalidTokenResponseError=Lt,e.AuthPKCECodeVerifierMissingError=Mt,e.AuthPKCEGrantCodeExchangeError=qt,e.AuthRetryableFetchError=Ht,e.AuthSessionMissingError=xt,e.AuthUnknownError=$t,e.AuthWeakPasswordError=Kt,e.CustomAuthError=It,Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return r}}),e.FunctionsError=s,e.FunctionsFetchError=i,e.FunctionsHttpError=n,e.FunctionsRelayError=a,e.GoTrueAdminApi=Cr,e.GoTrueClient=ls,e.NavigatorLockAcquireTimeoutError=Nr,e.PostgrestError=u,e.REALTIME_CHANNEL_STATES=be,Object.defineProperty(e,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(e,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return fe}}),Object.defineProperty(e,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return me}}),e.RealtimeChannel=we,e.RealtimeClient=Se,e.RealtimePresence=pe,e.SIGN_OUT_SCOPES=jr,e.StorageApiError=De,e.SupabaseClient=ps,e.WebSocketFactory=E,e.createClient=(e,t,r)=>new ps(e,t,r),e.isAuthApiError=Ct,e.isAuthError=Pt,e.isAuthImplicitGrantRedirectError=Bt,e.isAuthPKCECodeVerifierMissingError=function(e){return Pt(e)&&"AuthPKCECodeVerifierMissingError"===e.name},e.isAuthRetryableFetchError=Wt,e.isAuthSessionMissingError=Nt,e.isAuthWeakPasswordError=function(e){return Pt(e)&&"AuthWeakPasswordError"===e.name},e.lockInternals=Ir,e.navigatorLock=Ur,e.processLock=async function(e,t,r){let s=Dr[e]??Promise.resolve(),i=(async()=>{try{return await s,null}catch{return null}})(),a=(async()=>{let s=null;try{let r=t>=0?new Promise(((r,i)=>{s=setTimeout((()=>{console.warn(`@supabase/gotrue-js: Lock "${e}" acquisition timed out after ${t}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),i(new Lr(`Acquiring process lock with name "${e}" timed out`))}),t)})):null;await Promise.race([i,r].filter((e=>e))),null!==s&&clearTimeout(s)}catch(e){if(null!==s&&clearTimeout(s),e&&e.isAcquireTimeout)throw e}return await r()})();return Dr[e]=(async()=>{try{return await a}catch(e){if(e&&e.isAcquireTimeout){try{await s}catch{}return null}throw e}})(),await a},e}({}); //# sourceMappingURL=/sm/0c3c96ca851916e8728e2c207f3423f5f249e4386bac712188c3f6c1d69e3bfb.map