1import"./rolldown-runtime-D78FXLAz.js";import{er as Xt,tr as Ne}from"./vendor-react-CXf0XbkU.js";var Qt=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),tt=class extends Error{constructor(t,e="FunctionsError",r){super(t),this.name=e,this.context=r}},Zt=class extends tt{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}},st=class extends tt{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}},it=class extends tt{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}},Fe;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Fe||(Fe={}));var er=class{constructor(t,{headers:e={},customFetch:r,region:s=Fe.Any}={}){this.url=t,this.headers=e,this.region=s,this.fetch=Qt(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return Xt(this,arguments,void 0,function*(e,r={}){var s;let i,n;try{const{headers:a,method:o,body:l,signal:c,timeout:h}=r;let u={},{region:d}=r;d||(d=this.region);const f=new URL(`${this.url}/${e}`);d&&d!=="any"&&(u["x-region"]=d,f.searchParams.set("forceFunctionRegion",d));let p;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob!="undefined"&&l instanceof Blob||l instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",p=l):typeof l=="string"?(u["Content-Type"]="text/plain",p=l):typeof FormData!="undefined"&&l instanceof FormData?p=l:(u["Content-Type"]="application/json",p=JSON.stringify(l)):l&&typeof l!="string"&&!(typeof Blob!="undefined"&&l instanceof Blob)&&!(l instanceof ArrayBuffer)&&!(typeof FormData!="undefined"&&l instanceof FormData)?p=JSON.stringify(l):p=l;let v=c;h&&(n=new AbortController,i=setTimeout(()=>n.abort(),h),c?(v=n.signal,c.addEventListener("abort",()=>n.abort())):v=n.signal);const g=yield this.fetch(f.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),a),body:p,signal:v}).catch(T=>{throw new Zt(T)}),k=g.headers.get("x-relay-error");if(k&&k==="true")throw new st(g);if(!g.ok)throw new it(g);let _=((s=g.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),w;return _==="application/json"?w=yield g.json():_==="application/octet-stream"||_==="application/pdf"?w=yield g.blob():_==="text/event-stream"?w=g:_==="multipart/form-data"?w=yield g.formData():w=yield g.text(),{data:w,error:null,response:g}}catch(a){return{data:null,error:a,response:a instanceof it||a instanceof st?a.context:void 0}}finally{i&&clearTimeout(i)}})}},tr=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
1de=t.code}},rr=class{constructor(t){var e,r,s;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,l=null,c=n.status,h=n.statusText;if(n.ok){var u,d;if(r.method!=="HEAD"){var f;const g=await n.text();g===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?o=g:o=JSON.parse(g))}const p=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),v=(d=n.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");p&&v&&v.length>1&&(l=parseInt(v[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,l=null,c=406,h="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{const p=await n.text();try{a=JSON.parse(p),Array.isArray(a)&&n.status===404&&(o=[],a=null,c=200,h="OK")}catch{n.status===404&&p===""?(c=204,h="No Content"):a={message:p}}if(a&&r.shouldThrowOnError)throw new tr(a)}return{error:a,data:o,count:l,status:c,statusText:h}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",l="",c="";const h=n==null?void 0:n.cause;if(h){var u,d,f,p;const k=(u=h==null?void 0:h.message)!==null&&u!==void 0?u:"",_=(d=h==null?void 0:h.code)!==null&&d!==void 0?d:"";o=`${(f=n==null?void 0:n.name)!==null&&f!==void 0?f:"FetchError"}: ${n==null?void 0:n.message}`,o+=` 2 3Caused by: ${(p=h==null?void 0:h.name)!==null&&p!==void 0?p:"Error"}: ${k}`,_&&(o+=` (${_})`),h!=null&&h.stack&&(o+=` 4${h.stack}`)}else{var v;o=(v=n==null?void 0:n.stack)!==null&&v!==void 0?v:""}const g=this.url.toString().length;return(n==null?void 0:n.name)==="AbortError"||(n==null?void 0:n.code)==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",g>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${g} 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.`)):((h==null?void 0:h.name)==="HeadersOverflowError"||(h==null?void 0:h.code)==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",g>this.urlLengthLimit&&(l+=`. Your request URL is ${g} 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.`)),{error:{message:`${(a=n==null?void 0:n.name)!==null&&a!==void 0?a:"FetchError"}: ${n==null?void 0:n.message}`,details:o,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},sr=class extends rr{select(t){let e=!1;const r=(t!=null?t:"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){const n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r=="undefined"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const i=typeof s=="undefined"?"offset":`${s}.offset`,n=typeof s=="undefined"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(n,`${e-t+1}`),this}abortSignal(t){return this.signal=t,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}
4explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},nt=new RegExp("[,()]"),se=class extends sr{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&nt.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&nt.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");const n=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${n}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},ir=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:i=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:s}=e!=null?e:{},i=r?"HEAD":"GET";let n=!1;const a=(t!=null?t:"*").split("").map(c=>/\s/.test(c)&&!n?"":(c==='"'&&(n=!n),c)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),s&&l.append("Prefer",`count=${s}`),new se({method:i,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const i="POST",{url:n,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),r||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(o.length>0){const l=[...new Set(o)].map(c=>`"${c}"`);n.searchParams.set("columns",l.join(","))}}return new se({method:i,url:n,headers:a,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var n;const a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),i||l.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((h,u)=>h.concat(Object.keys(u)),[]);if(c.length>0){const h=[...new Set(c)].map(u=>`"${u}"`);o.searchParams.set("columns",h.join(","))}}return new se({method:a,url:o,headers:l,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;const s="PATCH",{url:i,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new se({method:s,url:i,headers:n,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new se({method:r,url:s,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function fe(t){"@babel/helpers - typeof";return fe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},fe(t)}function nr(t,e){if(fe(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(fe(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ar(t){var e=nr(t,"string");return fe(e)=="symbol"?e:e+""}function or(t,e,r){return(e=ar(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function at(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,s)}return r}function be(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};
4e%2?at(Object(r),!0).forEach(function(s){or(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):at(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var lr=class Pt{constructor(e,{headers:r={},schema:s,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=a;const o=i!=null?i:globalThis.fetch;n!==void 0&&n>0?this.fetch=(l,c)=>{const h=new AbortController,u=setTimeout(()=>h.abort(),n),d=c==null?void 0:c.signal;if(d){if(d.aborted)return clearTimeout(u),o(l,c);const f=()=>{clearTimeout(u),h.abort()};return d.addEventListener("abort",f,{once:!0}),o(l,be(be({},c),{},{signal:h.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",f)})}return o(l,be(be({},c),{},{signal:h.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ir(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Pt(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:i=!1,count:n}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let c;const h=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(h)),u=s&&Object.values(r).some(h);u?(o="POST",c=r):s||i?(o=s?"HEAD":"GET",Object.entries(r).filter(([f,p])=>p!==void 0).map(([f,p])=>[f,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([f,p])=>{l.searchParams.append(f,p)})):(o="POST",c=r);const d=new Headers(this.headers);return u?d.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&d.set("Prefer",`count=${n}`),new se({method:o,url:l,headers:d,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}},cr=class{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket!="undefined")return{type:"native",constructor:WebSocket};if(typeof globalThis!="undefined"&&typeof globalThis.WebSocket!="undefined")return{type:"native",constructor:globalThis.WebSocket};if(typeof global!="undefined"&&typeof global.WebSocket!="undefined")return{type:"native",constructor:global.WebSocket};if(typeof globalThis!="undefined"&&typeof globalThis.WebSocketPair!="undefined"&&typeof globalThis.WebSocket=="undefined")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!="undefined"&&globalThis.EdgeRuntime||typeof navigator!="undefined"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.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."};const e=globalThis.process;if(e){const r=e.versions;if(r&&r.node){const s=r.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket!="undefined"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 5import ws from "ws" 6new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const t=this.detectEnvironment();if(t.constructor)return t.constructor;let e=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(e+=` 7 8Suggested solution: ${t.workaround}`),new Error(e)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}},hr="2.101.1",ur=`realtime-js/${hr}`,dr="1.0.0",jt="2.0.0",fr=jt,pr=1e4,W={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},$t={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},Ke={connecting:"connecting",open:"open",closing:"closing",closed:"closed"},gr=class{constructor(t){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=t!=null?t:[]}encode(t,e){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return e(this._binaryEncodeUserBroadcastPush(t));let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(t){var e;return this._isArrayBuffer((e=t.payload)===null||e===void 0?void 0:e.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var e,r;const s=(r=(e=t.payload)===null||e===void 0?void 0:e.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(t){var e,r;const s=(r=(e=t.payload)===null||e===void 0?void 0:e.payload)!==null&&r!==void 0?r:{},i=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(t,e,r){var s,i;const n=t.topic,a=(s=t.ref)!==null&&s!==void 0?s:"",o=(i=t.join_ref)!==null&&i!==void 0?i:"",l=t.payload.event,c=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},h=Object.keys(c).length===0?"":JSON.stringify(c);if(o.length>255)throw new Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(n.length>255)throw new Error(`topic length ${n.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+n.length+l.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let f=new DataView(d),p=0;f.setUint8(p++,this.KINDS.userBroadcastPush),f.setUint8(p++,o.length),f.setUint8(p++,a.length),f.setUint8(p++,n.length),f.setUint8(p++,l.length),f.setUint8(p++,h.length),f.setUint8(p++,e),Array.from(o,g=>f.setUint8(p++,g.charCodeAt(0))),Array.from(a,g=>f.setUint8(p++,g.charCodeAt(0))),Array.from(n,g=>f.setUint8(p++,g.charCodeAt(0))),Array.from(l,g=>f.setUint8(p++,g.charCodeAt(0))),Array.from(h,g=>f.setUint8(p++,g.charCodeAt(0)));var v=new Uint8Array(d.byteLength+r.byteLength);return v.set(new Uint8Array(d),0),v.set(new Uint8Array(r),d.byteLength),v.buffer}decode(t,e){if(this._isArrayBuffer(t))return e(this._binaryDecode(t));if(typeof t=="string"){const[r,s,i,n,a]=JSON.parse(t);return e({join_ref:r,ref:s,topic:i,event:n,payload:a})}return e({})}
8_binaryDecode(t){const e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(t,e,s)}_decodeUserBroadcast(t,e,r){const s=e.getUint8(1),i=e.getUint8(2),n=e.getUint8(3),a=e.getUint8(4);let o=this.HEADER_LENGTH+4;const l=r.decode(t.slice(o,o+s));o=o+s;const c=r.decode(t.slice(o,o+i));o=o+i;const h=r.decode(t.slice(o,o+n));o=o+n;const u=t.slice(o,t.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,f={type:this.BROADCAST_EVENT,event:c,payload:d};return n>0&&(f.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(t){var e;return t instanceof ArrayBuffer||((e=t==null?void 0:t.constructor)===null||e===void 0?void 0:e.name)==="ArrayBuffer"}_pick(t,e){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([r])=>e.includes(r)))}},S;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(S||(S={}));var ot=(t,e,r={})=>{var s;const i=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((n,a)=>(n[a]=vr(a,t,e,i),n),{}):{}},vr=(t,e,r,s)=>{const i=e.find(o=>o.name===t),n=i==null?void 0:i.type,a=r[t];return n&&!s.includes(n)?It(n,a):Ve(a)},It=(t,e)=>{if(t.charAt(0)==="_")return br(e,t.slice(1,t.length));switch(t){case S.bool:return yr(e);case S.float4:case S.float8:case S.int2:case S.int4:case S.int8:case S.numeric:case S.oid:return mr(e);case S.json:case S.jsonb:return wr(e);case S.timestamp:return _r(e);case S.abstime:case S.date:case S.daterange:case S.int4range:case S.int8range:case S.money:case S.reltime:case S.text:case S.time:case S.timestamptz:case S.timetz:case S.tsrange:case S.tstzrange:return Ve(e);default:return Ve(e)}},Ve=t=>t,yr=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},mr=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},wr=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},br=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i;const n=t.slice(1,r);try{i=JSON.parse("["+n+"]")}catch{i=n?n.split(","):[]}return i.map(a=>It(e,a))}return t},_r=t=>typeof t=="string"?t.replace(" ","T"):t,Ut=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href},de=t=>typeof t=="function"?t:function(){return t},kr=typeof self!="undefined"?self:null,ie=typeof window!="undefined"?window:null,L=kr||ie||globalThis,Sr="2.0.0",Er=1e4,Tr=1e3,D={connecting:0,open:1,closing:2,closed:3},j={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},B={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ge={longpoll:"longpoll",websocket:"websocket"},Ar={complete:4},Je="base64url.bearer.phx.",_e=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,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(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}
vendor: 20,101 bytes, lines 8-9
8matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}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,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Nt=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Rr=class{constructor(t,e,r){this.state=j.closed,this.topic=t,this.params=de(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new _e(this,B.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Nt(()=>{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=j.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=j.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=j.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=j.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 _e(this,B.leave,de({}),this.timeout).send(),this.state=j.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(B.reply,(s,i)=>{this.trigger(this.replyEventName(i),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=j.closed,this.bindings=[]}onClose(t){this.on(B.close,t)}onError(t){return this.on(B.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e=="undefined"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new _e(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=j.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(B.close,"leave")},r=new _e(this,B.leave,de({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=j.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let i=this.onMessage(t,e,r,s);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let n=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,r));for(let a=0;a<n.length;a++)n[a].callback(i,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===j.closed}isErrored(){return this.state===j.errored}isJoined(){return this.state===j.joined}isJoining(){return this.state===j.joining}isLeaving(){return this.state===j.leaving}},je=class{static request(t,e,r,s,i,n,a){if(L.XDomainRequest){let o=new L.XDomainRequest;return this.xdomainRequest(o,t,e,s,i,n,a)}else if(L.XMLHttpRequest){let o=new L.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,i,n,a)}else{if(L.fetch&&L.AbortController)return this.fetchRequest(t,e,r,s,i,n,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,i,n,a){let o={method:t,headers:r,body:s},l=null;return i&&(l=new AbortController,setTimeout(()=>l.abort(),i),o.signal=l.signal),L.fetch(e,o).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>a&&a(c)).catch(c=>{c.name==="AbortError"&&n?n():a&&a(null)}),l}static xdomainRequest(t,e,r,s,i,n,a){return t.timeout=i,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},n&&(t.ontimeout=n),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,i,n,a,o){t.open(e,r,!0),t.timeout=n;for(let[l,c]of Object.entries(s))t.setRequestHeader(l,c);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{t.readyState===Ar.complete&&o&&o(this.parseJSON(t.responseText))},a&&(t.ontimeout=a),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let i=e?`${e}[${s}]`:s,n=t[s];typeof n=="object"?r.push(this.serialize(n,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(n))}return r.join("&")}static appendParams(t,e){return Object.keys(e).length===0?t:`${t}${t.match(/\?/)?"&":"?"}${this.serialize(e)}`}},Or=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let i=0;i<s;i++)e+=String.fromCharCode(r[i]);return btoa(e)},X=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Je)&&(this.authToken=atob(e[1].slice(Je.length))),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(t),this.readyState=D.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ge.websocket),"$1/"+Ge.longpoll)}endpointURL(){return je.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=D.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===D.open||this.readyState===D.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:i.forEach(n=>{setTimeout(()=>this.onmessage({data:n}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=D.open,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 new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Or(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(` 9`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=D.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent!="undefined"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,i){let n,a=()=>{this.reqs.delete(n),s()};n=je.request(t,this.endpointURL(),e,r,this.timeout,a,o=>{this.reqs.delete(n),this.isActive()&&i(o)}),this.reqs.add(n)}},Cr=class he{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,i=>{let{onJoin:n,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=he.syncState(this.state,i,n,a),this.pendingDiffs.forEach(l=>{this.state=he.syncDiff(this.state,l,n,a)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,i=>{let{onJoin:n,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=he.syncDiff(this.state,i,n,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return he.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,i){let n=this.clone(e),a={},o={};return this.map(n,(l,c)=>{r[l]||(o[l]=c)}),this.map(r,(l,c)=>{let h=n[l];if(h){let u=c.metas.map(v=>v.phx_ref),d=h.metas.map(v=>v.phx_ref),f=c.metas.filter(v=>d.indexOf(v.phx_ref)<0),p=h.metas.filter(v=>u.indexOf(v.phx_ref)<0);f.length>0&&(a[l]=c,a[l].metas=f),p.length>0&&(o[l]=this.clone(h),o[l].metas=p)}else a[l]=c}),this.syncDiff(n,{joins:a,leaves:o},s,i)}static syncDiff(e,r,s,i){let{joins:n,leaves:a}=this.clone(r);return s||(s=function(){}),i||(i=function(){}),this.map(n,(o,l)=>{let c=e[o];if(e[o]=this.clone(l),c){let h=e[o].metas.map(d=>d.phx_ref),u=c.metas.filter(d=>h.indexOf(d.phx_ref)<0);e[o].metas.unshift(...u)}s(o,c,l)}),this.map(a,(o,l)=>{let c=e[o];if(!c)return;let h=l.metas.map(u=>u.phx_ref);c.metas=c.metas.filter(u=>h.indexOf(u.phx_ref)<0),i(o,c,l),c.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,i){return i}),this.map(e,(s,i)=>r(s,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},ke={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,i,n,a]=JSON.parse(t);return e({join_ref:r,ref:s,topic:i,event:n,payload:a})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:i,payload:n}=t,a=this.META_LENGTH+e.length+r.length+i.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),l=new DataView(o),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,e.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,s.length),Array.from(e,u=>l.setUint8(c++,u.charCodeAt(0))),Array.from(r,u=>l.setUint8(c++,u.charCodeAt(0))),Array.from(i,u=>l.setUint8(c++,u.charCodeAt(0))),Array.from(s,u=>l.setUint8(c++,u.charCodeAt(0)));var h=new Uint8Array(o.byteLength+n.byteLength);return h.set(new Uint8Array(o),0),h.set(new Uint8Array(n),o.byteLength),h.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),i=e.getUint8(2),n=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(a,a+s));a=a+s;let l=r.decode(t.slice(a,a+i));a=a+i;let c=r.decode(t.slice(a,a+n));return a=a+n,{join_ref:o,ref:null,topic:l,event:c,payload:t.slice(a,t.byteLength)}},decodeReply(t,e,r){let s=e.getUint8(1),i=e.getUint8(2),n=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(o,o+s));o=o+s;let c=r.decode(t.slice(o,o+i));o=o+i;let h=r.decode(t.slice(o,o+n));o=o+n;let u=r.decode(t.slice(o,o+a));o=o+a;let d={status:u,response:t.slice(o,t.byteLength)};return{join_ref:l,ref:c,topic:h,event:B.reply,payload:d}},decodeBroadcast(t,e,r){let s=e.getUint8(1),i=e.getUint8(2),n=this.HEADER_LENGTH+2,a=r.decode(t.slice(n,n+s));n=n+s;let o=r.decode(t.slice(n,n+i));return n=n+i,{join_ref:null,ref:null,topic:a,event:o,payload:t.slice(n,t.byteLength)}}},Pr=class{constructor(t,e={}){var r,s;this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Er,this.transport=e.transport||L.WebSocket||X,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||L&&L.sessionStorage,this.establishedConnections=0,this.defaultEncoder=ke.encode.bind(ke),this.defaultDecoder=ke.decode.bind(ke),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==X?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;ie&&ie.addEventListener&&(ie.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),i=this.connectClock)}),ie.addEventListener("pageshow",n=>{i===this.connectClock&&(i=null,this.connect())}),ie.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=(r=e.autoSendHeartbeat)!==null&&r!==void 0?r:!0,this.heartbeatCallback=(s=e.heartbeatCallback)!==null&&s!==void 0?s:(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,a,o)=>{`${n}${a}`}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=de(e.params||{}),this.endPoint=`${t}/${Ge.websocket}`,this.vsn=e.vsn||Sr,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Nt(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return X}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=je.appendParams(je.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(this.params=de(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==X?this.connectWithFallback(X,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(i=>{i.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){return t===X?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Je}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),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(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,i,n,a=this.transportName(t),o=l=>{this.log("transport",`falling back to ${a}...`,l),this.off([i,n]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),n=this.onError(l=>{this.log("transport","error",l),s&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),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(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Tr,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){}
vendor: 6,415 bytes, line 9
9,this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===D.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(B.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case D.connecting:return"connecting";case D.open:return"open";case D.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new Rr(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:i,join_ref:n}=t;this.log("push",`${e} ${r} (${n}, ${i})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:i,ref:n,join_ref:a}=e;if(n&&n===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${s} ${n&&"("+n+")"||""}`.trim(),i);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(r,s,i,a)&&l.trigger(s,i,n,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(i){this.log("error",`error in ${t} callback`,i)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}},jr=class Re{constructor(e,r){const s=Ir(r);this.presence=new Cr(e.getChannel(),s),this.presence.onJoin((i,n,a)=>{const o=Re.onJoinPayload(i,n,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((i,n,a)=>{const o=Re.onLeavePayload(i,n,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Re.transformState(this.presence.state)}static transformState(e){return e=$r(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const i=e[s];return r[s]=Oe(i),r},{})}static onJoinPayload(e,r,s){return{event:"join",key:e,currentPresences:lt(r),newPresences:Oe(s)}}static onLeavePayload(e,r,s){return{event:"leave",key:e,currentPresences:lt(r),leftPresences:Oe(s)}}};function Oe(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function $r(t){return JSON.parse(JSON.stringify(t))}function Ir(t){return(t==null?void 0:t.events)&&{events:t.events}}function lt(t){return t!=null&&t.metas?Oe(t):[]}var ct;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(ct||(ct={}));var Ur=class{get state(){return this.presenceAdapter.state}constructor(t,e){this.channel=t,this.presenceAdapter=new jr(this.channel.channelAdapter,e)}},Nr=class{constructor(t,e,r){const s=xr(r);this.channel=t.getSocket().channel(e,s),this.socket=t}get state(){return this.channel.state}set state(t){this.channel.state=t}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(t,e){return this.channel.on(t,e)}off(t,e){this.channel.off(t,e)}subscribe(t){return this.channel.join(t)}unsubscribe(t){return this.channel.leave(t)}teardown(){this.channel.teardown()}onClose(t){this.channel.onClose(t)}onError(t){return this.channel.onError(t)}push(t,e,r){let s;try{s=this.channel.push(t,e,r)}catch{throw`tried to push '${t}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>100){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return s}updateJoinPayload(t){const e=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},e),t)}canPush(){return this.socket.isConnected()&&this.state===W.joined}isJoined(){return this.state===W.joined}isJoining(){return this.state===W.joining}isClosed(){return this.state===W.closed}isLeaving(){return this.state===W.leaving}updateFilterBindings(t){this.channel.filterBindings=t}updatePayloadTransform(t){this.channel.onMessage=t}getChannel(){return this.channel}};function xr(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var ht;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELET
9E="DELETE"})(ht||(ht={}));var ae;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ae||(ae={}));var q;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(q||(q={}));var Lr=class Ce{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,r={config:{}},s){var i,n;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Nr(this.socket.socketAdapter,e,this.params),this.presence=new Ur(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Ut(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((n=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||n===void 0)&&n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var s,i,n;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:l}}=this.params,c=(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(f=>f.filter))!==null&&i!==void 0?i:[],h=!!this.bindings[ae.PRESENCE]&&this.bindings[ae.PRESENCE].length>0||((n=this.params.config.presence)===null||n===void 0?void 0:n.enabled)===!0,u={},d={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:h}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(f=>{e==null||e(q.CHANNEL_ERROR,f)}),this._onClose(()=>e==null?void 0:e(q.CLOSED)),this.updateJoinPayload(Object.assign({config:d},u)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e==null||e(q.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=W.errored,e==null||e(q.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(q.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const i=this.bindings.postgres_changes,n=(s=i==null?void 0:i.length)!==null&&s!==void 0?s:0,a=[];for(let o=0;o<n;o++){const l=i[o],{filter:{event:c,schema:h,table:u,filter:d}}=l,f=e&&e[o];if(f&&f.event===c&&Ce.isFilterValueEqual(f.schema,h)&&Ce.isFilterValueEqual(f.table,u)&&Ce.isFilterValueEqual(f.filter,d))a.push(Object.assign(Object.assign({},l),{id:f.id}));else{this.unsubscribe(),this.state=W.errored,r==null||r(q.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=W.errored&&r&&r(q.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){const i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),n=e===ae.PRESENCE||e===ae.POSTGRES_CHANGES;if(i&&n)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var i;if(r==null)return Promise.reject("Payload is required for httpSend()");const n={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(n.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:n,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(i=s.timeout)!==null&&i!==void 0?i:this.timeout);if(o.status===202)return{success:!0};let l=o.statusText;
9try{const c=await o.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var s,i;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){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.");const{event:n,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:a,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var a,o,l;const c=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const i=new AbortController,n=setTimeout(()=>i.abort(),s),a=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(n),a}_on(e,r,s){const i=e.toLocaleLowerCase(),n={type:i,filter:r,callback:s,ref:this.channelAdapter.on(e,s)};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var i,n,a,o,l,c,h;const u=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(u,s))return!1;const d=(i=this.bindings[u])===null||i===void 0?void 0:i.find(f=>f.ref===e.ref);if(!d)return!0;if(["broadcast","presence","postgres_changes"].includes(u))if("id"in d){const f=d.id,p=(n=d.filter)===null||n===void 0?void 0:n.event;return f&&((a=r.ids)===null||a===void 0?void 0:a.includes(f))&&(p==="*"||(p==null?void 0:p.toLocaleLowerCase())===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const f=(c=(l=d==null?void 0:d.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return f==="*"||f===((h=r==null?void 0:r.event)===null||h===void 0?void 0:h.toLocaleLowerCase())}else return d.type.toLocaleLowerCase()===u})}_notThisChannelEvent(e,r){const{close:s,error:i,leave:n,join:a}=$t;return r&&[s,i,n,a].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const i=r.data,{schema:n,table:a,commit_timestamp:o,type:l,errors:c}=i;return Object.assign(Object.assign({},{schema:n,table:a,commit_timestamp:o,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(i))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e!=null?e:void 0)===(r!=null?r:void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=ot(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=ot(e.columns,e.old_record)),r}},Dr=class{constructor(t,e){this.socket=new Pr(t,e)}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(t){this.socket.heartbeatCallback=t}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(t,e,r,s=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),s),this.socket.disconnect(()=>{t(),i("ok")},e,r)})}push(t){this.socket.push(t)}log(t,e,r){this.socket.log(t,e,r)}makeRef(){return this.socket.makeRef()}onOpen(t){this.socket.onOpen(t)}onClose(t){this.socket.onClose(t)}onError(t){this.socket.onError(t)}onMessage(t){this.socket.onMessage(t)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Ke.connecting}isDisconnecting(){return this.socket.connectionState()==Ke.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}},Br={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},qr=[1e3,2e3,5e3,1e4],Hr=1e4,Mr=` 10 addEventListener("message", (e) => { 11 if (e.data.event === "start") { 12 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 13 } 14 });`,Wr=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(t,e){var r;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={}
14,this.ref=0,this.serializer=new gr,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=i=>i?(...n)=>i(...n):(...n)=>fetch(...n),!(!((r=e==null?void 0:e.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=e.params.apikey;const s=this._initializeOptions(e);this.socketAdapter=new Dr(t,s),this.httpEndpoint=Ut(t),this.fetch=this._resolveFetch(e==null?void 0:e.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){const e=t.message;throw e.includes("Node.js")?new Error(`${e} 15 16To use Realtime in Node.js, you need to provide a WebSocket implementation: 17 18Option 1: Use Node.js 22+ which has native WebSocket support 19Option 2: Install and provide the "ws" package: 20 21 npm install ws 22 23 import ws from "ws" 24 const client = new RealtimeClient(url, { 25 ...options, 26 transport: ws 27 })`):new Error(`WebSocket not available: ${e}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(t,e){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},t,e)}getChannels(){return this.channels}async removeChannel(t){const e=await t.unsubscribe();return e==="ok"&&t.teardown(),this.channels.length===0&&this.disconnect(),e}async removeAllChannels(){const t=this.channels.map(async r=>{const s=await r.unsubscribe();return r.teardown(),s}),e=await Promise.all(t);return this.disconnect(),e}log(t,e,r){this.socketAdapter.log(t,e,r)}connectionState(){return this.socketAdapter.connectionState()||Ke.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(t,e={config:{}}){const r=`realtime:${t}`,s=this.getChannels().find(i=>i.topic===r);if(s)return s;{const i=new Lr(`realtime:${t}`,e,this);return this.channels.push(i),i}}push(t){this.socketAdapter.push(t)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(t){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(t)}_makeRef(){return this.socketAdapter.makeRef()}_remove(t){this.channels=this.channels.filter(e=>e.topic!==t.topic)}async _performAuth(t=null){let e,r=!1;if(t)e=t,r=!0;else if(this.accessToken)try{e=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),e=this.accessTokenValue}else e=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=e&&(this.accessTokenValue=e,this.channels.forEach(s=>{const i={access_token:e,version:ur};e&&s.updateJoinPayload(i),s.joinedOnce&&s.channelAdapter.isJoined()&&s.channelAdapter.push($t.access_token,{access_token:e})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(e=>{this.log("error",`Error setting auth in ${t}`,e)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(t=>{this.log("error","error waiting for auth on connect",t)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(t=>{t.ref&&t.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(t){return(e,r)=>{e=="sent"&&this._setAuthSafely(),t&&t(e,r)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{e.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(t){let e;if(t)e=t;else{const r=new Blob([Mr],{type:"application/javascript"});e=URL.createObjectURL(r)}return e}_initializeOptions(t){var e,r,s,i,n,a,o,l,c;this.worker=(e=t==null?void 0:t.worker)!==null&&e!==void 0?e:!1,this.accessToken=(r=t==null?void 0:t.accessToken)!==null&&r!==void 0?r:null;const h={};
27h.timeout=(s=t==null?void 0:t.timeout)!==null&&s!==void 0?s:pr,h.heartbeatIntervalMs=(i=t==null?void 0:t.heartbeatIntervalMs)!==null&&i!==void 0?i:Br.HEARTBEAT_INTERVAL,h.transport=(n=t==null?void 0:t.transport)!==null&&n!==void 0?n:cr.getWebSocketConstructor(),h.params=t==null?void 0:t.params,h.logger=t==null?void 0:t.logger,h.heartbeatCallback=this._wrapHeartbeatCallback(t==null?void 0:t.heartbeatCallback),h.reconnectAfterMs=(a=t==null?void 0:t.reconnectAfterMs)!==null&&a!==void 0?a:(p=>qr[p-1]||Hr);let u,d;const f=(o=t==null?void 0:t.vsn)!==null&&o!==void 0?o:fr;switch(f){case dr:u=(p,v)=>v(JSON.stringify(p)),d=(p,v)=>v(JSON.parse(p));break;case jt:u=this.serializer.encode.bind(this.serializer),d=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${h.vsn}`)}if(h.vsn=f,h.encode=(l=t==null?void 0:t.encode)!==null&&l!==void 0?l:u,h.decode=(c=t==null?void 0:t.decode)!==null&&c!==void 0?c:d,h.beforeReconnect=this._reconnectAuth.bind(this),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,h.params=Object.assign(Object.assign({},h.params),{log_level:this.logLevel})),this.worker){if(typeof window!="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl,h.autoSendHeartbeat=!this.worker}return h}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}},pe=class extends Error{constructor(t,e){var r;super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((r=e.icebergType)===null||r===void 0?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Fr(t,e,r){const s=new URL(e,t);if(r)for(const[i,n]of Object.entries(r))n!==void 0&&s.searchParams.set(i,n);return s.toString()}async function Kr(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Vr(t){var e;const r=(e=t.fetchImpl)!==null&&e!==void 0?e:globalThis.fetch;return{async request({method:s,path:i,query:n,body:a,headers:o}){const l=Fr(t.baseUrl,i,n),c=await Kr(t.auth),h=await r(l,{method:s,headers:{...a?{"Content-Type":"application/json"}:{},...c,...o},body:a?JSON.stringify(a):void 0}),u=await h.text(),d=(h.headers.get("content-type")||"").includes("application/json"),f=d&&u?JSON.parse(u):u;if(!h.ok){var p;const v=d?f:void 0,g=v==null?void 0:v.error;throw new pe((p=g==null?void 0:g.message)!==null&&p!==void 0?p:`Request failed with status ${h.status}`,{status:h.status,icebergType:g==null?void 0:g.type,icebergCode:g==null?void 0:g.code,details:v})}return{status:h.status,headers:h.headers,data:f}}}}function Se(t){return t.join("�")}var Gr=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Se(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Se(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Se(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Se(t.namespace)}`}),!0}catch(e){if(e instanceof pe&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof pe&&r.status===409)return;throw r}}};function Q(t){return t.join("�")}var Jr=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Q(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Q(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Q(t.namespace)}
27/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){var r;await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Q(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String((r=e==null?void 0:e.purge)!==null&&r!==void 0?r:!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Q(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Q(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof pe&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof pe&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},zr=class{constructor(t){var e;let r="v1";t.catalogName&&(r+=`/${t.catalogName}`);const s=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Vr({baseUrl:s,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(e=t.accessDelegation)===null||e===void 0?void 0:e.join(","),this.namespaceOps=new Gr(this.client,r),this.tableOps=new Jr(this.client,r,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}},xe=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function Le(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ze=class extends xe{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},xt=class extends xe{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}},Yr=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Xr=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Ye=t=>{if(Array.isArray(t))return t.map(r=>Ye(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const i=r.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[i]=Ye(s)}),e},Qr=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function ge(t){"@babel/helpers - typeof";return ge=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ge(t)}function Zr(t,e){if(ge(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(ge(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function es(t){var e=Zr(t,"string");return ge(e)=="symbol"?e:e+""}function ts(t,e,r){return(e=es(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ut(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,s)}return r}function b(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};
27e%2?ut(Object(r),!0).forEach(function(s){ts(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ut(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var dt=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},rs=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const i=t;let n=parseInt(i.status,10);Number.isFinite(n)||(n=500),i.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||n+"";e(new ze(dt(a),n,o,s))}).catch(()=>{const a=n+"";e(new ze(i.statusText||`HTTP ${n} error`,n,a,s))})}else e(new xt(dt(t),t,s))},ss=(t,e,r,s)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||t==="HEAD"||!s?b(b({},i),r):(Xr(s)?(i.headers=b({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(s)):i.body=s,e!=null&&e.duplex&&(i.duplex=e.duplex),b(b({},i),r))};async function ce(t,e,r,s,i,n,a){return new Promise((o,l)=>{t(r,ss(e,s,i,n)).then(c=>{if(!c.ok)throw c;if(s!=null&&s.noResolveJson)return c;if(a==="vectors"){const h=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!h||!h.includes("application/json"))return{}}return c.json()}).then(c=>o(c)).catch(c=>rs(c,l,s,a))})}function Lt(t="storage"){return{get:async(e,r,s,i)=>ce(e,"GET",r,s,i,void 0,t),post:async(e,r,s,i,n)=>ce(e,"POST",r,i,n,s,t),put:async(e,r,s,i,n)=>ce(e,"PUT",r,i,n,s,t),head:async(e,r,s,i)=>ce(e,"HEAD",r,b(b({},s),{},{noResolveJson:!0}),i,void 0,t),remove:async(e,r,s,i,n)=>ce(e,"DELETE",r,i,n,s,t)}}var{get:ve,post:N,put:Xe,head:is,remove:rt}=Lt("storage"),I=Lt("vectors"),le=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Yr(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=b(b({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Le(r))return{data:null,error:r};throw r}}},ns=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Le(e))return{data:null,error:e};throw e}}},Dt;Dt=Symbol.toStringTag;var as=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Dt]="BlobDownloadBuilder",this.promise=null}asStream(){return new ns(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Le(e))return{data:null,error:e};throw e}}},os={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ft={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ls=class extends le{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var i=this;return i.handleOperation(async()=>{let n;const a=b(b({},ft),s);let o=b(b({},i.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;typeof Blob!="undefined"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",a.cacheControl),l&&n.append("metadata",i.encodeMetadata(l)),n.append("",r)):typeof FormData!="undefined"&&r instanceof FormData?(n=r,n.has("cacheControl")||n.append("cacheControl",a.cacheControl),l&&!n.has("metadata")&&n.append("metadata",i.encodeMetadata(l))):(n=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream!="undefined"&&n instanceof ReadableStream||n&&typeof n=="object"&&"pipe"in n&&typeof n.pipe=="function")&&!a.duplex&&(a.duplex="half")),s!=null&&s.headers&&(o=b(b({},o),s.headers));const c=i._removeEmptyFolders(e),h=i._getFinalPath(c),u=await(t=="PUT"?Xe:N)(i.fetch,`${i.url}/object/${h}`,n,b({headers:o},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{path:c,id:u.Id,fullPath:u.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}
27async uploadToSignedUrl(t,e,r,s){var i=this;const n=i._removeEmptyFolders(t),a=i._getFinalPath(n),o=new URL(i.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),i.handleOperation(async()=>{let l;const c=b(b({},ft),s),h=b(b({},i.headers),{"x-upsert":String(c.upsert)});return typeof Blob!="undefined"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData!="undefined"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType),{path:n,fullPath:(await Xe(i.fetch,o.toString(),l,{headers:h})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const i=b({},r.headers);e!=null&&e.upsert&&(i["x-upsert"]="true");const n=await N(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(r.url+n.url),o=a.searchParams.get("token");if(!o)throw new xe("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await N(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await N(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let i=s._getFinalPath(t);const n=typeof(r==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let a=await N(s.fetch,`${s.url}/object/sign/${i}`,b({expiresIn:e},n?{transform:r.transform}:{}),{headers:s.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"",l=n&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${l}${o}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const i=await N(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),n=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i.map(a=>b(b({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${n}`):null}))})}download(t,e,r){const s=typeof(e==null?void 0:e.transform)!="undefined"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((e==null?void 0:e.transform)||{}),n=i?`?${i}`:"",a=this._getFinalPath(t),o=()=>ve(this.fetch,`${this.url}/${s}/${a}${n}`,{headers:this.headers,noResolveJson:!0},r);return new as(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>Ye(await ve(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await is(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Le(i)){var s;const n=i instanceof ze?i.status:i instanceof xt?(s=i.originalError)===null||s===void 0?void 0:s.status:void 0;if(n!==void 0&&[400,404].includes(n))return{data:!1,error:i}}throw i}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=[],i=e!=null&&e.download?`download=${e.download===!0?"":e.download}`:"";i!==""&&s.push(i);const n=typeof(e==null?void 0:e.transform)!="undefined"?"render/image":"object",a=this.transformOptsToQueryString((e==null?void 0:e.transform)||{});a!==""&&s.push(a);let o=s.join("&");return o!==""&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}${o}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await rt(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const i=b(b(b({},os),e),{},{prefix:t||""});return await N(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=b({},t);return await N(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer!="undefined"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},we={"X-Client-Info":"storage-js/2.101.1"},cs=class extends le{constructor(t,e={},r,s){const i=new URL(t);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));const n=i.href.replace(/\/$/,""),a=b(b({},we),e);super(n,a,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await ve(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ve(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await N(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Xe(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await N(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await rt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},hs=class extends le{constructor(t,e={},r){const s=t.replace(/\/$/,""),i=b(b({},we),e);super(s,i,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await N(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>
27{const r=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const s=r.toString(),i=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await ve(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await rt(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Qr(t))throw new xe("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new zr({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(i,n){const a=i[n];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(i,o),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},us=class extends le{constructor(t,e={},r){const s=t.replace(/\/$/,""),i=b(b({},we),{},{"Content-Type":"application/json"},e);super(s,i,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await I.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await I.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},ds=class extends le{constructor(t,e={},r){const s=t.replace(/\/$/,""),i=b(b({},we),{},{"Content-Type":"application/json"},e);super(s,i,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},fs=class extends le{constructor(t,e={},r){const s=t.replace(/\/$/,""),i=b(b({},we),{},{"Content-Type":"application/json"},e);super(s,i,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await I.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},ps=class extends fs{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new gs(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},gs=class extends us{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,b(b({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,b(b({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new vs(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},vs=class extends ds{constructor(t,e,r,s,i){super(t,e,i),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,b(b({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,b(b({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,b(b({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,b(b({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,b(b({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},ys=class extends cs{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new ls(this.url,this.headers,t,this.fetch)}get vectors(){return new ps(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new hs(this.url+"/iceberg",this.headers,this.fetch)}},Bt="2.101.1",Pe=30*1e3;var De=3*Pe,ms="http://localhost:9999",ws="supabase.auth.token",bs={"X-Client-Info":`gotrue-js/${Bt}`},qt="X-Supabase-Api-Version",Ht={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},_s=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}
27$)$/i,Mi=600*1e3,ye=class extends Error{constructor(t,e,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=e,this.code=r}};function y(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var ks=class extends ye{constructor(t,e,r){super(t,e,r),this.name="AuthApiError",this.status=e,this.code=r}};function Ss(t){return y(t)&&t.name==="AuthApiError"}var z=class extends ye{constructor(t,e){super(t),this.name="AuthUnknownError",this.originalError=e}},H=class extends ye{constructor(t,e,r,s){super(t,r,s),this.name=e,this.status=r}},$=class extends H{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Be(t){return y(t)&&t.name==="AuthSessionMissingError"}var Z=class extends H{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ee=class extends H{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}},Te=class extends H{constructor(t,e=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=e}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function Es(t){return y(t)&&t.name==="AuthImplicitGrantRedirectError"}var pt=class extends H{constructor(t,e=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=e}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Ts=class extends H{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")}},Qe=class extends H{constructor(t,e){super(t,"AuthRetryableFetchError",e,void 0)}};function qe(t){return y(t)&&t.name==="AuthRetryableFetchError"}var gt=class extends H{constructor(t,e,r){super(t,"AuthWeakPasswordError",e,"weak_password"),this.reasons=r}},Ze=class extends H{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}},$e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),vt=` 28\r=`.split(""),As=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<vt.length;e+=1)t[vt[e].charCodeAt(0)]=-2;for(let e=0;e<$e.length;e+=1)t[$e[e].charCodeAt(0)]=e;return t})();function yt(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;)r($e[e.queue>>e.queuedBits-6&63]),e.queuedBits-=6;else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;)r($e[e.queue>>e.queuedBits-6&63]),e.queuedBits-=6}function Mt(t,e,r){const s=As[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function mt(t){const e=[],r=a=>{e.push(String.fromCodePoint(a))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=a=>{Cs(a,s,r)};for(let a=0;a<t.length;a+=1)Mt(t.charCodeAt(a),i,n);return e.join("")}function Rs(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Os(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const i=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}Rs(s,e)}}function Cs(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function oe(t){const e=[],r={queue:0,queuedBits:0},s=i=>{e.push(i)};for(let i=0;i<t.length;i+=1)Mt(t.charCodeAt(i),r,s);return new Uint8Array(e)}function Ps(t){const e=[];return Os(t,r=>e.push(r)),new Uint8Array(e)}function Y(t){const e=[],r={queue:0,queuedBits:0},s=i=>{e.push(i)};return t.forEach(i=>
28yt(i,r,s)),yt(null,r,s),e.join("")}function js(t){return Math.round(Date.now()/1e3)+t}function $s(){return Symbol("auth-callback")}var P=()=>typeof window!="undefined"&&typeof document!="undefined",V={tested:!1,writable:!1},Wt=()=>{if(!P())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(V.tested)return V.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),V.tested=!0,V.writable=!0}catch{V.tested=!0,V.writable=!1}return V.writable};function Is(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return r.searchParams.forEach((s,i)=>{e[i]=s}),e}var Ft=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Us=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",ne=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},G=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},C=async(t,e)=>{await t.removeItem(e)},Kt=class Vt{constructor(){this.promise=new Vt.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};Kt.promiseConstructor=Promise;function Ae(t){const e=t.split(".");if(e.length!==3)throw new Ze("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!_s.test(e[r]))throw new Ze("JWT not in base64url format");return{header:JSON.parse(mt(e[0])),payload:JSON.parse(mt(e[1])),signature:oe(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ns(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function xs(t,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const n=await t(i);if(!e(i,null,n)){r(n);return}}catch(n){if(!e(i,n)){s(n);return}}})()})}function Ls(t){return("0"+t.toString(16)).substr(-2)}function Ds(){const e=new Uint32Array(56);if(typeof crypto=="undefined"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";let i="";for(let n=0;n<56;n++)i+=r.charAt(Math.floor(Math.random()*66));return i}return crypto.getRandomValues(e),Array.from(e,Ls).join("")}async function Bs(t){const e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function qs(t){if(!(typeof crypto!="undefined"&&typeof crypto.subtle!="undefined"&&typeof TextEncoder!="undefined"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const e=await Bs(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ee(t,e,r=!1){const s=Ds();let i=s;r&&(i+="/PASSWORD_RECOVERY"),await ne(t,`${e}-code-verifier`,i);const n=await qs(s);return[n,s===n?"plain":"s256"]}var Hs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ms(t){const e=t.headers.get(qt);if(!e||!e.match(Hs))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Ws(t){if(!t)throw new Error("Missing exp claim");if(t<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}function Fs(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Ks=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function te(t){if(!Ks.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function He(){return new Proxy({},{get:(t,e)=>{if(e==="__isUserNotAvailableProxy")return!0;if(typeof e=="symbol"){const r=e.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${e}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,e)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${e}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,e)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${e}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Vs(t,e){return new Proxy(t,{get:(r,s,i)=>{if(s==="__isInsecureUserWarningProxy")return!0;
28if(typeof s=="symbol"){const n=s.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)"||n==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,i)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,s,i)}})}function wt(t){return JSON.parse(JSON.stringify(t))}var J=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Gs=[502,503,504];async function bt(t){var e;if(!Us(t))throw new Qe(J(t),0);if(Gs.includes(t.status))throw new Qe(J(t),t.status);let r;try{r=await t.json()}catch(n){throw new z(J(n),n)}let s;const i=Ms(t);if(i&&i.getTime()>=Ht["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new gt(J(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new $}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((n,a)=>n&&typeof a=="string",!0))throw new gt(J(r),t.status,r.weak_password.reasons);throw new ks(J(r),t.status||500,s)}var Js=(t,e,r,s)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};async function m(t,e,r,s){var i;const n=Object.assign({},s==null?void 0:s.headers);n["X-Supabase-Api-Version"]||(n[qt]=Ht["2024-01-01"].name),s!=null&&s.jwt&&(n.Authorization=`Bearer ${s.jwt}`);const a=(i=s==null?void 0:s.query)!==null&&i!==void 0?i:{};s!=null&&s.redirectTo&&(a.redirect_to=s.redirectTo);const o=await zs(t,e,r+(Object.keys(a).length?"?"+new URLSearchParams(a).toString():""),{headers:n,noResolveJson:s==null?void 0:s.noResolveJson},{},s==null?void 0:s.body);return s!=null&&s.xform?s==null?void 0:s.xform(o):{data:Object.assign({},o),error:null}}async function zs(t,e,r,s,i,n){const a=Js(e,s,i,n);let o;try{o=await t(r,Object.assign({},a))}catch(l){throw console.error(l),new Qe(J(l),0)}if(o.ok||await bt(o),s!=null&&s.noResolveJson)return o;try{return await o.json()}catch(l){await bt(l)}}function U(t){var e;let r=null;Qs(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=js(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function _t(t){const e=U(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function F(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Ys(t){return{data:t,error:null}}function Xs(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=t,a=Ne(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:e,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:Object.assign({},a)},error:null}}function kt(t){return t}function Qs(t){return t.access_token&&t.refresh_token&&t.expires_in}var Me=["global","local","others"],Zs=class{constructor({url:t="",headers:e={},fetch:r}){this.url=t,this.headers=e,this.fetch=Ft(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},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)}}async signOut(t,e=Me[0]){if(Me.indexOf(e)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Me.join(", ")}`);try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${e}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(y(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,e={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:e.data},headers:this.headers,redirectTo:e.redirectTo,xform:F})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:e}=t,r=Ne(t,["options"]),s=Object.assign(Object.assign({},r),e);return"newEmail"in r&&(s.new_email=r==null?void 0:r.newEmail,delete s.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Xs,redirectTo:e==null?void 0:e.redirectTo})}catch(e){if(y(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(t){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:F})}catch(e){if(y(e))return{data:{user:null},error:e};throw e}}async listUsers(t){var e,r,s,i,n,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(e=t==null?void 0:t.page)===null||e===void 0?void 0:e.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:kt});if(c.error)throw c.error;const h=await c.json(),u=(n=c.headers.get("x-total-count"))!==null&&n!==void 0?n:0,d=(o=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&o!==void 0?o:[];return d.length>
280&&(d.forEach(f=>{const p=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(f.split(";")[1].split("=")[1]);l[`${v}Page`]=p}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(y(l))return{data:{users:[]},error:l};throw l}}async getUserById(t){te(t);try{return await m(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:F})}catch(e){if(y(e))return{data:{user:null},error:e};throw e}}async updateUserById(t,e){te(t);try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:e,headers:this.headers,xform:F})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,e=!1){te(t);try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:e},xform:F})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){te(t.userId);try{const{data:e,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:e,error:r}}catch(e){if(y(e))return{data:null,error:e};throw e}}async _deleteFactor(t){te(t.userId),te(t.id);try{return{data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(e){if(y(e))return{data:null,error:e};throw e}}async _listOAuthClients(t){var e,r,s,i,n,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await m(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(e=t==null?void 0:t.page)===null||e===void 0?void 0:e.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:kt});if(c.error)throw c.error;const h=await c.json(),u=(n=c.headers.get("x-total-count"))!==null&&n!==void 0?n:0,d=(o=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&o!==void 0?o:[];return d.length>0&&(d.forEach(f=>{const p=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(f.split(";")[1].split("=")[1]);l[`${v}Page`]=p}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(y(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(t){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(y(e))return{data:null,error:e};throw e}}async _getOAuthClient(t){try{return await m(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(y(e))return{data:null,error:e};throw e}}async _updateOAuthClient(t,e){try{return await m(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await m(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(y(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(t){try{return await m(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(y(e))return{data:null,error:e};throw e}}async _listCustomProviders(t){try{const e={};return t!=null&&t.type&&(e.type=t.type),await m(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:e,xform:r=>{var s;return{data:{providers:(s=r==null?void 0:r.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(e){if(y(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(t){try{return await m(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(y(e))return{data:null,error:e};throw e}}async _getCustomProvider(t){try{return await m(this.fetch,"GET",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(y(e))return{data:null,error:e};throw e}}async _updateCustomProvider(t,e){try{return await m(this.fetch,"PUT",`${this.url}/admin/custom-providers/${t}`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(t){try{return await m(this.fetch,"DELET
28E",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(y(e))return{data:null,error:e};throw e}}};function St(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var x={debug:!!(globalThis&&Wt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Gt=class extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}},Et=class extends Gt{};async function ei(t,e,r){x.debug;const s=new globalThis.AbortController;let i;e>0&&(i=setTimeout(()=>{s.abort(),x.debug},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){clearTimeout(i),x.debug&&n.name;try{return await r()}finally{x.debug&&n.name}}else{if(e===0)throw x.debug,new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(x.debug)try{const a=await globalThis.navigator.locks.query();JSON.stringify(a,null," ")}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}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(i),await r()}})}catch(n){if(e>0&&clearTimeout(i),(n==null?void 0:n.name)==="AbortError"&&e>0){if(s.signal.aborted)return x.debug,console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}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(t,{mode:"exclusive",steal:!0},async a=>{if(a){x.debug&&a.name;try{return await r()}finally{x.debug&&a.name}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw x.debug,new Et(`Lock "${t}" was released because another request stole it`)}throw n}}function ti(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self!="undefined"&&(self.globalThis=self)}}function Jt(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function ri(t){return parseInt(t,16)}function si(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function ii(t){var e;const{chainId:r,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:h,uri:u,version:d}=t;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(d!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(` 29`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`);const f=Jt(t.address),p=`${h?`${h}://${s}`:s} wants you to sign in with your Ethereum account: 30${f} 31 32${t.statement?`${t.statement} 33`:""}`;let v=`URI: ${u} 34Version: ${d} 35Chain ID: ${r}${a?` 36Nonce: ${a}`:""} 37Issued At: ${n.toISOString()}`;if(i&&(v+=` 38Expiration Time: ${i.toISOString()}`),o&&(v+=` 39Not Before: ${o.toISOString()}`),l&&(v+=` 40Request ID: ${l}`),c){let g=` 41Resources:`;for(const k of c){if(!k||typeof k!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${k}`);g+=` 42- ${k}`}v+=g}return`${p} 43${v}`}
43var R=class extends Error{constructor({message:t,code:e,cause:r,name:s}){var i;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s!=null?s:r instanceof Error?r.name:void 0)!==null&&i!==void 0?i:"Unknown Error",this.code=e}},Ie=class extends R{constructor(t,e){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e,message:t}),this.name="WebAuthnUnknownError",this.originalError=e}};function ni({error:t,options:e}){var r,s,i;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new R({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=n.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new R({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=n.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new R({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=n.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new R({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new R({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new R({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return n.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new R({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new R({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(zt(a)){if(n.rp.id!==a)return new R({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new R({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new R({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new R({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new R({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function ai({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new R({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new R({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(zt(s)){if(r.rpId!==s)return new R({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new R({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new R({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new R({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var oi=class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}},li=new oi;function ci(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential!="undefined"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,i=Ne(t,["challenge","user","excludeCredentials"]),n=oe(e).buffer,a=Object.assign(Object.assign({},r),{id:oe(r.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:n,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const c=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:oe(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return o}function hi(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential!="undefined"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=Ne(t,["challenge","allowCredentials"]),i=oe(e).buffer,n=Object.assign(Object.assign({}
43,s),{challenge:i});if(r&&r.length>0){n.allowCredentials=new Array(r.length);for(let a=0;a<r.length;a++){const o=r[a];n.allowCredentials[a]=Object.assign(Object.assign({},o),{id:oe(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return n}function ui(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:Y(new Uint8Array(t.response.attestationObject)),clientDataJSON:Y(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function di(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Y(new Uint8Array(i.authenticatorData)),clientDataJSON:Y(new Uint8Array(i.clientDataJSON)),signature:Y(new Uint8Array(i.signature)),userHandle:i.userHandle?Y(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function zt(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Tt(){var t,e;return!!(P()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function fi(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ie("Browser returned unexpected credential type",e)}:{data:null,error:new Ie("Empty credential response",e)}}catch(e){return{data:null,error:ni({error:e,options:t})}}}async function pi(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ie("Browser returned unexpected credential type",e)}:{data:null,error:new Ie("Empty credential response",e)}}catch(e){return{data:null,error:ai({error:e,options:t})}}}var gi={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},vi={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ue(...t){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),s={};for(const i of t)if(i)for(const n in i){const a=i[n];if(a!==void 0)if(Array.isArray(a))s[n]=a;else if(r(a))s[n]=a;else if(e(a)){const o=s[n];e(o)?s[n]=Ue(o,a):s[n]=Ue(a)}else s[n]=a}return s}function yi(t,e){return Ue(gi,t,e||{})}function mi(t,e){return Ue(vi,t,e||{})}var wi=class{constructor(t){this.client=t,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(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:e,friendlyName:r,signal:s},i){var n;try{const{data:a,error:o}=await this.client.mfa.challenge({factorId:t,webauthn:e});if(!a)return{data:null,error:o};const l=s!=null?s:li.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){const h=r;if(h)c.name=`${c.id}:${h}`;else{const u=(await this.client.getUser()).data.user,d=((n=u==null?void 0:u.user_metadata)===null||n===void 0?void 0:n.name)||(u==null?void 0:u.email)||(u==null?void 0:u.id)||"User";c.name=`${c.id}:${d}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{const{data:c,error:h}=await fi({publicKey:yi(a.webauthn.credential_options.publicKey,i==null?void 0:i.create),signal:l});return c?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:c}},error:null}:{data:null,error:h}}case"request":{const c=mi(a.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:u}=await pi(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:l}));return h?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:u}}}}catch(a){return y(a)?{data:null,error:a}:{data:null,error:new z("Unexpected error in challenge",a)}}}async _verify({challengeId:t,factorId:e,webauthn:r}){return this.client.mfa.verify({factorId:e,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:e=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:r=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!e)return{data:null,error:new ye("rpId is required for WebAuthn authentication")};try{if(!Tt())return{data:null,error:new z("Browser does not support WebAuthn",null)};const{data:n,error:a}=await this.challenge({factorId:t,webauthn:{rpId:e,rpOrigins:r},signal:s},{request:i});if(!n)return{data:null,error:a};const{webauthn:o}=n;return this._verify({factorId:t,challengeId:n.challengeId,webauthn:{type:o.type,rpId:e,rpOrigins:r,credential_response:o.credential_response}})}catch(n){return y(n)?{data:null,error:n}:{data:null,error:new z("Unexpected error in authenticate",n)}}}async _register({friendlyName:t,webauthn:{rpId:e=typeof window!="undefined"?window.location.hostname:void 0,rpOrigins:r=typeof window!="undefined"?[window.location.origin]:void 0,signal:s}={}},i){if(!e)return{data:null,error:new ye("rpId is required for WebAuthn registration")};try{if(!Tt())return{data:null,error:new z("Browser does not support WebAuthn",null)};const{data:n,error:a}=await this._enroll({friendlyName:t});if(!n)return await this.client.mfa.listFactors().then(c=>{var h;
43return(h=c.data)===null||h===void 0?void 0:h.all.find(u=>u.factor_type==="webauthn"&&u.friendly_name===t&&u.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c==null?void 0:c.id}):void 0),{data:null,error:a};const{data:o,error:l}=await this._challenge({factorId:n.id,friendlyName:n.friendly_name,webauthn:{rpId:e,rpOrigins:r},signal:s},{create:i});return o?this._verify({factorId:n.id,challengeId:o.challengeId,webauthn:{rpId:e,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:l}}catch(n){return y(n)?{data:null,error:n}:{data:null,error:new z("Unexpected error in register",n)}}}};ti();var bi={url:ms,storageKey:ws,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:bs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function At(t,e,r){return await r()}var re={},Yt=class et{get jwks(){var e,r;return(r=(e=re[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){re[this.storageKey]=Object.assign(Object.assign({},re[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=re[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){re[this.storageKey]=Object.assign(Object.assign({},re[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,i;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;const n=Object.assign(Object.assign({},bi),e);if(this.storageKey=n.storageKey,this.instanceID=(r=et.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,et.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,typeof n.debug=="function"&&(this.logger=n.debug),this.instanceID>0&&P()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.admin=new Zs({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=Ft(n.fetch),this.lock=n.lock||At,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,this.throwOnError=n.throwOnError,this.lockAcquireTimeout=n.lockAcquireTimeout,n.lock?this.lock=n.lock:this.persistSession&&P()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=ei:this.lock=At,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new wi(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(n.storage?this.storage=n.storage:Wt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=St(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=St(this.memoryStorage)),P()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}n.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Bt}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(P()&&(r=Is(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),P()&&this.detectSessionInUrl&&s!=="none"){const{data:i,error:n}=await this._getSessionFromURL(r,s);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),Es(n)){const l=(e=n.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:n}}return{error:n}}const{session:a,redirectType:o}=i;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return y(r)?this._returnResult({error:r}):this._returnResult({error:new z("Unexpected error during initialization",r)}
43)}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,i;try{const{data:n,error:a}=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:U});if(a||!n)return this._returnResult({data:{user:null,session:null},error:a});const o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(n){if(y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signUp(e){var r,s,i;try{let n;if("email"in e){const{email:h,password:u,options:d}=e;let f=null,p=null;this.flowType==="pkce"&&([f,p]=await ee(this.storage,this.storageKey)),n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:h,password:u,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:f,code_challenge_method:p},xform:U})}else if("phone"in e){const{phone:h,password:u,options:d}=e;n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:u,data:(s=d==null?void 0:d.data)!==null&&s!==void 0?s:{},channel:(i=d==null?void 0:d.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:U})}else throw new Ee("You must provide either an email or phone number and a password");const{data:a,error:o}=n;if(o||!a)return await C(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(n){if(await C(this.storage,`${this.storageKey}-code-verifier`),y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithPassword(e){try{let r;if("email"in e){const{email:n,password:a,options:o}=e;r=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:_t})}else if("phone"in e){const{phone:n,password:a,options:o}=e;r=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:_t})}else throw new Ee("You must provide either an email or phone number and a password");const{data:s,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!s||!s.session||!s.user){const n=new Z;return this._returnResult({data:{user:null,session:null},error:n})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,i,n,a,o,l,c,h,u,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:v,wallet:g,statement:k,options:_}=e;let w;if(P())if(typeof g=="object")w=g;else{const K=window;if("ethereum"in K&&typeof K.ethereum=="object"&&"request"in K.ethereum&&typeof K.ethereum.request=="function")w=K.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof g!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=g}const T=new URL((r=_==null?void 0:_.url)!==null&&r!==void 0?r:window.location.href),M=await w.request({method:"eth_requestAccounts"}).then(K=>K).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!M||M.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const E=Jt(M[0]);let O=(s=_==null?void 0:_.signInWithEthereum)===null||s===void 0?void 0:s.chainId;O||(O=ri(await w.request({method:"eth_chainId"}))),f=ii({domain:T.host,address:E,statement:k,uri:T.href,version:"1",chainId:O,nonce:(i=_==null?void 0:_.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(a=(n=_==null?void 0:_.signInWithEthereum)===null||n===void 0?void 0:n.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=_==null?void 0:_.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=_==null?void 0:_.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=_==null?void 0:_.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(h=_==null?void 0:_.signInWithEthereum)===null||h===void 0?void 0:h.resources}),p=await w.request({method:"personal_sign",params:[si(f),E]})}try{const{data:v,error:g}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:p},!((u=e.options)===null||u===void 0)&&u.captchaToken?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:U});if(g)throw g;if(!v||!v.session||!v.user){const k=new Z;return this._returnResult({data:{user:null,session:null},error:k})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:g})}catch(v){if(y(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,s,i,n,a,o,l,c,h,u,d,f;let p,v;if("message"in e)p=e.message,v=e.signature;else{const{chain:g,wallet:k,statement:_,options:w}=e;let T;if(P())if(typeof k=="object")T=k;else{const E=window;if("solana"in E&&typeof E.solana=="object"&&("signIn"in E.solana&&typeof E.solana.signIn=="function"||"signMessage"in E.solana&&typeof E.solana.signMessage=="function"))T=E.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof k!="object"||!(w!=null&&w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");T=k}const M=new URL((r=w==null?void 0:w.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in T&&T.signIn){const E=await T.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w==null?void 0:w.signInWithSolana),{version:"1",domain:M.host,uri:M.href}),_?{statement:_}:null));let O;if(Array.isArray(E)&&E[0]&&typeof E[0]=="object")O=E[0];else if(E&&typeof E=="object"&&"signedMessage"in E&&"signature"in E)O=E;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in O&&"signature"in O&&(typeof O.signedMessage=="string"||O.signedMessage instanceof Uint8Array)&&O.signature instanceof Uint8Array)p=typeof O.signedMessage=="string"?O.signedMessage:new TextDecoder().decode(O.signedMessage),v=O.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in T)||typeof T.signMessage!="function"||!("publicKey"in T)||typeof T!="object"||!T.publicKey||!("toBase58"in T.publicKey)||typeof T.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${M.host} wants you to sign in with your Solana account:`,T.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${M.href}`,`Issued At: ${(i=(s=w==null?void 0:w.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((n=w==null?void 0:w.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((a=w==null?void 0:w.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((o=w==null?void 0:w.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((l=w==null?void 0:w.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((c=w==null?void 0:w.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((u=(h=w==null?void 0:w.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||u===void 0)&&u.length?["Resources",...w.sign
43InWithSolana.resources.map(O=>`- ${O}`)]:[]].join(` 44`);const E=await T.signMessage(new TextEncoder().encode(p),"utf8");if(!E||!(E instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=E}}try{const{data:g,error:k}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:Y(v)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:U});if(k)throw k;if(!g||!g.session||!g.user){const _=new Z;return this._returnResult({data:{user:null,session:null},error:_})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:k})}catch(g){if(y(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async _exchangeCodeForSession(e){const r=await G(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(r!=null?r:"").split("/");try{if(!s&&this.flowType==="pkce")throw new Ts;const{data:n,error:a}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:U});if(await C(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!n||!n.session||!n.user){const o=new Z;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign(Object.assign({},n),{redirectType:i!=null?i:null}),error:a})}catch(n){if(await C(this.storage,`${this.storageKey}-code-verifier`),y(n))return this._returnResult({data:{user:null,session:null,redirectType:null},error:n});throw n}}async signInWithIdToken(e){try{const{options:r,provider:s,token:i,access_token:n,nonce:a}=e,{data:o,error:l}=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:a,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:U});if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o||!o.session||!o.user){const c=new Z;return this._returnResult({data:{user:null,session:null},error:c})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:l})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,i,n,a;try{if("email"in e){const{email:o,options:l}=e;let c=null,h=null;this.flowType==="pkce"&&([c,h]=await ee(this.storage,this.storageKey));const{error:u}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:u})}if("phone"in e){const{phone:o,options:l}=e,{data:c,error:h}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(i=l==null?void 0:l.data)!==null&&i!==void 0?i:{},create_user:(n=l==null?void 0:l.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(a=l==null?void 0:l.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:h})}throw new Ee("You must provide either an email or phone number.")}catch(o){if(await C(this.storage,`${this.storageKey}-code-verifier`),y(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var r,s;try{let i,n;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:a,error:o}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:U});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(y(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,s,i,n,a;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await ee(this.storage,this.storageKey));const c=await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}
44:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:Ys});return!((n=c.data)===null||n===void 0)&&n.url&&P()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await C(this.storage,`${this.storageKey}-code-verifier`),y(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new $;const{error:i}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(y(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:i,options:n}=e,{error:a}=await m(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},redirectTo:n==null?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:s,type:i,options:n}=e,{data:a,error:o}=await m(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new Ee("You must provide either an email or phone number and a type")}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{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!",new Error().stack);try{let e=null;const r=await G(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<De:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const a=await G(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=He()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Vs(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{session:null},error:n}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:F}):await this._useSession(async r=>{var s,i,n;const{data:a,error:o}=r;if(o)throw o;return!(!((s=a.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new $}:await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=a.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:F})})}catch(r){if(y(r))return Be(r)&&(await this._removeSession(),await C(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new $;const a=i.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await ee(this.storage,this.storageKey));const{data:c,error:h}=await m(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({}
44,e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:F});if(h)throw h;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(s){if(await C(this.storage,`${this.storageKey}-code-verifier`),y(s))return this._returnResult({data:{user:null},error:s});throw s}}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 $;const r=Date.now()/1e3;let s=r,i=!0,n=null;const{payload:a}=Ae(e.access_token);if(a.exp&&(s=a.exp,i=s<=r),i){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};n=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});n={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(r){if(y(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}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 r=>{var s;if(!e){const{data:a,error:o}=r;if(o)throw o;e=(s=a.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new $;const{data:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!P())throw new Te("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Te(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new pt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Te("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new pt("No code detected.");const{data:_,error:w}=await this._exchangeCodeForSession(e.code);if(w)throw w;const T=new URL(window.location.href);return T.searchParams.delete("code"),window.history.replaceState(window.history.state,"",T.toString()),{data:{session:_.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:o,expires_at:l,token_type:c}=e;if(!n||!o||!a||!c)throw new Te("No session defined in URL");const h=Math.round(Date.now()/1e3),u=parseInt(o);let d=h+u;l&&(d=parseInt(l));const f=d-h;f*1e3<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);const p=d-u;h-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,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,d,h);const{data:v,error:g}=await this._getUser(n);if(g)throw g;const k={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:a,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:k,redirectType:e.type},error:null})}catch(s){if(y(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await G(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}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 r=>{var s;const{data:i,error:n}=r;if(n&&!Be(n))return this._returnResult({error:n});const a=(s=i.session)===null||s===void 0?void 0:s.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);
44if(o&&!(Ss(o)&&(o.status===404||o.status===401||o.status===403)||Be(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await C(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=$s(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,i;try{const{data:{session:n},error:a}=r;if(a)throw a;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,r={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await ee(this.storage,this.storageKey,!0));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(n){if(await C(this.storage,`${this.storageKey}-code-verifier`),y(n))return this._returnResult({data:null,error:n});throw n}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:i}=await this._useSession(async n=>{var a,o,l,c,h;const{data:u,error:d}=n;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await m(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(i)throw i;return P()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(y(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:i,data:{session:n}}=r;if(i)throw i;const{options:a,provider:o,token:l,access_token:c,nonce:h}=e,{data:u,error:d}=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=n==null?void 0:n.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:c,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:U});return d?this._returnResult({data:{user:null,session:null},error:d}):!u||!u.session||!u.user?this._returnResult({data:{user:null,session:null},error:new Z}):(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d}))}catch(i){if(await C(this.storage,`${this.storageKey}-code-verifier`),y(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,i;const{data:n,error:a}=r;if(a)throw a;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await xs(async i=>(i>0&&await Ns(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:U})),(i,n)=>{const a=200*Math.pow(2,i);return n&&qe(n)&&Date.now()+a-s<3e4})}catch(s){if(this._debug(r,"error",s),y(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),P()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const i=await G(this.storage,this.storageKey);if(i&&this.userStorage){let a=await G(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:i.user},await ne(this.userStorage,this.storageKey+"-user",a)),i.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:He()}else if(i&&!i.user&&!i.user){const a=await G(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(i.user=a.user,await C(this.storage,this.storageKey+"-user"),await ne(this.storage,this.storageKey,i)):i.user=He()}
44if(this._debug(s,"session from storage",i),!this._isValidSession(i)){this._debug(s,"session is not valid"),i!==null&&await this._removeSession();return}const n=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<De;if(this._debug(s,`session has${n?"":" not"} expired with margin of ${De}s`),n){if(this.autoRefreshToken&&i.refresh_token){const{error:a}=await this._callRefreshToken(i.refresh_token);a&&(console.error(a),qe(a)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(i.access_token);!o&&(a!=null&&a.user)?(i.user=a.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(s,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(s,"error",i),console.error(i);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new $;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Kt;const{data:n,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!n.session)throw new $;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);const o={data:n.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(n){if(this._debug(i,"error",n),y(n)){const a={data:null,error:n};return qe(n)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(a),a}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,s=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const n=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){n.push(l)}});if(await Promise.all(a),n.length>0){for(let o=0;o<n.length;o+=1)console.error(n[o]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await C(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await ne(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const n=wt(i);await ne(this.storage,this.storageKey,n)}else{const i=wt(r);await ne(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await C(this.storage,this.storageKey),await C(this.storage,this.storageKey+"-code-verifier"),await C(this.storage,this.storageKey+"-user"),this.userStorage&&await C(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&P()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Pe);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((s.expires_at*1e3-e)/Pe);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Pe}ms, refresh threshold is 3 ticks`),i<=3&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Gt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!P()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(
44await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const i=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[n,a]=await ee(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(a)}`});i.push(o.toString())}if(s!=null&&s.queryParams){const n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s!=null&&s.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:i,error:n}=r;return n?this._returnResult({data:null,error:n}):await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,i;const{data:n,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await m(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:i,error:n}=r;if(n)return this._returnResult({data:null,error:n});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?ui(e.webauthn.credential_response):di(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:l}))})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:i,error:n}=r;if(n)return this._returnResult({data:null,error:n});const a=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});if(a.error)return a;const{data:o}=a;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:ci(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:hi(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const i={all:[],phone:[],totp:[],webauthn:[]};for(const n of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])i.all.push(n),n.status==="verified"&&i[n.factor_type].push(n);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,i,n;if(e)try{const{payload:d}=Ae(e);let f=null;d.aal&&(f=d.aal);let p=f;const{data:{user:v},error:g}=await this.getUser(e);if(g)return this._returnResult({data:null,error:g});((s=(r=v==null?void 0:v.factors)===null||r===void 0?void 0:r.filter(_=>_.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(p="aal2");const k=d.amr||[];return{data:{currentLevel:f,nextLevel:p,currentAuthenticationMethods:k},error:null}}catch(d){if(y(d))return this._returnResult({data:null,error:d});throw d}const{data:{session:a},error:o}
44=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Ae(a.access_token);let c=null;l.aal&&(c=l.aal);let h=c;((n=(i=a.user.factors)===null||i===void 0?void 0:i.filter(d=>d.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(h="aal2");const u=l.amr||[];return{data:{currentLevel:c,nextLevel:h,currentAuthenticationMethods:u},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;return i?this._returnResult({data:null,error:i}):s?await m(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new $})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:i},error:n}=s;if(n)return this._returnResult({data:null,error:n});if(!i)return this._returnResult({data:null,error:new $});const a=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&P()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:i},error:n}=s;if(n)return this._returnResult({data:null,error:n});if(!i)return this._returnResult({data:null,error:new $});const a=await m(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&P()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await m(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new $})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;return i?this._returnResult({data:null,error:i}):s?(await m(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new $})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const i=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+6e5>i)return s;const{data:n,error:a}=await m(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!n.keys||n.keys.length===0||(this.jwks=n,this.jwks_cached_at=i,s=n.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:d,error:f}
44=await this.getSession();if(f||!d.session)return this._returnResult({data:null,error:f});s=d.session.access_token}const{header:i,payload:n,signature:a,raw:{header:o,payload:l}}=Ae(s);r!=null&&r.allowExpired||Ws(n.exp);const c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!c){const{error:d}=await this.getUser(s);if(d)throw d;return{data:{claims:n,header:i,signature:a},error:null}}const h=Fs(i.alg),u=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,u,a,Ps(`${o}.${l}`)))throw new Ze("Invalid JWT signature");return{data:{claims:n,header:i,signature:a},error:null}}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}};Yt.nextInstanceID={};var _i=Yt,ki="2.101.1",ue="";typeof Deno!="undefined"?ue="deno":typeof document!="undefined"?ue="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?ue="react-native":ue="node";var Si={headers:{"X-Client-Info":`supabase-js-${ue}/${ki}`}},Ei={schema:"public"},Ti={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ai={};function me(t){"@babel/helpers - typeof";return me=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},me(t)}function Ri(t,e){if(me(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(me(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Oi(t){var e=Ri(t,"string");return me(e)=="symbol"?e:e+""}function Ci(t,e,r){return(e=Oi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Rt(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,s)}return r}function A(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Rt(Object(r),!0).forEach(function(s){Ci(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Rt(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Pi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),ji=()=>Headers,$i=(t,e,r)=>{const s=Pi(r),i=ji();return async(n,a)=>{var o;const l=(o=await e())!==null&&o!==void 0?o:t;let c=new i(a==null?void 0:a.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(n,A(A({},a),{},{headers:c}))}};function Ii(t){return t.endsWith("/")?t:t+"/"}function Ui(t,e){var r,s;const{db:i,auth:n,realtime:a,global:o}=t,{db:l,auth:c,realtime:h,global:u}=e,d={db:A(A({},l),i),auth:A(A({},c),n),realtime:A(A({},h),a),storage:{},global:A(A(A({},u),o),{},{headers:A(A({},(r=u==null?void 0:u.headers)!==null&&r!==void 0?r:{}),(s=o==null?void 0:o.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?d.accessToken=t.accessToken:delete d.accessToken,d}function Ni(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Ii(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var xi=class extends _i{constructor(t){super(t)}},Li=class{constructor(t,e,r){var s,i;this.supabaseUrl=t,this.supabaseKey=e;const n=Ni(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",n),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",n),this.storageUrl=new URL("storage/v1",n),this.functionsUrl=new URL("functions/v1",n);const a=`sb-${n.hostname.split(".")[0]}-auth-token`,o={db:Ei,realtime:Ai,auth:A(A({},Ti),{},{storageKey:a}),global:Si},l=Ui(r!=null?r:{},o);if(this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(h,u)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(u)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=$i(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(A({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new lr(new URL("rest/v1",n).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new ys(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new er(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:n,flowType:a,lock:o,debug:l,throwOnError:c},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new xi({url:this.authUrl.href,headers:A(A({},d),h),storageKey:n,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:o,debug:l,throwOnError:c,fetch:u,hasCu
44stomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Wr(this.realtimeUrl.href,A(A({},t),{},{params:A(A({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Wi=(t,e,r)=>new Li(t,e,r);function Di(){if(typeof window!="undefined")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Di()&&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");var Ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ct=` 45\r=`.split(""),Fi=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Ct.length;e+=1)t[Ct[e].charCodeAt(0)]=-2;for(let e=0;e<Ot.length;e+=1)t[Ot[e].charCodeAt(0)]=e;return t})(),We;if(typeof process!="undefined"&&(!((We={})===null||We===void 0)&&We.npm_package_name)){const t={}.npm_package_name;["@supabase/auth-helpers-nextjs","@supabase/auth-helpers-react","@supabase/auth-helpers-remix","@supabase/auth-helpers-sveltekit"].includes(t)&&console.warn(` 46ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 47â â ï¸ IMPORTANT: Package Consolidation Notice â 48â â 49â The ${t.padEnd(35)} package name is deprecated. â 50â â 51â You are now using @supabase/ssr - a unified solution for all frameworks. â 52â â 53â The auth-helpers packages have been consolidated into @supabase/ssr â 54â to provide better maintenance and consistent APIs across frameworks. â 55â â 56â Please update your package.json to use @supabase/ssr directly: â 57â npm uninstall ${t.padEnd(42)} â 58â npm install @supabase/ssr â 59â â 60â For more information, visit: â 61â https://supabase.com/docs/guides/auth/server-side â 62ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 63 `)}export{ei as n,it as r,Wi as t};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.