/** * Minified by jsDelivr using Terser v5.39.0. * Original file: /npm/@supabase/supabase-js@2.106.0/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))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return r(this,arguments,void 0,(function*(e,t={}){let r,s;try{let{headers:i,method:l,body:h,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)),h&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)?typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",f=h):"string"==typeof h?(d["Content-Type"]="text/plain",f=h):typeof FormData<"u"&&h instanceof FormData?f=h:(d["Content-Type"]="application/json",f=JSON.stringify(h)):f=!h||"string"==typeof h||typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer||typeof FormData<"u"&&h instanceof FormData?h:JSON.stringify(h);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:l||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),i),body:f,signal:m}).catch((e=>{throw new a(e)})),b=y.headers.get("x-relay-error");if(b&&"true"===b)throw new n(y);if(!y.ok)throw new o(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 o||e instanceof n?e.context:void 0}}finally{r&&clearTimeout(r)}}))}};let h=e=>Math.min(1e3*2**e,3e4),c=[520,503],u=["GET","HEAD","OPTIONS"];var d=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 p(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 f(e,t,r,s){return!(!s||r>=3||!u.includes(e)||!c.includes(t))}var g=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||!u.includes(r.method))throw t;if(r.retryEnabled&&e<3){let t=h(e);e++,await p(t,r.signal);continue}throw t}if(!f(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 p(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)/),l=e.headers.get("content-range")?.split("/");o&&l&&l.length>1&&(i=parseInt(l[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 d(r)}return{success:null===r,error:r,data:s,count:i,status:a,statusText:n}}returns(){return this}overrideTypes(){return this}},m=class extends g{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 y=RegExp("[,()]");var b=class extends m{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&&y.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&&y.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}},w=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:l}=this.cloneRequestState();return o.searchParams.set("select",n),s&&l.append("Prefer",`count=${s}`),new b({method:i,url:o,headers:l,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 b({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 b({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 b({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 b({method:"DELETE",url:t,headers:r,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function _(e){return _="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},_(e)}function k(e){var t=function(e,t){if("object"!=_(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=_(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==_(t)?t:t+""}function v(e,t,r){return(t=k(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function S(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 T(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,T(T({},t),{},{signal:r.signal})).finally((()=>{clearTimeout(s),a.removeEventListener("abort",i)}))}return o(e,T(T({},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 w(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}`),l=e=>"object"==typeof e&&!!e&&(!Array.isArray(e)||e.some(l)),h=r&&Object.values(t).some(l);h?(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 h?c.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&c.set("Prefer",`count=${i}`),new b({method:a,url:o,headers:c,schema:this.schemaName,body:n,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},R=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};let e=globalThis;if(typeof globalThis<"u"&&void 0!==e.WebSocket)return{type:"native",wsConstructor:e.WebSocket};let t=typeof global<"u"?global:void 0;if(t&&void 0!==t.WebSocket)return{type:"native",wsConstructor:t.WebSocket};if(typeof globalThis<"u"&&void 0!==e.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"&&e.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 r=globalThis.process;if(r){let e=r.versions;if(e&&e.node){let t=e.node,r=parseInt(t.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",wsConstructor: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.wsConstructor)return e.wsConstructor;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 A={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},O={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},P={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var j,C=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):{},l=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(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let h=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+i.length+s.length+n.length+l.length,c=new ArrayBuffer(this.HEADER_LENGTH+h),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++,l.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(l,(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,l=r.decode(e.slice(o,o+s));o+=s;let h=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:h,payload:d};return a>0&&(p.meta=JSON.parse(c)),{join_ref:null,ref:null,topic:l,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"}(j||={});let I=(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)?x(i,a):N(a)},x=(e,t)=>{if("_"===e.charAt(0))return B(t,e.slice(1,e.length));switch(e){case j.bool:return L(t);case j.float4:case j.float8:case j.int2:case j.int4:case j.int8:case j.numeric:case j.oid:return U(t);case j.json:case j.jsonb:return D(t);case j.timestamp:return q(t);case j.abstime:case j.date:case j.daterange:case j.int4range:case j.int8range:case j.money:case j.reltime:case j.text:case j.time:case j.timestamptz:case j.timetz:case j.tsrange:case j.tstzrange:default:return N(t)}},N=e=>e,L=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},U=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},D=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e},B=(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=>x(t,e)))}return e},q=e=>"string"==typeof e?e.replace(" ","T"):e,M=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 H,W=e=>"function"==typeof e?e:function(){return e},K=typeof self<"u"?self:null,F=typeof window<"u"?window:null,J=K||F||globalThis,G=0,V=1,z=2,Y=3,X={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Q={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Z="longpoll",ee="websocket",te=4,re="base64url.bearer.phx.",se=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})}},ie=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))}},ae=class{constructor(e,t,r){this.state=X.closed,this.topic=e,this.params=W(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new se(this,Q.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ie((()=>{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=X.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((e=>e.send())),this.pushBuffer=[]})),this.joinPush.receive("error",(e=>{this.state=X.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=X.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=X.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 se(this,Q.leave,W({}),this.timeout).send(),this.state=X.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.on(Q.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=X.closed,this.bindings=[]}onClose(e){this.on(Q.close,e)}onError(e){return this.on(Q.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 se(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=X.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Q.close,"leave")},r=new se(this,Q.leave,W({}),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=X.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;el.abort()),i),o.signal=l.signal),J.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)})),l}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===te&&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)}`}},oe=class{constructor(e,t){t&&2===t.length&&t[1].startsWith(re)&&(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=G,setTimeout((()=>this.poll()),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+ee),"$1/"+Z)}endpointURL(){return ne.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=G}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===V||this.readyState===G}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=V,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=Y;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=ne.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)}},le=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)),l=r.metas.filter((e=>s.indexOf(e.phx_ref)<0));o.length>0&&(a[e]=t,a[e].metas=o),l.length>0&&(n[e]=this.clone(r),n[e].metas=l)}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),l=new DataView(o),h=0;l.setUint8(h++,this.KINDS.push),l.setUint8(h++,t.length),l.setUint8(h++,r.length),l.setUint8(h++,i.length),l.setUint8(h++,s.length),Array.from(t,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(r,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(i,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(s,(e=>l.setUint8(h++,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 l=r.decode(e.slice(n,n+i));n+=i;let h=r.decode(e.slice(n,n+a));return n+=a,{join_ref:o,ref:null,topic:l,event:h,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,l=r.decode(e.slice(o,o+s));o+=s;let h=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:l,ref:h,topic:c,event:Q.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)}}},ce=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||J.WebSocket||oe,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=J&&J.sessionStorage}catch{}this.sessionStore=t.sessionStorage||r,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===oe?(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder):(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder);let s=null;F&&F.addEventListener&&(F.addEventListener("pagehide",(e=>{this.conn&&(this.disconnect(),s=this.connectClock)})),F.addEventListener("pageshow",(e=>{s===this.connectClock&&(s=null,this.connect())})),F.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=W(t.params||{}),this.endPoint=`${e}/${ee}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ie((()=>{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 oe}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=ne.appendParams(ne.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=W(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==oe?this.connectWithFallback(oe,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===oe?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix",`${re}${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!==Y?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(Q.error,e)}))}connectionState(){switch(this.conn&&this.conn.readyState){case G:return"connecting";case V:return"open";case z: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 ae(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())}},ue=class e{constructor(t,r){let s=function(e){return e?.events&&{events:e.events}}(r);this.presence=new le(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]=de(s),t}),{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:pe(t),newPresences:de(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:pe(t),leftPresences:de(r)}}};function de(e){return e.metas.map((e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)))}function pe(e){return e?.metas?de(e):[]}!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(H||={});var fe=class{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new ue(this.channel.channelAdapter,t)}};var ge,me,ye,be=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===A.joined}isJoined(){return this.state===A.joined}isJoining(){return this.state===A.joining}isClosed(){return this.state===A.closed}isLeaving(){return this.state===A.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"}(ge||={}),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(me||={}),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(ye||={});let we=A;var _e=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 be(this.socket.socketAdapter,e,this.params),this.presence=new fe(this),this._onClose((()=>{this.socket._remove(this)})),this._updateFilterTransform(),this.broadcastEndpointURL=M(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[me.PRESENCE]&&this.bindings[me.PRESENCE].length>0||!0===this.params.config.presence?.enabled,o={},l={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?.(ye.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?.(ye.CLOSED))),this.updateJoinPayload(Object.assign({config:l},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?.(ye.SUBSCRIBED)})).receive("error",(t=>{this.state=A.errored;let r=Object.values(t).join(", ")||"error";e?.(ye.CHANNEL_ERROR,Error(r,{cause:t}))})).receive("timeout",(()=>{e?.(ye.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 e instanceof Error&&"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}=O;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=I(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=I(e.columns,e.old_record)),t}},ke=class{constructor(e,t){this.socket=new ce(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()==P.connecting}isDisconnecting(){return this.socket.connectionState()==P.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};let ve=25e3,Se=[1e3,2e3,5e3,1e4];function Te(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return function(){let e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem:t=>e.has(t)?e.get(t):null,key:t=>Array.from(e.keys())[t]??null,removeItem(t){e.delete(t)},setItem(t,r){e.set(t,String(r))}}}()}var Ee=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 C,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 ke(e,this._initializeOptions(t)),this.httpEndpoint=M(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()||P.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 _e(`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.106.0"};t&&e.updateJoinPayload(r),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(O.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??ve,this._disconnectOnEmptyChannelsAfterMs=e?.disconnectOnEmptyChannelsAfterMs??2*(e?.heartbeatIntervalMs??ve),t.transport=e?.transport??R.getWebSocketConstructor(),t.params=e?.params,t.logger=e?.logger,t.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),t.sessionStorage=e?.sessionStorage??Te(),t.reconnectAfterMs=e?.reconnectAfterMs??(e=>Se[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()}},Re=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 Ae(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),l=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),h=await t(o,{method:r,headers:{...a?{"Content-Type":"application/json"}:{},...l,...n},body:a?JSON.stringify(a):void 0}),c=await h.text(),u=(h.headers.get("content-type")||"").includes("application/json"),d=u&&c?JSON.parse(c):c;if(!h.ok){let e=u?d:void 0,t=e?.error;throw new Re(t?.message??`Request failed with status ${h.status}`,{status:h.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:h.status,headers:h.headers,data:d}}}}function Oe(e){return e.join("")}var Pe=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Oe(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/${Oe(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Oe(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Oe(e.namespace)}`}),!0}catch(e){if(e instanceof Re&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Re&&409===e.status)return;throw e}}};function je(e){return e.join("")}var Ce=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/${je(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/${je(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/${je(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/${je(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/${je(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/${je(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Re&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Re&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},Ie=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`),this.client=Ae({baseUrl:e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new Pe(this.client,t),this.tableOps=new Ce(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 $e(e){return $e="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},$e(e)}function xe(e){var t=function(e,t){if("object"!=$e(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=$e(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==$e(t)?t:t+""}function Ne(e,t,r){return(t=xe(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Le(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 Ue(e){for(var t=1;t{if(Array.isArray(e))return e.map((e=>We(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]=We(r)})),t},Ke=e=>{if("object"==typeof e&&e){let t=e;if("string"==typeof t.msg)return t.msg;if("string"==typeof t.message)return t.message;if("string"==typeof t.error_description)return t.error_description;if("string"==typeof t.error)return t.error;if("object"==typeof t.error&&null!==t.error){let e=t.error;if("string"==typeof e.message)return e.message}}return JSON.stringify(e)},Fe=(e,t,r,s)=>{let i={method:e,headers:t?.headers||{}};if("GET"===e||"HEAD"===e||!s)return Ue(Ue({},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=He(r,"Content-Type",e??"application/json"),i.body=JSON.stringify(s)}else i.body=s;return t?.duplex&&(i.duplex=t.duplex),Ue(Ue({},i),r)};async function Je(e,t,r,s,i,a,n){return new Promise(((o,l)=>{e(r,Fe(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&&"json"in e&&"function"==typeof e.json){let r=e,i=parseInt(String(r.status),10);Number.isFinite(i)||(i=500),r.json().then((e=>{let r=e?.statusCode||e?.code||i+"";t(new qe(Ke(e),i,r,s))})).catch((()=>{let e=i+"";t(new qe(r.statusText||`HTTP ${i} error`,i,e,s))}))}else t(new Me(Ke(e),e,s))})(e,l,0,n)))}))}function Ge(e="storage"){return{get:async(t,r,s,i)=>Je(t,"GET",r,s,i,void 0,e),post:async(t,r,s,i,a)=>Je(t,"POST",r,i,a,s,e),put:async(t,r,s,i,a)=>Je(t,"PUT",r,i,a,s,e),head:async(t,r,s,i)=>Je(t,"HEAD",r,Ue(Ue({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,s,i,a)=>Je(t,"DELETE",r,i,a,s,e)}}let{get:Ve,post:ze,put:Ye,head:Xe,remove:Qe}=Ge("storage"),Ze=Ge("vectors");var et=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=He(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Be(e))return{data:null,error:e};throw e}}};let tt;tt=Symbol.toStringTag;var rt=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[tt]="StreamDownloadBuilder",this.promise=null}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 this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Be(e))return{data:null,error:e};throw e}}};let st;st=Symbol.toStringTag;var it=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[st]="BlobDownloadBuilder",this.promise=null}asStream(){return new rt(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(Be(e))return{data:null,error:e};throw e}}};let at={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},nt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var ot=class extends et{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=Ue(Ue({},nt),s),o=Ue(Ue({},i.headers),"POST"===e&&{"x-upsert":String(n.upsert)}),l=n.metadata;if(typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",n.cacheControl),l&&a.append("metadata",i.encodeMetadata(l)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",n.cacheControl),l&&!a.has("metadata")&&a.append("metadata",i.encodeMetadata(l))):(a=r,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(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=He(o,e,t);let h=i._removeEmptyFolders(t),c=i._getFinalPath(h),u=await("PUT"==e?Ye:ze)(i.fetch,`${i.url}/object/${c}`,a,Ue({headers:o},n?.duplex?{duplex:n.duplex}:{}));return{path:h,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=Ue(Ue({},nt),s),n=Ue(Ue({},i.headers),{"x-upsert":String(t.upsert)}),l=t.metadata;if(typeof Blob<"u"&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),l&&e.append("metadata",i.encodeMetadata(l)),e.append("",r)):typeof FormData<"u"&&r instanceof FormData?(e=r,e.has("cacheControl")||e.append("cacheControl",t.cacheControl),l&&!e.has("metadata")&&e.append("metadata",i.encodeMetadata(l))):(e=r,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType,l&&(n["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(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=He(n,e,t);return{path:a,fullPath:(await Ye(i.fetch,o.toString(),e,Ue({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=Ue({},r.headers);t?.upsert&&(i["x-upsert"]="true");let a=await ze(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 De("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 ze(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 ze(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 ze(s.fetch,`${s.url}/object/sign/${i}`,Ue({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 l=o.toString();return{signedUrl:encodeURI(`${s.url}${n.signedURL}${l?`&${l}`:""}`)}}))}async createSignedUrls(e,t,r){var s=this;return s.handleOperation((async()=>{let i=await ze(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=>Ue(Ue({},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 it((()=>Ve(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()=>We(await Ve(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers}))))}async exists(e){var t=this;let r=t._getFinalPath(e);try{return await Xe(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Be(e)){let t=e instanceof qe?e.status:e instanceof Me?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 Qe(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=Ue(Ue(Ue({},at),t),{},{prefix:e||""});return await ze(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=Ue({},e);return await ze(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 lt={"X-Client-Info":"storage-js/2.106.0"};var ht=class extends et{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(/\/$/,""),Ue(Ue({},lt),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation((async()=>{let r=t.listBucketOptionsToQueryString(e);return await Ve(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})}))}async getBucket(e){var t=this;return t.handleOperation((async()=>await Ve(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers})))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation((async()=>await ze(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 Ye(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 ze(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers})))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Qe(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():""}},ct=class extends et{constructor(e,t={},r){super(e.replace(/\/$/,""),Ue(Ue({},lt),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation((async()=>await ze(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 Ve(t.fetch,i,{headers:t.headers})}))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Qe(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 De("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 Ie({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}})}},ut=class extends et{constructor(e,t={},r){super(e.replace(/\/$/,""),Ue(Ue({},lt),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation((async()=>await Ze.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{}))}async getIndex(e,t){var r=this;return r.handleOperation((async()=>await Ze.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})))}async listIndexes(e){var t=this;return t.handleOperation((async()=>await Ze.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers})))}async deleteIndex(e,t){var r=this;return r.handleOperation((async()=>await Ze.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{}))}},dt=class extends et{constructor(e,t={},r){super(e.replace(/\/$/,""),Ue(Ue({},lt),{},{"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 Ze.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{}))}async getVectors(e){var t=this;return t.handleOperation((async()=>await Ze.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 Ze.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers})))}async queryVectors(e){var t=this;return t.handleOperation((async()=>await Ze.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 Ze.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{}))}},pt=class extends et{constructor(e,t={},r){super(e.replace(/\/$/,""),Ue(Ue({},lt),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation((async()=>await Ze.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{}))}async getBucket(e){var t=this;return t.handleOperation((async()=>await Ze.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers})))}async listBuckets(e={}){var t=this;return t.handleOperation((async()=>await Ze.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers})))}async deleteBucket(e){var t=this;return t.handleOperation((async()=>await Ze.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{}))}},ft=class extends pt{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new gt(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)}},gt=class extends ut{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,Ue(Ue({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,Ue(Ue({},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 mt(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},mt=class extends dt{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,Ue(Ue({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,Ue(Ue({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,Ue(Ue({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,Ue(Ue({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,Ue(Ue({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},yt=class extends ht{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new ot(this.url,this.headers,e,this.fetch)}get vectors(){return new ft(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new ct(this.url+"/iceberg",this.headers,this.fetch)}};let bt="";bt=typeof Deno<"u"?"deno":typeof document<"u"?"web":typeof navigator<"u"&&"ReactNative"===navigator.product?"react-native":"node";let wt={headers:{"X-Client-Info":`supabase-js-${bt}/2.106.0`}},_t={schema:"public"},kt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},vt={},St={enabled:!1,respectSamplingDecision:!0},Tt=null;function Et(){return r(this,void 0,void 0,(function*(){try{let e=yield(null===Tt&&(Tt=import("@opentelemetry/api").catch((()=>null))),Tt);if(!e||!e.propagation||!e.context)return null;let t={};e.propagation.inject(e.context.active(),t);let r=t.traceparent;return r?{traceparent:r,tracestate:t.tracestate,baggage:t.baggage}:null}catch{return null}}))}function Rt(e,t){if(t===e)return!0;if(t.startsWith("*.")){let r=t.slice(2);if(e.endsWith(r)&&(e===r||e.endsWith("."+r)))return!0}return!1}let At=(e,t,r,s,i)=>{let a=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(s),n=Headers,o=!0===i?.enabled,l=!1!==i?.respectSamplingDecision,h=o?function(e){let t=[];try{let r=new URL(e);t.push(r.hostname)}catch{}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}(t):null;return async(t,s)=>{let i=await r()??e,o=new n(s?.headers);if(o.has("apikey")||o.set("apikey",e),o.has("Authorization")||o.set("Authorization",`Bearer ${i}`),h){let e=await async function(e,t,r){if(!function(e,t){if(!e||!t||0===t.length)return!1;let r;if(e instanceof URL)r=e;else try{r=new URL(e)}catch{return!1}for(let e of t)try{if("string"==typeof e){if(Rt(r.hostname,e))return!0}else if(e instanceof RegExp){if(e.test(r.hostname))return!0}else if("function"==typeof e&&e(r))return!0}catch{continue}return!1}("string"==typeof e||e instanceof URL?e:e.url,t))return null;let s=await Et();if(!s||!s.traceparent)return null;if(r){let e=function(e){if(!e||"string"!=typeof e)return null;let t=e.split("-");if(4!==t.length)return null;let[r,s,i,a]=t;if(2!==r.length||32!==s.length||16!==i.length||2!==a.length)return null;let n=/^[0-9a-f]+$/i;return n.test(r)&&n.test(s)&&n.test(i)&&n.test(a)&&"00000000000000000000000000000000"!==s&&"0000000000000000"!==i?{version:r,traceId:s,parentId:i,traceFlags:a,isSampled:!(1&~parseInt(a,16))}:null}(s.traceparent);if(e&&!e.isSampled)return null}return s}(t,h,l);e&&(e.traceparent&&!o.has("traceparent")&&o.set("traceparent",e.traceparent),e.tracestate&&!o.has("tracestate")&&o.set("tracestate",e.tracestate),e.baggage&&!o.has("baggage")&&o.set("baggage",e.baggage))}return a(t,{...s,headers:o})}};function Ot(e){return"boolean"==typeof e?{enabled:e}:e}let Pt="2.106.0",jt=3e4,Ct=3*jt,It={"X-Client-Info":`gotrue-js/${Pt}`},$t="X-Supabase-Api-Version",xt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Nt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;var Lt=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 Ut(e){return"object"==typeof e&&!!e&&"__isAuthError"in e}var Dt=class extends Lt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Bt(e){return Ut(e)&&"AuthApiError"===e.name}var qt=class extends Lt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Mt=class extends Lt{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},Ht=class extends Mt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Wt(e){return Ut(e)&&"AuthSessionMissingError"===e.name}var Kt=class extends Mt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ft=class extends Mt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Jt=class extends Mt{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 Gt(e){return Ut(e)&&"AuthImplicitGrantRedirectError"===e.name}var Vt=class extends Mt{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})}},zt=class extends Mt{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 Yt=class extends Mt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Xt(e){return Ut(e)&&"AuthRetryableFetchError"===e.name}var Qt=class extends Mt{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 Zt=class extends Mt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};let er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tr=" \t\n\r=".split(""),rr=(()=>{let e=Array(128);for(let t=0;t=6;)r(er[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(er[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function ir(e,t,r){let s=rr[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 ar(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 or(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}nr(s,t)}}(e,(e=>t.push(e))),new Uint8Array(t)}function hr(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach((e=>sr(e,r,s))),sr(null,r,s),t.join("")}let cr=()=>typeof window<"u"&&typeof document<"u",ur={tested:!1,writable:!1},dr=()=>{if(!cr())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch{return!1}if(ur.tested)return ur.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),ur.tested=!0,ur.writable=!0}catch{ur.tested=!0,ur.writable=!1}return ur.writable};let pr=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),fr=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},gr=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return null}},mr=async(e,t)=>{await e.removeItem(t)};var yr=class e{constructor(){this.promise=new e.promiseConstructor(((e,t)=>{this.resolve=e,this.reject=t}))}};function br(e){let t=e.split(".");if(3!==t.length)throw new Zt("Invalid JWT structure");for(let e=0;eString.fromCharCode(e))).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function kr(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,wr).join("")}(),i=s;r&&(i+="/recovery"),await fr(e,`${t}-code-verifier`,i);let a=await _r(s);return[a,s===a?"plain":"s256"]}yr.promiseConstructor=Promise;let vr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;let Sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Tr(e){if(!Sr.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Er(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 Rr(){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 Ar(e){return JSON.parse(JSON.stringify(e))}let Or=e=>{if("object"==typeof e&&e){let t=e;if("string"==typeof t.msg)return t.msg;if("string"==typeof t.message)return t.message;if("string"==typeof t.error_description)return t.error_description;if("string"==typeof t.error)return t.error}return JSON.stringify(e)},Pr=[502,503,504,520,521,522,523,524,530];async function jr(e){if(!(e=>"object"==typeof e&&!!e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json)(e))throw new Yt(Or(e),0);if(Pr.includes(e.status))throw new Yt(Or(e),e.status);let t;try{t=await e.json()}catch(e){throw new qt(Or(e),e)}let r,s=function(e){let t=e.headers.get($t);if(!t||!t.match(vr))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}(e);if(s&&s.getTime()>=xt["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 Qt(Or(t),e.status,t.weak_password?.reasons||[]);if("session_not_found"===r)throw new Ht}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 Qt(Or(t),e.status,t.weak_password.reasons);throw new Dt(Or(t),e.status||500,r)}async function Cr(e,t,r,s){let i=Object.assign({},s?.headers);i[$t]||(i[$t]=xt["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 Yt(Or(e),0)}if(n.ok||await jr(n),s?.noResolveJson)return n;try{return await n.json()}catch(e){await jr(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 Ir(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??null},error:null}}function $r(e){let t=Ir(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 xr(e){return{data:{user:e.user??e},error:null}}function Nr(e){return{data:e,error:null}}function Lr(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 Ur(e){return e}let Dr=["global","local","others"];var Br=class{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=pr(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=Dr[0]){if(Dr.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${Dr.join(", ")}`);try{return await Cr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await Cr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:xr})}catch(e){if(Ut(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 Cr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Lr,redirectTo:r?.redirectTo})}catch(e){if(Ut(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await Cr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:xr})}catch(e){if(Ut(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},r=await Cr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:Ur});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(Ut(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Tr(e);try{return await Cr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:xr})}catch(e){if(Ut(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Tr(e);try{return await Cr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:xr})}catch(e){if(Ut(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Tr(e);try{return await Cr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:xr})}catch(e){if(Ut(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Tr(e.userId);try{let{data:t,error:r}=await Cr(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(Ut(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Tr(e.userId),Tr(e.id);try{return{data:await Cr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},r=await Cr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??"",per_page:(e?.perPage)?.toString()??""},xform:Ur});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(Ut(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await Cr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await Cr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await Cr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await Cr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await Cr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await Cr(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>({data:{providers:e?.providers??[]},error:null})})}catch(e){if(Ut(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await Cr(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await Cr(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await Cr(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await Cr(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){Er(this.experimental),Tr(e.userId);try{return await Cr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ut(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){Er(this.experimental),Tr(e.userId),Tr(e.passkeyId);try{return await Cr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Ut(e))return{data:null,error:e};throw e}}};function qr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let Mr={debug:!!(globalThis&&dr()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};var Hr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Wr=class extends Hr{},Kr=class extends Hr{};async function Fr(e,t,r){Mr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s,i=new globalThis.AbortController;t>0&&(s=setTimeout((()=>{i.abort(),Mr.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 Mr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new Wr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(Mr.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),Mr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await r()}finally{Mr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}))}catch(a){if(t>0&&clearTimeout(s),"object"==typeof a&&a&&"name"in a&&"AbortError"===a.name&&t>0){if(i.signal.aborted)return Mr.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();Mr.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,t.name);try{return await r()}finally{Mr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,t.name)}}))));throw Mr.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e),new Wr(`Lock "${e}" was released because another request stole it`)}throw a}}let Jr={};function Gr(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Vr(e){let t=(new TextEncoder).encode(e);return"0x"+Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("")}var zr=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}toJSON(){return{name:this.name,message:this.message,code:this.code}}},Yr=class extends zr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}};function Xr({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 zr({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 zr({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 zr({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 zr({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 zr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new zr({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 zr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new zr({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(!is(t))return new zr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rp.id!==t)return new zr({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 zr({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 zr({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 zr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Qr({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 zr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new zr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){let t=window.location.hostname;if(!is(t))return new zr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new zr({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 zr({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 zr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}let Zr=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 es(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=or(r).buffer,o=Object.assign(Object.assign({},s),{id:or(s.id).buffer}),l=Object.assign(Object.assign({},a),{challenge:n,user:o});if(i&&i.length>0){l.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]=cs(r,a):s[e]=cs(a)}else s[e]=a}return s}function us(e,t){return cs(ls,e,t||{})}var ds=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??Zr.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 ns({publicKey:us(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 cs(hs,e,t||{})}(a.webauthn.credential_options.publicKey,i?.request),{data:r,error:s}=await os(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 Ut(e)?{data:null,error:e}:{data:null,error:new qt("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 Lt("rpId is required for WebAuthn authentication")};try{if(!as())return{data:null,error:new qt("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 Ut(e)?{data:null,error:e}:{data:null,error:new qt("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 Lt("rpId is required for WebAuthn registration")};try{if(!as())return{data:null,error:new qt("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:l}=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:l}}catch(e){return Ut(e)?{data:null,error:e}:{data:null,error:new qt("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 ps={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:It,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function fs(e,t,r){return await r()}let gs={};var ms=class e{get jwks(){return gs[this.storageKey]?.jwks??{keys:[]}}set jwks(e){gs[this.storageKey]=Object.assign(Object.assign({},gs[this.storageKey]),{jwks:e})}get jwks_cached_at(){return gs[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){gs[this.storageKey]=Object.assign(Object.assign({},gs[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({},ps),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&&cr()){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 Br({url:s.url,headers:s.headers,fetch:s.fetch,experimental:this.experimental}),this.url=s.url,this.headers=s.headers,this.fetch=pr(s.fetch),this.lock=s.lock||fs,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&&cr()&&(null==globalThis?void 0:globalThis.navigator)?.locks?this.lock=Fr:this.lock=fs,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 ds(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:dr()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=qr(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=qr(this.memoryStorage)),cr()&&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} (${Pt}) ${(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(cr()&&(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")),cr()&&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),Gt(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 Ut(e)?this._returnResult({error:e}):this._returnResult({error:new qt("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){try{let{data:t,error:r}=await Cr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:Ir});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(Ut(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 kr(this.storage,this.storageKey)),t=await Cr(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:Ir})}else{if(!("phone"in e))throw new Ft("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:i}=e;t=await Cr(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:Ir})}}let{data:r,error:s}=t;if(s||!r)return await mr(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 mr(this.storage,`${this.storageKey}-code-verifier`),Ut(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 Cr(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:$r})}else{if(!("phone"in e))throw new Ft("You must provide either an email or phone number and a password");{let{phone:r,password:s,options:i}=e;t=await Cr(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:$r})}}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 Kt;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(Ut(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(cr())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 l=new URL(o?.url??window.location.href),h=await s.request({method:"eth_requestAccounts"}).then((e=>e)).catch((()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")}));if(!h||0===h.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let c=Gr(h[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:l,scheme:h,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=`${h?`${h}://${r}`:r} wants you to sign in with your Ethereum account:\n${Gr(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}`),l){let e="\nResources:";for(let t of l){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:l.host,address:c,statement:n,uri:l.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:[Vr(t),c]})}try{let{data:s,error:i}=await Cr(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:Ir});if(i)throw i;if(!s||!s.session||!s.user){let e=new Kt;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(Ut(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(cr())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 l=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:l.host,uri:l.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=[`${l.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...n?["",n,""]:[""],"Version: 1",`URI: ${l.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 Cr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:t,signature:hr(r)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Ir});if(i)throw i;if(!s||!s.session||!s.user){let e=new Kt;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(Ut(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let[t,r]=(await gr(this.storage,`${this.storageKey}-code-verifier`)??"").split("/");try{if(!t&&"pkce"===this.flowType)throw new zt;let{data:s,error:i}=await Cr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:Ir});if(await mr(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let e=new Kt;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 mr(this.storage,`${this.storageKey}-code-verifier`),Ut(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 Cr(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:Ir});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!n||!n.session||!n.user){let e=new Kt;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(Ut(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 kr(this.storage,this.storageKey));let{error:a}=await Cr(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 Cr(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 Ft("You must provide either an email or phone number.")}catch(e){if(await mr(this.storage,`${this.storageKey}-code-verifier`),Ut(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 Cr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:r}}),redirectTo:t,xform:Ir});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(Ut(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 kr(this.storage,this.storageKey));let s=await Cr(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:Nr});return s.data?.url&&cr()&&!e.options?.skipBrowserRedirect&&window.location.assign(s.data.url),this._returnResult(s)}catch(e){if(await mr(this.storage,`${this.storageKey}-code-verifier`),Ut(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 Ht;let{error:s}=await Cr(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(Ut(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 Cr(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 Cr(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 Ft("You must provide either an email or phone number and a type")}catch(e){if(Ut(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 gr(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 Cr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:xr}):await this._useSession((async e=>{let{data:t,error:r}=e;if(r)throw r;return t.session?.access_token||this.hasCustomAuthorizationHeader?await Cr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:xr}):{data:{user:null},error:new Ht}}))}catch(e){if(Ut(e))return Wt(e)&&(await this._removeSession(),await mr(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 Ht;let a=s.session,n=null,o=null;"pkce"===this.flowType&&null!=e.email&&([n,o]=await kr(this.storage,this.storageKey));let{data:l,error:h}=await Cr(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:xr});if(h)throw h;return a.user=l.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})}))}catch(e){if(await mr(this.storage,`${this.storageKey}-code-verifier`),Ut(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 Ht;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:a}=br(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(Ut(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 Ht;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(Ut(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!cr())throw new Jt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Jt(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 Vt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new Jt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Vt("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:l}=e;if(!(i&&n&&a&&l))throw new Jt("No session defined in URL");let h=Math.round(Date.now()/1e3),c=parseInt(n),u=h+c;o&&(u=parseInt(o));let d=u-h;1e3*d<=jt&&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;h-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,h):h-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,h);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:l,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(Ut(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 gr(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&&!Wt(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&&(!Bt(t)||404!==t.status&&401!==t.status&&403!==t.status)&&!Wt(t))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await mr(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),Wt(t)?console.warn(t):console.error(t)}}))}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await kr(this.storage,this.storageKey,!0));try{return await Cr(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 mr(this.storage,`${this.storageKey}-code-verifier`),Ut(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(Ut(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 Cr(this.fetch,"GET",i,{headers:this.headers,jwt:r.session?.access_token??void 0})}));if(r)throw r;return cr()&&!e.options?.skipBrowserRedirect&&window.location.assign(t?.url),this._returnResult({data:{provider:e.provider,url:t?.url},error:null})}catch(t){if(Ut(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:l}=e,{data:h,error:c}=await Cr(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:l,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Ir});return c?this._returnResult({data:{user:null,session:null},error:c}):h&&h.session&&h.user?(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:c})):this._returnResult({data:{user:null,session:null},error:new Kt})}catch(e){if(await mr(this.storage,`${this.storageKey}-code-verifier`),Ut(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 Cr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:r.session?.access_token??void 0})}))}catch(e){if(Ut(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 Cr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ir}))),((e,t)=>{let s=200*2**e;return t&&Xt(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()),jt);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)/jt);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 instanceof Hr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!cr()||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 kr(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 Cr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:r?.session?.access_token})}))}catch(e){if(Ut(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 Cr(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(Ut(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?rs(e.webauthn.credential_response):ss(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:n}=await Cr(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(Ut(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 Cr(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:es(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:ts(a.webauthn.credential_options.publicKey)})})}),error:null}}}))}catch(e){if(Ut(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}=br(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(Ut(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}=br(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 Cr(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 Ht})}))}catch(e){if(Ut(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 Ht});let a=await Cr(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&&cr()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a}))}catch(e){if(Ut(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 Ht});let a=await Cr(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&&cr()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a}))}catch(e){if(Ut(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 Cr(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 Ht})}))}catch(e){if(Ut(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 Cr(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 Ht})}))}catch(e){if(Ut(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 Cr(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}}=br(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 l=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(!l){let{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:i,header:s,signature:a},error:null}}let h=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",l,h,!0,["verify"]);if(!await crypto.subtle.verify(h,c,a,lr(`${n}.${o}`)))throw new Zt("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(e){if(Ut(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){Er(this.experimental);try{if(!as())return this._returnResult({data:null,error:new qt("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 os({publicKey:ts(t.options),signal:e?.options?.signal??Zr.createNewAbortSignal()});if(i||!s)return this._returnResult({data:null,error:i??new qt("WebAuthn ceremony failed",null)});let a=ss(s);return this._verifyPasskeyAuthentication({challengeId:t.challenge_id,credential:a})}catch(e){if(Ut(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){Er(this.experimental);try{if(!as())return this._returnResult({data:null,error:new qt("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 ns({publicKey:es(t.options),signal:e?.options?.signal??Zr.createNewAbortSignal()});if(i||!s)return this._returnResult({data:null,error:i??new qt("WebAuthn ceremony failed",null)});let a=rs(s);return this._verifyPasskeyRegistration({challengeId:t.challenge_id,credential:a})}catch(e){if(Ut(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){Er(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 Ht});let{data:s,error:i}=await Cr(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(Ut(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Er(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 Ht});let{data:i,error:a}=await Cr(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(Ut(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){Er(this.experimental);try{let{data:t,error:r}=await Cr(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(Ut(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){Er(this.experimental);try{let{data:t,error:r}=await Cr(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:Ir});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(Ut(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){Er(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 Ht});let{data:s,error:i}=await Cr(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(Ut(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Er(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 Ht});let{data:i,error:a}=await Cr(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(Ut(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){Er(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 Ht});let{error:i}=await Cr(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(Ut(e))return this._returnResult({data:null,error:e});throw e}}};ms.nextInstanceID={};var ys=ms,bs=Br,ws=ys,_s=class extends ws{constructor(e){super(e)}},ks=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:l,global:h}=t,c=Ot(e.tracePropagation),u=Ot(t.tracePropagation),d={db:{...n,...r},auth:{...o,...s},realtime:{...l,...i},storage:{},global:{...h,...a,headers:{...h?.headers??{},...a?.headers??{}}},tracePropagation:{enabled:c?.enabled??u?.enabled??!1,respectSamplingDecision:c?.respectSamplingDecision??u?.respectSamplingDecision??!0},accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(r??{},{db:_t,realtime:vt,auth:{...kt,storageKey:i},global:wt,tracePropagation:St});this.settings=a,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=At(t,e,this._getAccessToken.bind(this),a.global.fetch,a.tracePropagation),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 E(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 yt(this.storageUrl.href,this.headers,this.fetch,r?.storage),a.accessToken||this._listenForAuthEvents()}get functions(){return new l(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:l,throwOnError:h,experimental:c,lockAcquireTimeout:u,skipAutoInitialize:d},p,f){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new _s({url:this.authUrl.href,headers:{...g,...p},storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:n,lock:o,debug:l,throwOnError:h,experimental:c,fetch:f,lockAcquireTimeout:u,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some((e=>"authorization"===e.toLowerCase()))})}_initRealtimeClient(e){return new Ee(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=bs,e.AuthApiError=Dt,e.AuthClient=ws,e.AuthError=Lt,e.AuthImplicitGrantRedirectError=Jt,e.AuthInvalidCredentialsError=Ft,e.AuthInvalidJwtError=Zt,e.AuthInvalidTokenResponseError=Kt,e.AuthPKCECodeVerifierMissingError=zt,e.AuthPKCEGrantCodeExchangeError=Vt,e.AuthRetryableFetchError=Yt,e.AuthSessionMissingError=Ht,e.AuthUnknownError=qt,e.AuthWeakPasswordError=Qt,e.CustomAuthError=Mt,Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return s}}),e.FunctionsError=i,e.FunctionsFetchError=a,e.FunctionsHttpError=o,e.FunctionsRelayError=n,e.GoTrueAdminApi=Br,e.GoTrueClient=ys,e.NavigatorLockAcquireTimeoutError=Wr,e.PostgrestError=d,e.REALTIME_CHANNEL_STATES=we,Object.defineProperty(e,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return me}}),Object.defineProperty(e,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return ge}}),Object.defineProperty(e,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return H}}),Object.defineProperty(e,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return ye}}),e.RealtimeChannel=_e,e.RealtimeClient=Ee,e.RealtimePresence=fe,e.SIGN_OUT_SCOPES=Dr,e.StorageApiError=qe,e.SupabaseClient=ks,e.WebSocketFactory=R,e.createClient=(e,t,r)=>new ks(e,t,r),e.isAuthApiError=Bt,e.isAuthError=Ut,e.isAuthImplicitGrantRedirectError=Gt,e.isAuthPKCECodeVerifierMissingError=function(e){return Ut(e)&&"AuthPKCECodeVerifierMissingError"===e.name},e.isAuthRetryableFetchError=Xt,e.isAuthSessionMissingError=Wt,e.isAuthWeakPasswordError=function(e){return Ut(e)&&"AuthWeakPasswordError"===e.name},e.lockInternals=Mr,e.navigatorLock=Fr,e.processLock=async function(e,t,r){let s=Jr[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 Kr(`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 instanceof Hr)throw e}return await r()})();return Jr[e]=(async()=>{try{return await a}catch(e){if(e instanceof Hr){try{await s}catch{}return null}throw e}})(),await a},e}({}); //# sourceMappingURL=/sm/d374cd36963f7bf76009453a9ada07ef0c58e15924ced3833e1a1ed1a26ebd53.map