PageSourceSearch

https://growth-sync.com/_next/static/immutable/chunks/41kh3g4g5ka0b.js

js growth-sync.com collected 2026-10-02 01:31:21 UTC 235,716 bytes, 4 lines download raw bytes

1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="c533d350-387c-ec81-4448-761cc60e773d")}catch(e){}}();
2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,529225,972390,14602,999309,e=>{"use strict";let t,r;class s extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class n extends s{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class i extends s{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class a extends s{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}function o(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,s=Object.getOwnPropertySymbols(e);n<s.length;n++)0>t.indexOf(s[n])&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(r[s[n]]=e[s[n]]);return r}(w=b||(b={})).Any="any",w.ApNortheast1="ap-northeast-1",w.ApNortheast2="ap-northeast-2",w.ApSouth1="ap-south-1",w.ApSoutheast1="ap-southeast-1",w.ApSoutheast2="ap-southeast-2",w.CaCentral1="ca-central-1",w.EuCentral1="eu-central-1",w.EuWest1="eu-west-1",w.EuWest2="eu-west-2",w.EuWest3="eu-west-3",w.SaEast1="sa-east-1",w.UsEast1="us-east-1",w.UsWest1="us-west-1",w.UsWest2="us-west-2";"function"==typeof SuppressedError&&SuppressedError;class l{setAuth(e){this.headers.Authorization="Bearer ".concat(e)}invoke(e){var t,r,s,o;return t=this,r=arguments,s=void 0,o=function*(e){var t;let r,s,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{let l,{headers:c,method:u,body:h,signal:d,timeout:f}=o,p={},{region:g}=o;g||(g=this.region);let y=new URL("".concat(this.url,"/").concat(e));g&&"any"!==g&&(p["x-region"]=g,y.searchParams.set("forceFunctionRegion",g)),h&&(c&&!Object.prototype.hasOwnProperty.call(c,"Content-Type")||!c)?"u">typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",l=h):"string"==typeof h?(p["Content-Type"]="text/plain",l=h):"u">typeof FormData&&h instanceof FormData?l=h:(p["Content-Type"]="application/json",l=JSON.stringify(h)):l=!h||"string"==typeof h||"u">typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer||"u">typeof FormData&&h instanceof FormData?h:JSON.stringify(h);let m=d;f&&(s=new AbortController,r=setTimeout(()=>s.abort(),f),d?(m=s.signal,d.addEventListener("abort",()=>s.abort())):m=s.signal);let w=yield this.fetch(y.toString(),{method:u||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),c),body:l,signal:m}).catch(e=>{throw new n(e)}),b=w.headers.get("x-relay-error");if(b&&"true"===b)throw new i(w);if(!w.ok)throw new a(w);let v=(null!=(t=w.headers.get("Content-Type"))?t:"text/plain").split(";")[0].trim();return{data:"application/json"===v?yield w.json():"application/octet-stream"===v||"application/pdf"===v?yield w.blob():"text/event-stream"===v?w:"multipart/form-data"===v?yield w.formData():yield w.text(),error:null,response:w}}catch(e){return{data:null,error:e,response:e instanceof a||e instanceof i?e.context:void 0}}finally{r&&clearTimeout(r)}},new(s||(s=Promise))(function(e,n){function i(e){try{l(o.next(e))}catch(e){n(e)}}function a(e){try{l(o.throw(e))}catch(e){n(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof s?r:new s(function(e){e(r)})).then(i,a)}l((o=o.apply(t,r||[])).next())})}constructor(e,{headers:t={},customFetch:r,region:s=b.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)})(r)}}var c,u,h,d,f,p,g,y,m,w,b,v,_,S,k,E,T,A,O,R,I,C=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.co
2de=e.code}},P=class{throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,s,n,i;let a=null,o=null,l=null,c=e.status,u=e.statusText;if(e.ok){if("HEAD"!==r.method){let t=await e.text();""===t||(o="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null==(n=r.headers.get("Accept"))?void 0:n.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}let i=null==(t=r.headers.get("Prefer"))?void 0:t.match(/count=(exact|planned|estimated)/),h=null==(s=e.headers.get("content-range"))?void 0:s.split("/");i&&h&&h.length>1&&(l=parseInt(h[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:"Results contain ".concat(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,u="Not Acceptable"):o=1===o.length?o[0]:null)}else{let t=await e.text();try{a=JSON.parse(t),Array.isArray(a)&&404===e.status&&(o=[],a=null,c=200,u="OK")}catch(r){404===e.status&&""===t?(c=204,u="No Content"):a={message:t}}if(a&&r.isMaybeSingle&&(null==a||null==(i=a.details)?void 0:i.includes("0 rows"))&&(a=null,c=200,u="OK"),a&&r.shouldThrowOnError)throw new C(a)}return{error:a,data:o,count:l,status:c,statusText:u}});return this.shouldThrowOnError||(s=s.catch(e=>{var t,r,s,n,i,a;let o="",l=null==e?void 0:e.cause;if(l){let t=null!=(r=null==l?void 0:l.message)?r:"",a=null!=(s=null==l?void 0:l.code)?s:"";o="".concat(null!=(n=null==e?void 0:e.name)?n:"FetchError",": ").concat(null==e?void 0:e.message)+"\n\nCaused by: ".concat(null!=(i=null==l?void 0:l.name)?i:"Error",": ").concat(t),a&&(o+=" (".concat(a,")")),(null==l?void 0:l.stack)&&(o+="\n".concat(l.stack))}else o=null!=(a=null==e?void 0:e.stack)?a:"";return{error:{message:"".concat(null!=(t=null==e?void 0:e.name)?t:"FetchError",": ").concat(null==e?void 0:e.message),details:o,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!=(t=e.shouldThrowOnError)&&t,this.signal=e.signal,this.isMaybeSingle=null!=(r=e.isMaybeSingle)&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}},j=class extends P{select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e){let{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=n?"".concat(n,".order"):"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,"".concat(a?"".concat(a,","):"").concat(e,".").concat(t?"asc":"desc").concat(void 0===r?"":r?".nullsfirst":".nullslast")),this}limit(e){let{foreignTable:t,referencedTable:r=t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.url.searchParams.set(void 0===r?"limit":"".concat(r,".limit"),"".concat(e)),this}range(e,t){let{foreignTable:r,referencedTable:s=r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=void 0===s?"offset":"".concat(s,".offset"),i=void 0===s?"limit":"".concat(s,".limit");return this.url.searchParams.set(n,"".concat(e)),this.url.searchParams.set(i,"".concat(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain(){var e;
2let{analyze:t=!1,verbose:r=!1,settings:s=!1,buffers:n=!1,wal:i=!1,format:a="text"}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=[t?"analyze":null,r?"verbose":null,s?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!=(e=this.headers.get("Accept"))?e:"application/json";return this.headers.set("Accept","application/vnd.pgrst.plan+".concat(a,'; for="').concat(l,'"; options=').concat(o,";")),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer","max-affected=".concat(e)),this}};let x=RegExp("[,()]");var U=class extends j{eq(e,t){return this.url.searchParams.append(e,"eq.".concat(t)),this}neq(e,t){return this.url.searchParams.append(e,"neq.".concat(t)),this}gt(e,t){return this.url.searchParams.append(e,"gt.".concat(t)),this}gte(e,t){return this.url.searchParams.append(e,"gte.".concat(t)),this}lt(e,t){return this.url.searchParams.append(e,"lt.".concat(t)),this}lte(e,t){return this.url.searchParams.append(e,"lte.".concat(t)),this}like(e,t){return this.url.searchParams.append(e,"like.".concat(t)),this}likeAllOf(e,t){return this.url.searchParams.append(e,"like(all).{".concat(t.join(","),"}")),this}likeAnyOf(e,t){return this.url.searchParams.append(e,"like(any).{".concat(t.join(","),"}")),this}ilike(e,t){return this.url.searchParams.append(e,"ilike.".concat(t)),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,"ilike(all).{".concat(t.join(","),"}")),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,"ilike(any).{".concat(t.join(","),"}")),this}regexMatch(e,t){return this.url.searchParams.append(e,"match.".concat(t)),this}regexIMatch(e,t){return this.url.searchParams.append(e,"imatch.".concat(t)),this}is(e,t){return this.url.searchParams.append(e,"is.".concat(t)),this}isDistinct(e,t){return this.url.searchParams.append(e,"isdistinct.".concat(t)),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&x.test(e)?'"'.concat(e,'"'):"".concat(e)).join(",");return this.url.searchParams.append(e,"in.(".concat(r,")")),this}notIn(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&x.test(e)?'"'.concat(e,'"'):"".concat(e)).join(",");return this.url.searchParams.append(e,"not.in.(".concat(r,")")),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,"cs.".concat(t)):Array.isArray(t)?this.url.searchParams.append(e,"cs.{".concat(t.join(","),"}")):this.url.searchParams.append(e,"cs.".concat(JSON.stringify(t))),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,"cd.".concat(t)):Array.isArray(t)?this.url.searchParams.append(e,"cd.{".concat(t.join(","),"}")):this.url.searchParams.append(e,"cd.".concat(JSON.stringify(t))),this}rangeGt(e,t){return this.url.searchParams.append(e,"sr.".concat(t)),this}rangeGte(e,t){return this.url.searchParams.append(e,"nxl.".concat(t)),this}rangeLt(e,t){return this.url.searchParams.append(e,"sl.".concat(t)),this}rangeLte(e,t){return this.url.searchParams.append(e,"nxr.".concat(t)),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,"adj.".concat(t)),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,"ov.".concat(t)):this.url.searchParams.append(e,"ov.{".concat(t.join(","),"}")),this}textSearch(e,t){let{config:r,type:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n="";return"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w"),this.url.searchParams.append(e,"".concat(n,"fts").concat(void 0===r?"":"(".concat(r,")"),".").concat(t)),this}match(e){return Object.entries(e).forEach(e=>{let[t,r]=e;this.url.searchParams.append(t,"eq.".concat(r))}),this}not(e,t,r){return this.url.searchParams.append(e,"not.".concat(t,".").concat(r)),this}or(e){let{foreignTable:t,referencedTable:r=t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.url.searchParams.append(r?"".concat(r,".or"):"or","(".concat(e,")")),this}filter(e,t,r){return this.url.searchParams.append(e,"".concat(t,".").concat(r)),this}}
2,N=class{cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=null!=t?t:{},n=!1,i=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!n?"":('"'===e&&(n=!n),e)).join(""),{url:a,headers:o}=this.cloneRequestState();return a.searchParams.set("select",i),s&&o.append("Prefer","count=".concat(s)),new U({method:r?"HEAD":"GET",url:a,headers:o,schema:this.schema,fetch:this.fetch})}insert(e){var t;let{count:r,defaultToNull:s=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{url:n,headers:i}=this.cloneRequestState();if(r&&i.append("Prefer","count=".concat(r)),s||i.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>'"'.concat(e,'"'));n.searchParams.set("columns",e.join(","))}}return new U({method:"POST",url:n,headers:i,schema:this.schema,body:e,fetch:null!=(t=this.fetch)?t:fetch})}upsert(e){var t;let{onConflict:r,ignoreDuplicates:s=!1,count:n,defaultToNull:i=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer","resolution=".concat(s?"ignore":"merge","-duplicates")),void 0!==r&&a.searchParams.set("on_conflict",r),n&&o.append("Prefer","count=".concat(n)),i||o.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>'"'.concat(e,'"'));a.searchParams.set("columns",e.join(","))}}return new U({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!=(t=this.fetch)?t:fetch})}update(e){var t;let{count:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{url:s,headers:n}=this.cloneRequestState();return r&&n.append("Prefer","count=".concat(r)),new U({method:"PATCH",url:s,headers:n,schema:this.schema,body:e,fetch:null!=(t=this.fetch)?t:fetch})}delete(){var e;let{count:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{url:r,headers:s}=this.cloneRequestState();return t&&s.append("Prefer","count=".concat(t)),new U({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!=(e=this.fetch)?e:fetch})}constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}},D=class e{from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new N(new URL("".concat(this.url,"/").concat(e)),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e){var t;let r,s,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{head:i=!1,get:a=!1,count:o}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},l=new URL("".concat(this.url,"/rpc/").concat(e)),c=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(c)),u=i&&Object.values(n).some(c);u?(r="POST",s=n):i||a?(r=i?"HEAD":"GET",Object.entries(n).filter(e=>{let[t,r]=e;return void 0!==r}).map(e=>{let[t,r]=e;return[t,Array.isArray(r)?"{".concat(r.join(","),"}"):"".concat(r)]}).forEach(e=>{let[t,r]=e;l.searchParams.append(t,r)})):(r="POST",s=n);let h=new Headers(this.headers);return u?h.set("Prefer",o?"count=".concat(o,",return=minimal"):"return=minimal"):o&&h.set("Prefer","count=".concat(o)),new U({method:r,url:l,headers:h,schema:this.schemaName,body:s,fetch:null!=(t=this.fetch)?t:fetch})}constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}};let B=class{static detectEnvironment(){var t;if("u">typeof WebSocket)return{type:"native",constructor:WebSocket};if("u">typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if(void 0!==e.g.WebSocket)return{type:"native",constructor:e.g.WebSocket};if("u">typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("u">typeof globalThis&&globalThis.EdgeRuntime||"u">typeof navigator&&(null==(t=navigator.userAgent)?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."};let r=globalThis.process;if(r){let e=r.versions;if(e&&e.node){let t=parseInt(e.node.replace(/^v/,"").split(".")[0]);return t>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:"Node.js ".concat(t," detected but native WebSocket not found."),workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:"Node.js ".concat(t," detected without native WebSocket support."),workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+="\n\nSuggested solution: ".concat(e.workaround)),Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}},L="realtime-js/".concat("2.93.2"),q="2.0.0";(c=v||(v={}))[c.connecting=0]="connecting",c[c.open=1]="open",c[c.closing=2]="closing",c[c.closed=3]="closed",(u=_||(_={})).closed="closed",u.errored="errored",u.joined="joined",u.joining="joining",u.leaving="leaving",(h=S||(S={})).close="phx_close",h.error="phx_error",h.join="phx_join",h.reply="phx_reply",h.leave="phx_leave",h.access_token="access_token",(k||(k={})).websocket="websocket",(d=E||(E={})).Connecting="connecting",d.Open="open",d.Closing="closing",d.Closed="closed";class M{encode(e,t){return e.event!==this.BROADCAST_EVENT||e.payload instanceof ArrayBuffer||"string"!=typeof e.payload.event?t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload])):t(this._binaryEncodeUserBroadcastPush(e))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null==(t=e.payload)?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:{},n=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,r){let s=e.topic,n=null!=(f=e.ref)?f:"",i=null!=(p=e.join_ref)?p:"",a=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=0===Object.keys(o).length?"":JSON.stringify(o);if(i.length>255)throw Error("joinRef length ".concat(i.length," exceeds maximum of 255"));if(n.length>255)throw Error("ref length ".concat(n.length," exceeds maximum of 255"));if(s.length>255)throw Error("topic length ".concat(s.length," exceeds maximum of 255"));if(a.length>255)throw Error("userEvent length ".concat(a.length," exceeds maximum of 255"));if(l.length>255)throw Error("metadata length ".concat(l.length," exceeds maximum of 255"));let c=this.USER_BROADCAST_PUSH_META_LENGTH+i.length+n.length+s.length+a.length+l.length,u=new ArrayBuffer(this.HEADER_LENGTH+c),h=new DataView(u),d=0;h.setUint8(d++,this.KINDS.userBroadcastPush),h.setUint8(d++,i.length),h.setUint8(d++,n.length),h.setUint8(d++,s.length),h.setUint8(d++,a.length),h.setUint8(d++,l.length),h.setUint8(d++,t),Array.from(i,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(n,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(s,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(a,e=>h.setUint8(d++,e.charCodeAt(0))),Array.from(l,e=>h.setUint8(d++,e.charCodeAt(0)));var f,p,g=new Uint8Array(u.byteLength+r.byteLength);return g.set(new Uint8Array(u),0),g.set(new Uint8Array(r),u.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,n,i,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:n,event:i,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s
2)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+4,l=r.decode(e.slice(o,o+s));o+=s;let c=r.decode(e.slice(o,o+n));o+=n;let u=r.decode(e.slice(o,o+i));o+=i;let h=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,f={type:this.BROADCAST_EVENT,event:c,payload:d};return i>0&&(f.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||(null==(t=null==e?void 0:e.constructor)?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(e=>{let[r]=e;return t.includes(r)})):{}}constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}}class W{reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}}(f=T||(T={})).abstime="abstime",f.bool="bool",f.date="date",f.daterange="daterange",f.float4="float4",f.float8="float8",f.int2="int2",f.int4="int4",f.int4range="int4range",f.int8="int8",f.int8range="int8range",f.json="json",f.jsonb="jsonb",f.money="money",f.numeric="numeric",f.oid="oid",f.reltime="reltime",f.text="text",f.time="time",f.timestamp="timestamp",f.timestamptz="timestamptz",f.timetz="timetz",f.tsrange="tsrange",f.tstzrange="tstzrange";let K=function(e,t){var r;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=null!=(r=s.skipTypes)?r:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=F(s,e,t,n),r),{}):{}},F=(e,t,r,s)=>{let n=t.find(t=>t.name===e),i=null==n?void 0:n.type,a=r[e];return i&&!s.includes(i)?z(i,a):J(a)},z=(e,t)=>{if("_"===e.charAt(0))return Y(t,e.slice(1,e.length));switch(e){case T.bool:return H(t);case T.float4:case T.float8:case T.int2:case T.int4:case T.int8:case T.numeric:case T.oid:return G(t);case T.json:case T.jsonb:return V(t);case T.timestamp:return $(t);case T.abstime:case T.date:case T.daterange:case T.int4range:case T.int8range:case T.money:case T.reltime:case T.text:case T.time:case T.timestamptz:case T.timetz:case T.tsrange:case T.tstzrange:default:return J(t)}},J=e=>e,H=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},G=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},V=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},Y=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,n=e.slice(1,r);try{s=JSON.parse("["+n+"]")}catch(e){s=n?n.split(","):[]}return s.map(e=>z(t,e))}return e},$=e=>"string"==typeof e?e.replace(" ","T"):e,X=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class Z{resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null==(r=this.receivedResp)?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive(e){let{status:t,response:r}=e;
2this.recHooks.filter(e=>e.status===t).forEach(e=>e.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}}(p=A||(A={})).SYNC="sync",p.JOIN="join",p.LEAVE="leave";class Q{static syncState(e,t,r,s){let n=this.cloneDeep(e),i=this.transformState(t),a={},o={};return this.map(n,(e,t)=>{i[e]||(o[e]=t)}),this.map(i,(e,t)=>{let r=n[e];if(r){let s=t.map(e=>e.presence_ref),n=r.map(e=>e.presence_ref),i=t.filter(e=>0>n.indexOf(e.presence_ref)),l=r.filter(e=>0>s.indexOf(e.presence_ref));i.length>0&&(a[e]=i),l.length>0&&(o[e]=l)}else a[e]=t}),this.syncDiff(n,{joins:a,leaves:o},r,s)}static syncDiff(e,t,r,s){let{joins:n,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(t,s)=>{var n;let i=null!=(n=e[t])?n:[];if(e[t]=this.cloneDeep(s),i.length>0){let r=e[t].map(e=>e.presence_ref),s=i.filter(e=>0>r.indexOf(e.presence_ref));e[t].unshift(...s)}r(t,i,s)}),this.map(i,(t,r)=>{let n=e[t];if(!n)return;let i=r.map(e=>e.presence_ref);n=n.filter(e=>0>i.indexOf(e.presence_ref)),e[t]=n,s(t,n,r),0===n.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return Object.getOwnPropertyNames(e=this.cloneDeep(e)).reduce((t,r)=>{let s=e[r];return"metas"in s?t[r]=s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Q.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=Q.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=Q.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}}(g=O||(O={})).ALL="*",g.INSERT="INSERT",g.UPDATE="UPDATE",g.DELETE="DELETE",(y=R||(R={})).BROADCAST="broadcast",y.PRESENCE="presence",y.POSTGRES_CHANGES="postgres_changes",y.SYSTEM="system",(m=I||(I={})).SUBSCRIBED="SUBSCRIBED",m.TIMED_OUT="TIMED_OUT",m.CLOSED="CLOSED",m.CHANNEL_ERROR="CHANNEL_ERROR";class ee{subscribe(e){var t,r,s;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.timeout;if(this.socket.isConnected()||this.socket.connect(),this.state==_.closed){let{config:{broadcast:i,presence:a,private:o}}=this.params,l=null!=(r=null==(t=this.bindings.postgres_changes)?void 0:t.map(e=>e.filter))?r:[],c=!!this.bindings[R.PRESENCE]&&this.bindings[R.PRESENCE].length>0||(null==(s=this.params.config.presence)?void 0:s.enabled)===!0,u={},h={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(I.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(I.CLOSED)),this.updateJoinPayload(Object.assign({config:h},u)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async t=>{var r;let{postgres_changes:s}=t;if(this.socket._isManualToken()||this.socket.setAuth(),void 0===s){null==e||e(I.SUBSCRIBED);return}{let t=this.bindings.postgres_changes,n=null!=(r=null==t?void 0:t.length)?r:0,i=[];for(let r=0;r<n;r++){let n=t[r],{filter:{event:a,schema:o,table:l,filter:c}}=n,u=s&&s[r];if(u&&u.event===a&&ee.isFilterValueEqual(u.schema,o)&&ee.isFilterValueEqual(u.table,l)&&ee.isFilterValueEqual(u.filter,c))i.push(Object.assign(Object.assign({},n),{id:u.id}));else{this.unsubscribe(),this.state=_.errored,null==e||e(I.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,e&&e(I.SUBSCRIBED);return}}).receive("error",t=>{this.state=_.errored,null==e||e(I.CHANNEL_ERROR,Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(I.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===_.joined&&e===R.PRESENCE&&(this.socket.log("channel","resubscribe to ".concat(this.topic," due to change in presence callbacks on joined channel")),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t){var r;let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(null==t)return Promise.reject("Payload is required for httpSend()");let n={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(n.Authorization="Bearer ".concat(this.socket.accessTokenValue));let i={method:"POST",headers:n,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!=(r=s.timeout)?r:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;
2try{let e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(Error(o))}async send(e){var t,r;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._canPush()||"broadcast"!==e.type)return new Promise(t=>{var r,n,i;let a=this._push(e.type,e,s.timeout||this.timeout);"broadcast"!==e.type||(null==(i=null==(n=null==(r=this.params)?void 0:r.config)?void 0:n.broadcast)?void 0:i.ack)||t("ok"),a.receive("ok",()=>t("ok")),a.receive("error",()=>t("error")),a.receive("timeout",()=>t("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:n,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization="Bearer ".concat(this.socket.accessTokenValue));let o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:i,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!=(t=s.timeout)?t:this.timeout);return await (null==(r=e.body)?void 0:r.cancel()),e.ok?"ok":"error"}catch(e){if("AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this.state=_.leaving;let t=()=>{this.socket.log("channel","leave ".concat(this.topic)),this._trigger(S.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{(r=new Z(this,S.leave,{},e)).receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=_.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),i}_push(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.timeout;if(!this.joinedOnce)throw"tried to push '".concat(e,"' to '").concat(this.topic,"' before joining. Use channel.subscribe() before pushing events");let s=new Z(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){let e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel","discarded push due to buffer overflow: ".concat(e.event),e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;let i=e.toLocaleLowerCase(),{close:a,error:o,leave:l,join:c}=S;if(r&&[a,o,l,c].indexOf(i)>=0&&r!==this._joinRef())return;let u=this._onMessage(i,t,r);if(t&&!u)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null==(s=this.bindings.postgres_changes)||s.filter(e=>{var t,r,s;return(null==(t=e.filter)?void 0:t.event)==="*"||(null==(s=null==(r=e.filter)?void 0:r.event)?void 0:s.toLocaleLowerCase())===i}).map(e=>e.callback(u,r)):null==(n=this.bindings[i])||n.filter(e=>{var r,s,n,a,o,l;if(!["broadcast","presence","postgres_changes"].includes(i))return e.type.toLocaleLowerCase()===i;if("id"in e){let i=e.id,a=null==(r=e.filter)?void 0:r.event;return i&&(null==(s=t.ids)?void 0:s.includes(i))&&("*"===a||(null==a?void 0:a.toLocaleLowerCase())===(null==(n=t.data)?void 0:n.type.toLocaleLowerCase()))}{let r=null==(o=null==(a=null==e?void 0:e.filter)?void 0:a.event)?void 0:o.toLocaleLowerCase();return"*"===r||r===(null==(l=null==t?void 0:t.event)?void 0:l.toLocaleLowerCase())}}).map(e=>{if("object"==typeof u&&"ids"in u){let e=u.data,{schema:t,table:r,commit_timestamp:s,type:n,errors:i}=e;u=Object.assign(Object.assign({},{schema:t,table:r,commit_timestamp:s,eventType:n,new:{},old:{},errors:i}),this._getPayloadRecords(e))}e.callback(u,r)})}_isClosed(){return this.state===_.closed}_isJoined(){return this.state===_.joined}_isJoining(){return this.state===_.joining}_isLeaving(){return this.state===_.leaving}_replyEventName(e){return"chan_reply_".concat(e)}_on(e,t,r){let s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var s;return!((null==(s=e.type)?void 0:s.toLocaleLowerCase())===r&&ee.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(S.close,{},e)}_onError(e){this._on(S.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=_.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=K(e.columns,e.record)),("UPDATE"===e.type||"DELET
2E"===e.type)&&(t.old=K(e.columns,e.old_record)),t}constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=_.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Z(this,S.join,this.params,this.timeout),this.rejoinTimer=new W(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=_.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel","close ".concat(this.topic," ").concat(this._joinRef())),this.state=_.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel","error ".concat(this.topic),e),this.state=_.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel","timeout ".concat(this.topic),this.joinPush.timeout),this.state=_.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel","error ".concat(this.topic),e),this.state=_.errored,this.rejoinTimer.scheduleTimeout())}),this._on(S.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Q(this),this.broadcastEndpointURL=X(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null==(n=null==(s=this.params.config)?void 0:s.broadcast)?void 0:n.replay))throw"tried to use replay on public channel '".concat(this.topic,"'. It must be a private channel.")}}let et=()=>{},er=[1e3,2e3,5e3,1e4];class es{connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=B.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");let e=t.message;if(e.includes("Node.js"))throw Error("".concat(e,"\n\n")+'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n  npm install ws\n\n  import ws from "ws"\n  const client = new RealtimeClient(url, {\n    ...options,\n    transport: ws\n  })');throw Error("WebSocket not available: ".concat(e))}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case v.connecting:return E.Connecting;case v.open:return E.Open;case v.closing:return E.Closing;default:return E.Closed}}isConnected(){return this.connectionState()===E.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{config:{}},r="realtime:".concat(e),s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new ee("realtime:".concat(e),t,this);return this.channels.push(r),r}}push(e){let{topic:t,event:r,payload:s,ref:n}=e,i=()=>{this.encode(e,e=>{var t;null==(t=this.conn)||t.send(e)})};this.log("push","".concat(t," ").concat(r," (").concat(n,")"),s),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this._wasManualDisconnect=!1,null==(e=this.conn)||e.close(1e3,"heartbeat timeout"),setTimeout(()=>{var e;this.isConnected()||null==(e=this.reconnectTimer)||e.scheduleTimeout()},100);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>
20&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",'leaving duplicate topic "'.concat(e,'"')),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){let t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:t,event:r,payload:s,ref:n}=e,i=s.status||"";this.log("receive","".concat(i," ").concat(t," ").concat(r," ").concat(n?"(".concat(n,")"):"").trim(),s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,n)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null==(t=this.reconnectTimer)||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===v.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===v.open||this.conn.readyState===v.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport","connected to ".concat(this.endpointURL())),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker","starting worker for from ".concat(this.workerUrl)):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null==(t=this.reconnectTimer)||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport","".concat(e)),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(e){this.log("error","error in heartbeat callback",e)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(S.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return"".concat(e).concat(r).concat(s)}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob(['\n  addEventListener("message", (e) => {\n    if (e.data.event === "start") {\n      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n    }\n  });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,r=!1;if(t)e=t,r=!0;else if(this.accessToken)try{e=await this.accessToken()}catch(t){this.log("error","Error fetching access token from callback",t),e=this.accessTokenValue}else e=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=e&&(this.accessTokenValue=e,this.channels.forEac
2h(t=>{let r={access_token:e,version:L};e&&t.updateJoinPayload(r),t.joinedOnce&&t._isJoined()&&t._push(S.access_token,{access_token:e})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"general";this._isManualToken()||this.setAuth().catch(t=>{this.log("error","Error setting auth in ".concat(e),t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error","error in ".concat(e," callback"),t)}})}catch(t){this.log("error","error triggering ".concat(e," callbacks"),t)}}_setupReconnectionTimer(){this.reconnectTimer=new W(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},10)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,n,i,a,o,l,c,u,h,d;switch(this.transport=null!=(t=null==e?void 0:e.transport)?t:null,this.timeout=null!=(r=null==e?void 0:e.timeout)?r:1e4,this.heartbeatIntervalMs=null!=(s=null==e?void 0:e.heartbeatIntervalMs)?s:25e3,this.worker=null!=(n=null==e?void 0:e.worker)&&n,this.accessToken=null!=(i=null==e?void 0:e.accessToken)?i:null,this.heartbeatCallback=null!=(a=null==e?void 0:e.heartbeatCallback)?a:et,this.vsn=null!=(o=null==e?void 0:e.vsn)?o:q,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!=(l=null==e?void 0:e.reconnectAfterMs)?l:e=>er[e-1]||1e4,this.vsn){case"1.0.0":this.encode=null!=(c=null==e?void 0:e.encode)?c:(e,t)=>t(JSON.stringify(e)),this.decode=null!=(u=null==e?void 0:e.decode)?u:(e,t)=>t(JSON.parse(e));break;case q:this.encode=null!=(h=null==e?void 0:e.encode)?h:this.serializer.encode.bind(this.serializer),this.decode=null!=(d=null==e?void 0:e.decode)?d:this.serializer.decode.bind(this.serializer);break;default:throw Error("Unsupported serializer version: ".concat(this.vsn))}if(this.worker){if("u">typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=1e4,this.transport=null,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=et,this.ref=0,this.reconnectTimer=null,this.vsn=q,this.logger=et,this.conn=null,this.sendBuffer=[],this.serializer=new M,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)},!(null==(r=null==t?void 0:t.params)?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint="".concat(e,"/").concat(k.websocket),this.httpEndpoint=X(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}}var en=e.i(467034),ei=class extends Error{isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}constructor(e,t){var r;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&(null==(r=t.icebergType)?void 0:r.includes("CommitState"))===!0}};async function ea(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:"Bearer ".concat(e.token)}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}function eo(e){return e.join("\x1f")}var el=class{async listNamespaces(e){let t=e?{parent:eo(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces"),query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:null==t?void 0:t.properties};return(await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces"),body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:"".concat(this.prefix,"/namespaces/").concat(eo(e.namespace))})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eo(e.namespace))})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:"".concat(this.prefix,"/namespaces/").concat(eo(e.namespace))}),!0}catch(e){if(e instanceof ei&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof ei&&409===e.status)return;throw e}}constructor(e,t=""){this.client=e,this.prefix=t}};function ec(e){return e.join("\x1f")}var eu=class{async listTables(e){return(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(ec(e.namespace),"/tables")})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces/").concat(ec(e.namespace),"/tables"),body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:"".concat(this.prefix,"/namespaces/").concat(ec(e.namespace),"/tables/").concat(e.name),body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){var r;await this.client.request({method:"DELETE",path:"".concat(this.prefix,"/namespaces/").concat(ec(e.namespace),"/tables/").concat(e.name),query:{purgeRequested:String(null!=(r=null==t?void 0:t.purge)&&r)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(ec(e.namespace),"/tables/").concat(e.name),headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:"".concat(this.prefix,"/namespaces/").concat(ec(e.namespace),"/tables/").concat(e.name),headers:t}),!0}catch(e){if(e instanceof ei&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof ei&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}},eh=class{async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}
2async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}constructor(e){var t;let r="v1";e.catalogName&&(r+="/".concat(e.catalogName));const s=e.baseUrl.endsWith("/")?e.baseUrl:"".concat(e.baseUrl,"/");this.client=function(e){var t;let r=null!=(t=e.fetchImpl)?t:globalThis.fetch;return{async request(t){let{method:s,path:n,query:i,body:a,headers:o}=t,l=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,n,i),c=await ea(e.auth),u=await r(l,{method:s,headers:{...a?{"Content-Type":"application/json"}:{},...c,...o},body:a?JSON.stringify(a):void 0}),h=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),f=d&&h?JSON.parse(h):h;if(!u.ok){var p;let e=d?f:void 0,t=null==e?void 0:e.error;throw new ei(null!=(p=null==t?void 0:t.message)?p:"Request failed with status ".concat(u.status),{status:u.status,icebergType:null==t?void 0:t.type,icebergCode:null==t?void 0:t.code,details:e})}return{status:u.status,headers:u.headers,data:f}}}}({baseUrl:s,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=null==(t=e.accessDelegation)?void 0:t.join(","),this.namespaceOps=new el(this.client,r),this.tableOps=new eu(this.client,r,this.accessDelegation)}},ed=class extends Error{constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function ef(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var ep=class extends ed{toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}constructor(e,t,r,s="storage"){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}},eg=class extends ed{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};let ey=e=>{if(Array.isArray(e))return e.map(e=>ey(e));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach(e=>{let[r,s]=e;t[r.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""))]=ey(s)}),t};function em(e){return(em="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ew(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function eb(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ew(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=em(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=em(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==em(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ew(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}let ev=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null==(t=e.error)?void 0:t.message)||JSON.stringify(e)},e_=async(e,t,r,s)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){let r=e.status||500;"function"==typeof e.json?e.json().then(e=>{let n=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new ep(ev(e),r,n,s))}).catch(()=>{t(new ep(e.statusText||"HTTP ".concat(r," error"),r,r+"",s))}):t(new ep(e.statusText||"HTTP ".concat(r," error"),r,r+"",s))}else t(new eg(ev(e),e,s))};async function eS(e,t,r,s,n,i,a){return new Promise((o,l)=>{let c;e(r,(c={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t||"HEAD"===t||!i||((e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)})(i)?(c.headers=eb({"Content-Type":"application/json"},null==s?void 0:s.headers),c.body=JSON.stringify(i)):c.body=i,(null==s?void 0:s.duplex)&&(c.duplex=s.duplex)),eb(eb({},c),n))).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;if("vectors"===a){let t=e.headers.get("content-type");if(!t||!t.includes("application/json"))return{}}return e.json()}).then(e=>o(e)).catch(e=>e_(e,l,s,a))})}let{get:ek,post:eE,put:eT,head:eA,remove:eO}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"storage";return{get:async(t,r,s,n)=>eS(t,"GET",r,s,n,void 0,e),post:async(t,r,s,n,i)=>eS(t,"POST",r,n,i,s,e),put:async(t,r,s,n,i)=>eS(t,"PUT",r,n,i,s,e),head:async(t,r,s,n)=>eS(t,"HEAD",r,eb(eb({},s),{},{noResolveJson:!0}),n,void 0,e),remove:async(t,r,s,n,i)=>eS(t,"DELETE",r,n,i,s,e)}}("storage");var eR=class{throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ef(e))return{data:null,error:e};throw e}}constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=(e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)})(r),this.namespace=s}},eI=class{then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ef(e))return{data:null,error:e};throw e}}constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}};t=Symbol.toStringTag;var eC=class{asStream(){return new eI(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await (await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ef(e))return{data:null,error:e};throw e}}constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r,this[t]="BlobDownloadBuilder",this.promise=null}};let eP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ej={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var ex=class extends eR{async uploadOrUpdate(e,t,r,s){var n=this;return n.handleOperation(async()=>{let i,a=eb(eb({},ej),s),o=eb(eb({},n.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;"u">typeof Blob&&r instanceof Blob?((i=new FormData).append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):"u">typeof FormData&&r instanceof FormData?((i=r).has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]="max-age=".concat(a.cacheControl),o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("u">typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!a.duplex&&(a.duplex="half")),(null==s?void 0:s.headers)&&(o=eb(eb({},o),s.headers));let c=n._removeEmptyFolders(t),u=n._getFinalPath(c),h=await ("PUT"==e?eT:eE)(n.fetch,"".concat(n.url,"/object/").concat(u),i,eb({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{path:c,id:h.Id,fullPath:h.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var n=this;let i=n._removeEmptyFolders(e),a=n._getFinalPath(i),o=new URL(n.url+"/object/upload/sign/".concat(a));return o.searchParams.set("token",t),n.handleOperation(async()=>{let e,t=eb({upsert:ej.upsert},s),a=eb(eb({},n.headers),{"x-upsert":String(t.upsert)});return"u">typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),e.append("",r)):"u">typeof FormData&&r instanceof FormData?(e=r).append("cacheControl",t.cacheControl):(e=r,a["cache-control"]="max-age=".concat(t.cacheControl),a["content-type"]=t.contentType),{path:i,fullPath:(await eT(n.fetch,o.toString(),e,{headers:a})).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),n=eb({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");let i=await eE(r.fetch,"".concat(r.url,"/object/upload/sign/").concat(s),{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new ed("No token returned by API");return{signedUrl:a.toString(),path:e,token:o}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation(async()=>await eE(s.fetch,"".concat(s.url,"/object/move"),{bucketId:s.bucketId,sourceKey:e,destinationKey:t,de
2stinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await eE(s.fetch,"".concat(s.url,"/object/copy"),{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(e),i=await eE(s.fetch,"".concat(s.url,"/object/sign/").concat(n),eb({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:s.headers}),a=(null==r?void 0:r.download)?"&download=".concat(!0===r.download?"":r.download):"";return{signedUrl:encodeURI("".concat(s.url).concat(i.signedURL).concat(a))}})}async createSignedUrls(e,t,r){var s=this;return s.handleOperation(async()=>{let n=await eE(s.fetch,"".concat(s.url,"/object/sign/").concat(s.bucketId),{expiresIn:t,paths:e},{headers:s.headers}),i=(null==r?void 0:r.download)?"&download=".concat(!0===r.download?"":r.download):"";return n.map(e=>eb(eb({},e),{},{signedUrl:e.signedURL?encodeURI("".concat(s.url).concat(e.signedURL).concat(i)):null}))})}download(e,t){let r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=s?"?".concat(s):"",i=this._getFinalPath(e);return new eC(()=>ek(this.fetch,"".concat(this.url,"/").concat(r,"/").concat(i).concat(n),{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>ey(await ek(t.fetch,"".concat(t.url,"/object/info/").concat(r),{headers:t.headers})))}async exists(e){let t=this._getFinalPath(e);try{return await eA(this.fetch,"".concat(this.url,"/object/").concat(t),{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(ef(e)&&e instanceof eg){let t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],n=(null==t?void 0:t.download)?"download=".concat(!0===t.download?"":t.download):"";""!==n&&s.push(n);let i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&s.push(a);let o=s.join("&");return""!==o&&(o="?".concat(o)),{data:{publicUrl:encodeURI("".concat(this.url,"/").concat(i,"/public/").concat(r).concat(o))}}}async remove(e){var t=this;return t.handleOperation(async()=>await eO(t.fetch,"".concat(t.url,"/object/").concat(t.bucketId),{prefixes:e},{headers:t.headers}))}async list(e,t,r){var s=this;return s.handleOperation(async()=>{let n=eb(eb(eb({},eP),t),{},{prefix:e||""});return await eE(s.fetch,"".concat(s.url,"/object/list/").concat(s.bucketId),n,{headers:s.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let s=eb({},e);return await eE(r.fetch,"".concat(r.url,"/object/list-v2/").concat(r.bucketId),s,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return void 0!==en.Buffer?en.Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return"".concat(this.bucketId,"/").concat(e.replace(/^\/+/,""))}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push("width=".concat(e.width)),e.height&&t.push("height=".concat(e.height)),e.resize&&t.push("resize=".concat(e.resize)),e.format&&t.push("format=".concat(e.format)),e.quality&&t.push("quality=".concat(e.quality)),t.join("&")}constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}};let eU={"X-Client-Info":"storage-js/".concat("2.93.2")};var eN=class extends eR{async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await ek(t.fetch,"".concat(t.url,"/bucket").concat(r),{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ek(t.fetch,"".concat(t.url,"/bucket/").concat(e),{headers:t.headers}))}async createBucket(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{public:!1};var r=this;return r.handleOperation(async()=>await eE(r.fetch,"".concat(r.url,"/bucket"),{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await eT(r.fetch,"".concat(r.url,"/bucket/").concat(e),{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/bucket/").concat(e,"/empty"),{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eO(t.fetch,"".concat(t.url,"/bucket/").concat(e),{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}constructor(e,t={},r,s){const n=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),super(n.href.replace(/\/$/,""),eb(eb({},eU),t),r,"storage")}},eD=class extends eR{async createBucket(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/bucket"),{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;(null==e?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(null==e?void 0:e.offset)!==void 0&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);let s=r.toString(),n=s?"".concat(t.url,"/bucket?").concat(s):"".concat(t.url,"/bucket");return await ek(t.fetch,n,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eO(t.fetch,"".concat(t.url,"/bucket/").concat(e),{},{headers:t.headers}))}from(e){var t=this;if(!(!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)))throw new ed("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new eh({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"!=typeof r?r:async function(){for(var t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];try{return{data:await r.apply(e,n),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}constructor(e,t={},r){super(e.replace(/\/$/,""),eb(eb({},eU),t),r,"storage")}},eB=class extends eR{async createIndex(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/CreateIndex"),e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await eE(r.fetch,"".concat(r.url,"/GetIndex"),{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/ListIndexes"),e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await eE(r.fetch,"".concat(r.url,"/DeleteIndex"),{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eb(eb({},eU),{},{"Content-Type":"application/json"},t),r,"vectors")}},eL=class extends eR{async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/PutVectors"),e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/GetVectors"),e,{headers:t.headers}))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");
2if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error("segmentIndex must be between 0 and ".concat(e.segmentCount-1))}return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/ListVectors"),e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/QueryVectors"),e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/DeleteVectors"),e,{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eb(eb({},eU),{},{"Content-Type":"application/json"},t),r,"vectors")}},eq=class extends eR{async createBucket(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/CreateVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/GetVectorBucket"),{vectorBucketName:e},{headers:t.headers}))}async listBuckets(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/ListVectorBuckets"),e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eE(t.fetch,"".concat(t.url,"/DeleteVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eb(eb({},eU),{},{"Content-Type":"application/json"},t),r,"vectors")}},eM=class extends eq{from(e){return new eW(this.url,this.headers,e,this.fetch)}async createBucket(e){return super.createBucket.call(this,e)}async getBucket(e){return super.getBucket.call(this,e)}async listBuckets(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listBuckets.call(this,e)}async deleteBucket(e){return super.deleteBucket.call(this,e)}constructor(e,t={}){super(e,t.headers||{},t.fetch)}},eW=class extends eB{async createIndex(e){return super.createIndex.call(this,eb(eb({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listIndexes.call(this,eb(eb({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return super.getIndex.call(this,this.vectorBucketName,e)}async deleteIndex(e){return super.deleteIndex.call(this,this.vectorBucketName,e)}index(e){return new eK(this.url,this.headers,this.vectorBucketName,e,this.fetch)}constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}},eK=class extends eL{async putVectors(e){return super.putVectors.call(this,eb(eb({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,eb(eb({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listVectors.call(this,eb(eb({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,eb(eb({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,eb(eb({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}},eF=class extends eN{from(e){return new ex(this.url,this.headers,e,this.fetch)}get vectors(){return new eM(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new eD(this.url+"/iceberg",this.headers,this.fetch)}constructor(e,t={},r,s){super(e,t,r,s)}};let ez="2.93.2",eJ="X-Supabase-Api-Version",eH={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},eG=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class eV extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.co
2de=r}}function eY(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class e$ extends eV{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class eX extends eV{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class eZ extends eV{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class eQ extends eZ{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function e0(e){return eY(e)&&"AuthSessionMissingError"===e.name}class e1 extends eZ{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class e2 extends eZ{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class e5 extends eZ{toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}}class e8 extends eZ{toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}}class e3 extends eZ{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")}}class e6 extends eZ{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function e4(e){return eY(e)&&"AuthRetryableFetchError"===e.name}class e9 extends eZ{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class e7 extends eZ{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tt=" 	\n\r=".split(""),tr=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<tt.length;t+=1)e[tt[t].charCodeAt(0)]=-2;for(let t=0;t<te.length;t+=1)e[te[t].charCodeAt(0)]=t;return e})();function ts(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(te[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(te[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function tn(e,t,r){let s=tr[e];if(s>-1)for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(-2===s)return;else throw Error('Invalid Base64-URL character "'.concat(String.fromCharCode(e),'"'))}function ti(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)tn(e.charCodeAt(t),n,i);return t.join("")}function ta(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)tn(e.charCodeAt(t),r,s);return new Uint8Array(t)}function to(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>ts(e,r,s)),ts(null,r,s),t.join("")}let tl=()=>"u">typeof window&&"u">typeof document,tc={tested:!1,writable:!1},tu=()=>{if(!tl())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(tc.tested)return tc.writable;let e="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),tc.tested=!0,tc.writable=!0}catch(e){tc.tested=!0,tc.writable=!1}return tc.writable},th=e=>e?function(){for(var t=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];return e(...r)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)},td=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},tf=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},tp=async(e,t)=>{await e.removeItem(t)};class tg{constructor(){this.promise=new tg.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function ty(e){let t=e.split(".");if(3!==t.length)throw new e7("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!eG.test(t[e]))throw new e7("JWT not in base64url format");return{header:JSON.parse(ti(t[0])),payload:JSON.parse(ti(t[1])),signature:ta(t[2]),raw:{header:t[0],payload:t[1]}}}async function tm(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function tw(e){return("0"+e.toString(16)).substr(-2)}async function tb(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function tv(e){return"u">typeof crypto&&void 0!==crypto.subtle&&"u">typeof TextEncoder?btoa(await tb(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code 
2challenge method will default to use plain instead of sha256."),e)}async function t_(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=function(){let e=new Uint32Array(56);if("u"<typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,tw).join("")}(),n=s;r&&(n+="/PASSWORD_RECOVERY"),await td(e,"".concat(t,"-code-verifier"),n);let i=await tv(s),a=s===i?"plain":"s256";return[i,a]}tg.promiseConstructor=Promise;let tS=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,tk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function tE(e){if(!tk.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function tT(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "'.concat(t,'" property of the session object is not supported. Please use getUser() instead.'))},set:(e,t)=>{throw Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "'.concat(t,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))},deleteProperty:(e,t)=>{throw Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "'.concat(t,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))}})}function tA(e){return JSON.parse(JSON.stringify(e))}let tO=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tR=[502,503,504];async function tI(e){var t;let r,s;if(!("object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json))throw new e6(tO(e),0);if(tR.includes(e.status))throw new e6(tO(e),e.status);try{r=await e.json()}catch(e){throw new eX(tO(e),e)}let n=function(e){let t=e.headers.get(eJ);if(!t||!t.match(tS))return null;try{return new Date("".concat(t,"T00:00:00.0Z"))}catch(e){return null}}(e);if(n&&n.getTime()>=eH["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?s=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(s=r.error_code),s){if("weak_password"===s)throw new e9(tO(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[]);else if("session_not_found"===s)throw new eQ}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new e9(tO(r),e.status,r.weak_password.reasons);throw new e$(tO(r),e.status||500,s)}async function tC(e,t,r,s){var n;let i=Object.assign({},null==s?void 0:s.headers);i[eJ]||(i[eJ]=eH["2024-01-01"].name),(null==s?void 0:s.jwt)&&(i.Authorization="Bearer ".concat(s.jwt));let a=null!=(n=null==s?void 0:s.query)?n:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await tP(e,t,r+o,{headers:i,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function tP(e,t,r,s,n,i){let a,o,l=(o={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t?o:(o.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==s?void 0:s.headers),o.body=JSON.stringify(i),Object.assign(Object.assign({},o),n)));try{a=await e(r,Object.assign({},l))}catch(e){throw console.error(e),new e6(tO(e),0)}if(a.ok||await tI(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await tI(e)}}function tj(e){var t,r,s;let n=null;(s=e).access_token&&s.refresh_token&&s.expires_in&&(n=Object.assign({},e),e.expires_at||(n.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:n,user:null!=(t=e.user)?t:e},error:null}}function tx(e){let t=tj(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>
2e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function tU(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function tN(e){return{data:e,error:null}}function tD(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},user:Object.assign({},o(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function tB(e){return e}let tL=["global","local","others"];class tq{async signOut(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tL[0];if(0>tL.indexOf(t))throw Error("@supabase/auth-js: Parameter scope must be one of ".concat(tL.join(", ")));try{return await tC(this.fetch,"POST","".concat(this.url,"/logout?scope=").concat(t),{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(eY(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{return await tC(this.fetch,"POST","".concat(this.url,"/invite"),{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tU})}catch(e){if(eY(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=o(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await tC(this.fetch,"POST","".concat(this.url,"/admin/generate_link"),{body:s,headers:this.headers,xform:tD,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(eY(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await tC(this.fetch,"POST","".concat(this.url,"/admin/users"),{body:e,headers:this.headers,xform:tU})}catch(e){if(eY(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,n,i,a,o;try{let l={nextPage:null,lastPage:0,total:0},c=await tC(this.fetch,"GET","".concat(this.url,"/admin/users"),{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(n=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?n:""},xform:tB});if(c.error)throw c.error;let u=await c.json(),h=null!=(i=c.headers.get("x-total-count"))?i:0,d=null!=(o=null==(a=c.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l["".concat(r,"Page")]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(eY(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){tE(e);try{return await tC(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,xform:tU})}catch(e){if(eY(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){tE(e);try{return await tC(this.fetch,"PUT","".concat(this.url,"/admin/users/").concat(e),{body:t,headers:this.headers,xform:tU})}catch(e){if(eY(e))return{data:{user:null},error:e};throw e}}async deleteUser(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];tE(e);try{return await tC(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,body:{should_soft_delete:t},xform:tU})}catch(e){if(eY(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){tE(e.userId);try{let{data:t,error:r}=await tC(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e.userId,"/factors"),{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(eY(e))return{data:null,error:e};throw e}}async _deleteFactor(e){tE(e.userId),tE(e.id);try{return{data:await tC(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e.userId,"/factors/").concat(e.id),{headers:this.headers}),error:null}}catch(e){if(eY(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,n,i,a,o;try{let l={nextPage:null,lastPage:0,total:0},c=await tC(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients"),{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(n=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?n:""},xform:tB});if(c.error)throw c.error;let u=await c.json(),h=null!=(i=c.headers.get("x-total-count"))?i:0,d=null!=(o=null==(a=c.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>
20&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l["".concat(r,"Page")]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(eY(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await tC(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients"),{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(eY(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await tC(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(eY(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await tC(this.fetch,"PUT","".concat(this.url,"/admin/oauth/clients/").concat(e),{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(eY(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await tC(this.fetch,"DELETE","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(eY(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await tC(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients/").concat(e,"/regenerate_secret"),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(eY(e))return{data:null,error:e};throw e}}constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=th(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)}}}function tM(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let tW={debug:!!(globalThis&&tu()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class tK extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class tF extends tK{}async function tz(e,t,r){tW.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort(),tW.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async s=>{if(s){tW.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{tW.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}if(0===t)throw tW.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new tF('Acquiring an exclusive Navigator LockManager lock "'.concat(e,'" immediately failed'));if(tW.debug)try{let e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null,"  "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}))}function tJ(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error('@supabase/auth-js: Address "'.concat(e,'" is invalid.'));return e.toLowerCase()}
2class tH extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!=(n=null!=s?s:r instanceof Error?r.name:void 0)?n:"Unknown Error",this.code=t}}class tG extends tH{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}let tV=new class{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function tY(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function t$(){var e,t;return!!(tl()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null==(e=null==navigator?void 0:navigator.credentials)?void 0:e.create)&&"function"==typeof(null==(t=null==navigator?void 0:navigator.credentials)?void 0:t.get))}async function tX(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new tG("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new tG("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function(e){var t,r,s;let{error:n,options:i}=e,{publicKey:a}=i;if(!a)throw Error("options was missing required publicKey property");if("AbortError"===n.name){if(i.signal instanceof AbortSignal)return new tH({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if("ConstraintError"===n.name){if((null==(t=a.authenticatorSelection)?void 0:t.requireResidentKey)===!0)return new tH({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});else if("conditional"===i.mediation&&(null==(r=a.authenticatorSelection)?void 0:r.userVerification)==="required")return new tH({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});else if((null==(s=a.authenticatorSelection)?void 0:s.userVerification)==="required")return new tH({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else if("InvalidStateError"===n.name)return new tH({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});else if("NotAllowedError"===n.name)return new tH({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});else if("NotSupportedError"===n.name)return new tH(0===a.pubKeyCredParams.filter(e=>"public-key"===e.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});else if("SecurityError"===n.name){let e=window.location.hostname;if(!tY(e))return new tH({message:"".concat(window.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:n});if(a.rp.id!==e)return new tH({message:'The RP ID "'.concat(a.rp.id,'" is invalid for this domain'),code:"ERROR_INVALID_RP_ID",cause:n})}else if("TypeError"===n.name){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new tH({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if("UnknownError"===n.name)return new tH({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n});return new tH({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}
2({error:t,options:e})}}}async function tZ(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new tG("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new tG("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function(e){let{error:t,options:r}=e,{publicKey:s}=r;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(r.signal instanceof AbortSignal)return new tH({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("NotAllowedError"===t.name)return new tH({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});else if("SecurityError"===t.name){let e=window.location.hostname;if(!tY(e))return new tH({message:"".concat(window.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:t});if(s.rpId!==e)return new tH({message:'The RP ID "'.concat(s.rpId,'" is invalid for this domain'),code:"ERROR_INVALID_RP_ID",cause:t})}else if("UnknownError"===t.name)return new tH({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 tH({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}({error:t,options:e})}}}let tQ={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},t0={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function t1(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];let s=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),i={};for(let e of t)if(e)for(let t in e){let r=e[t];if(void 0!==r)if(Array.isArray(r))i[t]=r;else if(n(r))i[t]=r;else if(s(r)){let e=i[t];s(e)?i[t]=t1(e,r):i[t]=t1(r)}else i[t]=r}return i}class t2{async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge(e,t){let{factorId:r,webauthn:s,friendlyName:n,signal:i}=e;try{var a,o,l,c;let{data:e,error:u}=await this.client.mfa.challenge({factorId:r,webauthn:s});if(!e)return{data:null,error:u};let h=null!=i?i:tV.createNewAbortSignal();if("create"===e.webauthn.type){let{user:t}=e.webauthn.credential_options.publicKey;t.name||(t.name="".concat(t.id,":").concat(n)),t.displayName||(t.displayName=t.name)}switch(e.webauthn.type){case"create":{let s=(a=e.webauthn.credential_options.publicKey,o=null==t?void 0:t.create,t1(tQ,a,o||{})),{data:n,error:i}=await tX({publicKey:s,signal:h});if(n)return{data:{factorId:r,challengeId:e.id,webauthn:{type:e.webauthn.type,credential_response:n}},error:null};return{data:null,error:i}}case"request":{let s=(l=e.webauthn.credential_options.publicKey,c=null==t?void 0:t.request,t1(t0,l,c||{})),{data:n,error:i}=await tZ(Object.assign(Object.assign({},e.webauthn.credential_options),{publicKey:s,signal:h}));if(n)return{data:{factorId:r,challengeId:e.id,webauthn:{type:e.webauthn.type,credential_response:n}},error:null};return{data:null,error:i}}}}catch(e){if(eY(e))return{data:null,error:e};return{data:null,error:new eX("Unexpected error in challenge",e)}}}async _verify(e){let{challengeId:t,factorId:r,webauthn:s}=e;return this.client.mfa.verify({factorId:r,challengeId:t,webauthn:s})}async _authenticate(e,t){let{factorId:r,webauthn:{rpId:s="u">typeof window?window.location.hostname:void 0,rpOrigins:n="u">typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new eV("rpId is required for WebAuthn authentication")};try{if(!t$())return{data:null,error:new eX("Browser does not support WebAuthn",null)};let{data:e,error:a}=await this.challenge({factorId:r,webauthn:{rpId:s,rpOrigins:n},signal:i},{request:t});if(!e)return{data:null,error:a};let{webauthn:o}=e;return this._verify({factorId:r,challengeId:e.challengeId,webauthn:{type:o.type,rpId:s,rpOrigins:n,credential_response:o.credential_response}})}catch(e){if(eY(e))return{data:null,error:e};return{data:null,error:new eX("Unexpected error in authenticate",e)}}}async _register(e,t){let{friendlyName:r,webauthn:{rpId:s="u">typeof window?window.location.hostname:void 0,rpOrigins:n="u">typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new eV("rpId is required for WebAuthn registration")};try{if(!t$())return{data:null,error:new eX("Browser does not support WebAuthn",null)};let{data:e,error:a}=await this._enroll({friendlyName:r});if(!e)return await this.client.mfa.listFactors().then(e=>{var t;return null==(t=e.data)?void 0:t.all.find(e=>"webauthn"===e.factor_type&&e.friendly_name===r&&"unverified"!==e.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};let{data:o,error:l}=await this._challenge({factorId:e.id,friendlyName:e.friendly_name,webauthn:{rpId:s,rpOrigins:n},signal:i},{create:t});if(!o)return{data:null,error:l};return this._verify({factorId:e.id,challengeId:o.challengeId,webauthn:{rpId:s,rpOrigins:n,type:o.webauthn.type,credential_response:o.webauthn.credential_response}})}catch(e){if(eY(e))return{data:null,error:e};return{data:null,error:new eX("Unexpected error in register",e)}}}constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"u">typeof self&&(self.globalThis=self)}let t5={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:{"X-Client-Info":"gotrue-js/".concat(ez)},flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function t8(e,t,r){return await r()}let t3={};class t6{get jwks(){var e,t;return null!=(t=null==(e=t3[this.storageKey])?void 0:e.jwks)?t:{keys:[]}}set jwks(e){t3[this.storageKey]=Object.assign(Object.assign({},t3[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!=(t=null==(e=t3[this.storageKey])?void 0:e.cachedAt)?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){t3[this.storageKey]=Object.assign(Object.assign({},t3[this.storageKey]),{cachedAt:e})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return"GoTrueClient@"+"".concat(this.storageKey,":").concat(this.instanceID," (").concat(ez,") ").concat(new Date().toISOString())}_debug(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(tl()&&(t=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEac
2h((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),tl()&&this.detectSessionInUrl&&"none"!==r){let{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){(this._debug("#_initialize()","error detecting session from URL",n),eY(n)&&"AuthImplicitGrantRedirectError"===n.name)&&(null==(e=n.details)||e.code);return{error:n}}let{session:i,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(eY(e))return this._returnResult({error:e});return this._returnResult({error:new eX("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let{data:n,error:i}=await tC(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{data:null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.data)?r:{},gotrue_meta_security:{captcha_token:null==(s=null==e?void 0:e.options)?void 0:s.captchaToken}},xform:tj});if(i||!n)return this._returnResult({data:{user:null,session:null},error:i});let a=n.session,o=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let n;if("email"in e){let{email:r,password:s,options:i}=e,a=null,o=null;"pkce"===this.flowType&&([a,o]=await t_(this.storage,this.storageKey)),n=await tC(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:s,data:null!=(t=null==i?void 0:i.data)?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},xform:tj})}else if("phone"in e){let{phone:t,password:i,options:a}=e;n=await tC(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{phone:t,password:i,data:null!=(r=null==a?void 0:a.data)?r:{},channel:null!=(s=null==a?void 0:a.channel)?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:tj})}else throw new e2("You must provide either an email or phone number and a password");let{data:i,error:a}=n;if(a||!i)return await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),this._returnResult({data:{user:null,session:null},error:a});let o=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:n}=e;t=await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=password"),{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:tx})}else if("phone"in e){let{phone:r,password:s,options:n}=e;t=await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=password"),{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:tx})}else throw new e2("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new e1;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null==(t=e.options)?void 0:t.redirectTo,scopes:null==(r=e.options)?void 0:r.scopes,queryParams:null==(s=e.options)?void 0:s.queryParams,skipBrowserRedirect:null==(n=e.options)?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error('@supabase/auth-js: Unsupported chain "'.concat(t,'"'))}}async signInWithEthereum(e){var t,r,s,n,i,a,o,l,c,u,h,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{let u,{chain:h,wallet:g,statement:y,options:m}=e;if(tl())if("object"==typeof g)u=g;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)u=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==m?void 0:m.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");u=g}let w=new URL(null!=(t=null==m?void 0:m.url)?t:window.location.href),b=await u.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!b||0===b.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let v=tJ(b[0]),_=null==(r=null==m?void 0:m.signInWithEthereum)?void 0:r.chainId;_||(_=parseInt(await u.request({method:"eth_chainId"}),16)),f=function(e){var t;let{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:u,uri:h,version:d}=e;if(!Number.isInteger(r))throw Error('@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: '.concat(r));if(!s)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error('@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: '.concat(a));if(!h)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw Error("@supabase/auth-js: Invalid SIWE message field \"version\". Version must be '1'. Provided value: ".concat(d));if(null==(t=e.statement)?void 0:t.includes("\n"))throw Error("@supabase/auth-js: Invalid SIWE message field \"statement\". Statement must not include '\\n'. Provided value: ".concat(e.statement));let f=tJ(e.address),p=u?"".concat(u,"://").concat(s):s,g=e.statement?"".concat(e.statement,"\n"):"",y="".concat(p," wants you to sign in with your Ethereum account:\n").concat(f,"\n\n").concat(g),m="URI: ".concat(h,"\nVersion: ").concat(d,"\nChain ID: ").concat(r).concat(a?"\nNonce: ".concat(a):"","\nIssued At: ").concat(i.toISOString());if(n&&(m+="\nExpiration Time: ".concat(n.toISOString())),o&&(m+="\nNot Before: ".concat(o.toISOString())),l&&(m+="\
2nRequest ID: ".concat(l)),c){let e="\nResources:";for(let t of c){if(!t||"string"!=typeof t)throw Error('@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: '.concat(t));e+="\n- ".concat(t)}m+=e}return"".concat(y,"\n").concat(m)}({domain:w.host,address:v,statement:y,uri:w.href,version:"1",chainId:_,nonce:null==(s=null==m?void 0:m.signInWithEthereum)?void 0:s.nonce,issuedAt:null!=(i=null==(n=null==m?void 0:m.signInWithEthereum)?void 0:n.issuedAt)?i:new Date,expirationTime:null==(a=null==m?void 0:m.signInWithEthereum)?void 0:a.expirationTime,notBefore:null==(o=null==m?void 0:m.signInWithEthereum)?void 0:o.notBefore,requestId:null==(l=null==m?void 0:m.signInWithEthereum)?void 0:l.requestId,resources:null==(c=null==m?void 0:m.signInWithEthereum)?void 0:c.resources}),p=await u.request({method:"personal_sign",params:[(d=f,"0x"+Array.from(new TextEncoder().encode(d),e=>e.toString(16).padStart(2,"0")).join("")),v]})}try{let{data:t,error:r}=await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:p},(null==(u=e.options)?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null==(h=e.options)?void 0:h.captchaToken}}:null),xform:tj});if(r)throw r;if(!t||!t.session||!t.user){let e=new e1;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,n,i,a,o,l,c,u,h,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{let h,{chain:d,wallet:g,statement:y,options:m}=e;if(tl())if("object"==typeof g)h=g;else{let e=window;if("solana"in e&&"object"==typeof e.solana&&("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))h=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==m?void 0:m.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");h=g}let w=new URL(null!=(t=null==m?void 0:m.url)?t:window.location.href);if("signIn"in h&&h.signIn){let e,t=await h.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==m?void 0:m.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),y?{statement:y}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)f="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),p=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in h)||"function"!=typeof h.signMessage||!("publicKey"in h)||"object"!=typeof h||!h.publicKey||!("toBase58"in h.publicKey)||"function"!=typeof h.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=["".concat(w.host," wants you to sign in with your Solana account:"),h.publicKey.toBase58(),...y?["",y,""]:[""],"Version: 1","URI: ".concat(w.href),"Issued At: ".concat(null!=(s=null==(r=null==m?void 0:m.signInWithSolana)?void 0:r.issuedAt)?s:new Date().toISOString()),...(null==(n=null==m?void 0:m.signInWithSolana)?void 0:n.notBefore)?["Not Before: ".concat(m.signInWithSolana.notBefore)]:[],...(null==(i=null==m?void 0:m.signInWithSolana)?void 0:i.expirationTime)?["Expiration Time: ".concat(m.signInWithSolana.expirationTime)]:[],...(null==(a=null==m?void 0:m.signInWithSolana)?void 0:a.chainId)?["Chain ID: ".concat(m.signInWithSolana.chainId)]:[],...(null==(o=null==m?void 0:m.signInWithSolana)?void 0:o.nonce)?["Nonce: ".concat(m.signInWithSolana.nonce)]:[],...(null==(l=null==m?void 0:m.signInWithSolana)?void 0:l.requestId)?["Request ID: ".concat(m.signInWithSolana.requestId)]:[],...(null==(u=null==(c=null==m?void 0:m.signInWithSolana)?void 0:c.resources)?void 0:u.length)?["Resources",...m.signInWithSolana.resources.map(e=>"- ".concat(e))]:[]].join("\n");let e=await h.signMessage(new TextEncoder().encode(f),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{let{data:t,error:r}=await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:to(p)},(null==(h=e.options)?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null==(d=e.options)?void 0:d.captchaToken}}:null),xform:tj});if(r)throw r;if(!t||!t.session||!t.user){let e=new e1;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await tf(this.storage,"".concat(this.storageKey,"-code-verifier")),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new e3;let{data:t,error:n}=await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=pkce"),{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:tj});if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),n)throw n;if(!t||!t.session||!t.user){let e=new e1;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:n})}catch(e){if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),eY(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:n,nonce:i}=e,{data:a,error:o}=await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=id_token"),{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:tj});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new e1;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:o})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,n,i;try{if("email"in e){let{email:s,options:n}=e,i=null,a=null;"pkce"===this.flowType&&([i,a]=await t_(this.storage,this.storageKey));let{error:o}=await tC(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{email:s,data:null!=(t=null==n?void 0:n.data)?t:{},create_user:null==(r=null==n?void 0:n.shouldCreateUser)||r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:a},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){let{phone:t,options:r}=e,{data:a,error:o}=await tC(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{phone:t,data:null!=(s=null==r?void 0:r.data)?s:{},create_user:null==(n=null==r?void 0:r.shouldCreateUser)||n,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!=(i=null==r?void 0:r.channel)?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new e2("You must provide either an email or phone number.")}catch(e){if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=null==(t=e.options)?void 0:t.redirectTo,n=null==(r=e.options)?void 0:r.captchaToken);let{data:i,error:a}=await tC(this.fetch,"POST","".concat(this.url,"/verify"),{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:tj});if(a)throw a;if(!i)throw Error("An error occurred on token verification.");let o=i.session,l=i.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,n,i;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await t_(this.storage,this.storageKey));let l=await tC(this.fetch,"POST","".concat(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:null!=(r=null==(t=e.options)?void 0:t.redirectTo)?r:void 0}),(null==(s=null==e?void 0:e.options)?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:tN});return(null==(n=l.data)?void 0:n.url)&&tl()&&!(null==(i=e.options)?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),eY(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new eQ;let{error:s}=await tC(this.fetch,"GET","".concat(this.url,"/reauthenticate"),{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t="".concat(this.url,"/resend");if("email"in e){let{email:r,type:s,options:n}=e,{error:i}=await tC(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){let{phone:r,type:s,options:n}=e,{data:i,error:a}=await tC(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:a})}throw new e2("You must provide either an email or phone number and a type")}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock("lock:".concat(this.storageKey),e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let t=null,r=await tf(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),null!==r&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not val
2id"),await this._removeSession())),!t)return{data:{session:null},error:null};let s=!!t.expires_at&&1e3*t.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()","session has".concat(s?"":" not"," expired"),"expires_at",t.expires_at),!s){if(this.userStorage){let e=await tf(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=tT()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){var e;let r={value:this.suppressGetSessionWarning};t.user=(e=t.user,new Proxy(e,{get:(e,t,s)=>{if("__isInsecureUserWarningProxy"===t)return!0;if("symbol"==typeof t){let r=t.toString();if("Symbol(Symbol.toPrimitive)"===r||"Symbol(Symbol.toStringTag)"===r||"Symbol(util.inspect.custom)"===r||"Symbol(nodejs.util.inspect.custom)"===r)return Reflect.get(e,t,s)}return r.value||"string"!=typeof t||(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."),r.value=!0),Reflect.get(e,t,s)}})),r.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}let{data:n,error:i}=await this._callRefreshToken(t.refresh_token);if(i)return this._returnResult({data:{session:null},error:i});return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{if(e)return await tC(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:e,xform:tU});return await this._useSession(async e=>{var t,r,s;let{data:n,error:i}=e;if(i)throw i;return(null==(t=n.session)?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await tC(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:null!=(s=null==(r=n.session)?void 0:r.access_token)?s:void 0,xform:tU}):{data:{user:null},error:new eQ}})}catch(e){if(eY(e))return e0(e)&&(await this._removeSession(),await tp(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{return await this._useSession(async r=>{let{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new eQ;let i=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await t_(this.storage,this.storageKey));let{data:l,error:c}=await tC(this.fetch,"PUT","".concat(this.url,"/user"),{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:i.access_token,xform:tU});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),eY(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new eQ;let t=Date.now()/1e3,r=t,s=!0,n=null,{payload:i}=ty(e.access_token);if(i.exp&&(s=(r=i.exp)<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};n=t}else{let{data:s,error:i}=await this._getUser(e.access_token);if(i)return this._returnResult({data:{user:null,session:null},error:i});n={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(e){if(eY(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:s,error:n}=t;if(n)throw n;e=null!=(r=s.session)?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new eQ;let{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!tl())throw new e5("No browser detected.");
2if(e.error||e.error_description||e.error_code)throw new e5(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new e8("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new e5("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new e8("No code detected.");let{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;let s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}let{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:i,expires_in:a,expires_at:o,token_type:l}=e;if(!n||!a||!i||!l)throw new e5("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),h=c+u;o&&(h=parseInt(o));let d=h-c;1e3*d<=3e4&&console.warn("@supabase/gotrue-js: Session as retrieved from URL expires in ".concat(d,"s, should have been closer to ").concat(u,"s"));let f=h-u;c-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,h,c):c-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,h,c);let{data:p,error:g}=await this._getUser(n);if(g)throw g;let y={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:u,expires_at:h,refresh_token:i,token_type:l,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(e){if(eY(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await tf(this.storage,"".concat(this.storageKey,"-code-verifier"));return!!(e.code&&t)}async signOut(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{scope:"global"};return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut(){let{scope:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{scope:"global"};return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n&&!e0(n))return this._returnResult({error:n});let i=null==(r=s.session)?void 0:r.access_token;if(i){let{error:t}=await this.admin.signOut(i,e);if(t&&!(eY(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)||e0(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await tp(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({error:null})})}onAuthStateChange(e){let t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:s},error:n}=t;if(n)throw n;await (null==(r=this.stateChangeEmitters.get(e))?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await (null==(s=this.stateChangeEmitters.get(e))?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,s=null;"pkce"===this.flowType&&([r,s]=await t_(this.storage,this.storageKey,!0));try{return await tC(this.fetch,"POST","".concat(this.url,"/recover"),{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),eY(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!=(e=t.user.identities)?e:[]},error:null})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:s}=await this._useSession(async t=>{var r,s,n,i,a;let{data:o,error:l}=t;if(l)throw l;let c=await this._getUrlForProvider("".concat(this.url,"/user/identities/authorize"),e.provider,{redirectTo:null==(r=e.options)?void 0:r.redirectTo,scopes:null==(s=e.options)?void 0:s.scopes,queryParams:null==(n=e.options)?void 0:n.queryParams,skipBrowserRedirect:!0});return await tC(this.fetch,"GET",c,{headers:this.headers,jwt:null!=(a=null==(i=o.session)?void 0:i.access_token)?a:void 0})});if(s)throw s;return!tl()||(null==(t=e.options)?void 0:t.skipBrowserRedirect)||window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(eY(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:n}}=t;if(s)throw s;let{options:i,provider:a,token:o,access_token:l,nonce:c}=e,{data:u,error:h}=await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=id_token"),{headers:this.headers,jwt:null!=(r=null==n?void 0:n.access_token)?r:void 0,body:{provider:a,id_token:o,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:tj});if(h)return this._returnResult({data:{user:null,session:null},error:h});if(!u||!u.session||!u.user)return this._returnResult({data:{user:null,session:null},error:new e1});return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:h})}catch(e){if(await tp(this.storage,"".concat(this.storageKey,"-code-verifier")),eY(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:i}=t;if(i)throw i;
2return await tC(this.fetch,"DELETE","".concat(this.url,"/user/identities/").concat(e.identity_id),{headers:this.headers,jwt:null!=(s=null==(r=n.session)?void 0:r.access_token)?s:void 0})})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t="#_refreshAccessToken(".concat(e.substring(0,5),"...)");this._debug(t,"begin");try{var r,s;let n=Date.now();return await (r=async r=>(r>0&&await tm(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await tC(this.fetch,"POST","".concat(this.url,"/token?grant_type=refresh_token"),{body:{refresh_token:e},headers:this.headers,xform:tj})),s=(e,t)=>{let r=200*Math.pow(2,e);return t&&e4(t)&&Date.now()+r-n<3e4},new Promise((e,t)=>{(async()=>{for(let n=0;n<1/0;n++)try{let t=await r(n);if(!s(n,null))return void e(t)}catch(e){if(!s(n,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),eY(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider("".concat(this.url,"/authorize"),e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),tl()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await tf(this.storage,this.storageKey);if(s&&this.userStorage){let t=await tf(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await td(this.userStorage,this.storageKey+"-user",t)),s.user=null!=(e=null==t?void 0:t.user)?e:tT()}else if(s&&!s.user&&!s.user){let e=await tf(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await tp(this.storage,this.storageKey+"-user"),await td(this.storage,this.storageKey,s)):s.user=tT()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),null!==s&&await this._removeSession();return}let n=(null!=(t=s.expires_at)?t:1/0)*1e3-Date.now()<9e4;if(this._debug(r,"session has".concat(n?"":" not"," expired with margin of ").concat(9e4,"s")),n){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),e4(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{let{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(r,"error",e),console.error(e);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new eQ;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s="#_callRefreshToken(".concat(e.substring(0,5),"...)");this._debug(s,"begin");try{this.refreshingDeferred=new tg;let{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new eQ;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),eY(e)){let r={data:null,error:e};return e4(e)||await this._removeSession(),null==(t=this.refreshingDeferred)||t.resolve(r),r}throw null==(r=this.refreshingDeferred)||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t){let r=!(arguments.length>2)||void 0===arguments[2]||arguments[2],s="#_notifyAllSubscribers(".concat(e,")");this._debug(s,"begin",t,"broadcast = ".concat(r));try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],n=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(n),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await tp(this.storage,"".concat(this.storageKey,"-code-verifier"));let t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await td(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=tA(e);await td(this.storage,this.storageKey,s)}else{let e=tA(t);await td(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await tp(this.storage,this.storageKey),await tp(this.storage,this.storageKey+"-code-verifier"),await tp(this.storage,this.storageKey+"-user"),this.userStorage&&await tp(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&tl()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
2catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()","access token expires in ".concat(s," ticks, a tick lasts ").concat(3e4,"ms, refresh threshold is ").concat(3," ticks")),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof tK)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!tl()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t="#_onVisibilityChanged(".concat(e,")");this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"!==document.visibilityState?this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"):await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=["provider=".concat(encodeURIComponent(t))];if((null==r?void 0:r.redirectTo)&&s.push("redirect_to=".concat(encodeURIComponent(r.redirectTo))),(null==r?void 0:r.scopes)&&s.push("scopes=".concat(encodeURIComponent(r.scopes))),"pkce"===this.flowType){let[e,t]=await t_(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:"".concat(encodeURIComponent(e)),code_challenge_method:"".concat(encodeURIComponent(t))});s.push(r.toString())}if(null==r?void 0:r.queryParams){let e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push("skip_http_redirect=".concat(r.skipBrowserRedirect)),"".concat(e,"?").concat(s.join("&"))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await tC(this.fetch,"DELETE","".concat(this.url,"/factors/").concat(e.factorId),{headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token})})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await tC(this.fetch,"POST","".concat(this.url,"/factors"),{body:a,headers:this.headers,jwt:null==(r=null==n?void 0:n.session)?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===o.type&&(null==(s=null==o?void 0:o.totp)?void 0:s.qr_code)&&(o.totp.qr_code="data:image/svg+xml;utf-8,".concat(o.totp.qr_code)),this._returnResult({data:o,error:null}))})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r,s,n;let{data:i,error:a}=t;if(a)return this._returnResult({data:null,error:a});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?(s=e.webauthn.credential_response,"toJSON"in s&&"function"==typeof s.toJSON?s.toJSON():{id:s.id,rawId:s.id,response:{attestationObject:to(new Uint8Array(s.response.attestationObject)),clientDataJSON:to(new Uint8Array(s.response.clientDataJSON))},type:"public-key",clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:null!=(n=s.authenticatorAttachment)?n:void 0}):function(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();let r=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:to(new Uint8Array(s.authenticatorData)),clientDataJSON:to(new Uint8Array(s.clientDataJSON)),signature:to(new Uint8Array(s.signature)),userHandle:s.userHandle?to(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:c}=await tC(this.fetch,"POST","".concat(this.url,"/factors/").concat(e.factorId,"/verify"),{body:o,headers:this.headers,jwt:null==(r=null==i?void 0:i.session)?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:c}))})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});let i=await tC(this.fetch,"POST","".concat(this.url,"/factors/").concat(e.factorId,"/challenge"),{body:e,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});if(i.error)return i;let{data:a}=i;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:function(e){if(!e)throw Error("Credential creation options are required");if("u">typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,n=o(e,["challenge","user","excludeCredentials"]),i=ta(t).buffer,a=Object.assign(Object.assign({},r),{id:ta(r.id).buffer}),l=Object.assign(Object.assign({}
2,n),{challenge:i,user:a});if(s&&s.length>0){l.excludeCredentials=Array(s.length);for(let e=0;e<s.length;e++){let t=s[e];l.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:ta(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return l}(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:function(e){if(!e)throw Error("Credential request options are required");if("u">typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=o(e,["challenge","allowCredentials"]),n=ta(t).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];i.allowCredentials[e]=Object.assign(Object.assign({},t),{id:ta(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[]};for(let r of null!=(e=null==t?void 0:t.factors)?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,n;if(e)try{let{payload:s}=ty(e),n=null;s.aal&&(n=s.aal);let i=n,{data:{user:a},error:o}=await this.getUser(e);if(o)return this._returnResult({data:null,error:o});(null!=(r=null==(t=null==a?void 0:a.factors)?void 0:t.filter(e=>"verified"===e.status))?r:[]).length>0&&(i="aal2");let l=s.amr||[];return{data:{currentLevel:n,nextLevel:i,currentAuthenticationMethods:l},error:null}}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:i},error:a}
2=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:o}=ty(i.access_token),l=null;o.aal&&(l=o.aal);let c=l;return(null!=(n=null==(s=i.user.factors)?void 0:s.filter(e=>"verified"===e.status))?n:[]).length>0&&(c="aal2"),{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:o.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await tC(this.fetch,"GET","".concat(this.url,"/oauth/authorizations/").concat(e),{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new eQ})})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new eQ});let i=await tC(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(e,"/consent"),{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&tl()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new eQ});let i=await tC(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(e,"/consent"),{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&tl()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await tC(this.fetch,"GET","".concat(this.url,"/user/oauth/grants"),{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new eQ})})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await tC(this.fetch,"DELETE","".concat(this.url,"/user/oauth/grants"),{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new eQ})})}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{keys:[]},r=t.keys.find(t=>t.kid===e);if(r)return r;let s=Date.now();if((r=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+6e5>s)return r;let{data:n,error:i}=await tC(this.fetch,"GET","".concat(this.url,"/.well-known/jwks.json"),{headers:this.headers});if(i)throw i;return n.keys&&0!==n.keys.length&&(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(t=>t.kid===e))?r:null}async getClaims(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{var r;let s,n=e;if(!n){let{data:e,error:t}
2=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}let{header:i,payload:a,signature:o,raw:{header:l,payload:c}}=ty(n);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(a.exp);let u=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!u){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:a,header:i,signature:o},error:null}}let h=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(i.alg),d=await crypto.subtle.importKey("jwk",u,h,!0,["verify"]);if(!await crypto.subtle.verify(h,d,o,(r="".concat(l,".").concat(c),s=[],!function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error("Unrecognized Unicode codepoint: ".concat(e.toString(16)))}(s,t)}}(r,e=>s.push(e)),new Uint8Array(s))))throw new e7("Invalid JWT signature");return{data:{claims:a,header:i,signature:o},error:null}}catch(e){if(eY(e))return this._returnResult({data:null,error:e});throw e}}constructor(e){var t,r,s;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({},t5),e);if(this.storageKey=n.storageKey,this.instanceID=null!=(t=t6.nextInstanceID[this.storageKey])?t:0,t6.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&tl()){const e="".concat(this._logPrefix()," Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.admin=new tq({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=th(n.fetch),this.lock=n.lock||t8,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&&tl()&&(null==(r=null==globalThis?void 0:globalThis.navigator)?void 0:r.locks)?this.lock=tz:this.lock=t8,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 t2(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:tu()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=tM(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=tM(this.memoryStorage)),tl()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null==(s=this.broadcastChannel)||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}})}this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}}t6.nextInstanceID={};let t4=t6,t9="";t9="u">typeof Deno?"deno":"u">typeof document?"web":"u">typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";let t7={headers:{"X-Client-Info":"supabase-js-".concat(t9,"/").concat("2.93.2")}},re={schema:"public"},rt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},rr={};function rs(e){return(rs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function rn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function ri(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};
2t%2?rn(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=rs(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=rs(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==rs(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rn(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var ra=class extends t4{constructor(e){super(e)}},ro=class{get functions(){return new l(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{head:!1,get:!1,count:void 0};return this.rest.rpc(e,t,r)}channel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{config:{}};return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();let{data:r}=await this.auth.getSession();return null!=(e=null==(t=r.session)?void 0:t.access_token)?e:this.supabaseKey}_initSupabaseAuthClient(e,t,r){let{autoRefreshToken:s,persistSession:n,detectSessionInUrl:i,storage:a,userStorage:o,storageKey:l,flowType:c,lock:u,debug:h,throwOnError:d}=e,f={Authorization:"Bearer ".concat(this.supabaseKey),apikey:"".concat(this.supabaseKey)};return new ra({url:this.authUrl.href,headers:ri(ri({},f),t),storageKey:l,autoRefreshToken:s,persistSession:n,detectSessionInUrl:i,storage:a,userStorage:o,flowType:c,lock:u,debug:h,throwOnError:d,fetch:r,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new es(this.realtimeUrl.href,ri(ri({},e),{},{params:ri(ri({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}constructor(e,t,r){var s,n,i;this.supabaseUrl=e,this.supabaseKey=t;const a=function(e){let t=null==e?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(t.endsWith("/")?t:t+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o="sb-".concat(a.hostname.split(".")[0],"-auth-token"),l=function(e,t){var r,s;let{db:n,auth:i,realtime:a,global:o}=e,{db:l,auth:c,realtime:u,global:h}=t,d={db:ri(ri({},l),n),auth:ri(ri({},c),i),realtime:ri(ri({},u),a),storage:{},global:ri(ri(ri({},h),o),{},{headers:ri(ri({},null!=(r=null==h?void 0:h.headers)?r:{}),null!=(s=null==o?void 0:o.headers)?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:re,realtime:rr,auth:ri(ri({},rt),{},{storageKey:o}),global:t7});this.storageKey=null!=(s=l.auth.storageKey)?s:"",this.headers=null!=(n=l.global.headers)?n:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error("@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.".concat(String(t)," is not possible"))}})):this.auth=this._initSupabaseAuthClient(null!=(i=l.auth)?i:{},this.headers,l.global.fetch),this.fetch=((e,t,r)=>{let s=r?function(){for(var e=arguments.length,t=Array(e),s=0;s<e;s++)t[s]=arguments[s];return r(...t)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)},n=Headers;return async(r,i)=>{var a;let o=null!=(a=await t())?a:e,l=new n(null==i?void 0:i.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization","Bearer ".concat(o)),s(r,ri(ri({},i),{},{headers:l}))}})(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(ri({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new D(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this.storage=new eF(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}};(function(){if("u">typeof window)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&18>=parseInt(r[1],10)})()&&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 N
2ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let rl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rc=" 	\n\r=".split(""),ru=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<rc.length;t+=1)e[rc[t].charCodeAt(0)]=-2;for(let t=0;t<rl.length;t+=1)e[rl[t].charCodeAt(0)]=t;return e})();function rh(e){let t=[],r=0,s=0;if(function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error("Unrecognized Unicode codepoint: ".concat(e.toString(16)))}(s,t)}}(e,e=>{for(r=r<<8|e,s+=8;s>=6;){let e=r>>s-6&63;t.push(rl[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(rl[e]),s-=6}return t.join("")}function rd(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n=0,i=0;for(let t=0;t<e.length;t+=1){let a=ru[e.charCodeAt(t)];if(a>-1)for(n=n<<6|a,i+=6;i>=8;)(function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}})(n>>i-8&255,s,r),i-=8;else if(-2===a)continue;else throw Error('Invalid Base64-URL character "'.concat(e.at(t),'" at position ').concat(t))}return t.join("")}var rf=e.i(909156);function rp(){return"u">typeof window&&void 0!==window.document}rf.parse,rf.serialize;let rg={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},ry=/^(.*)[.](0|[1-9][0-9]*)$/;function rm(e,t){if(e===t)return!0;let r=e.match(ry);return!!r&&r[1]===t}function rw(e,t,r){let s=null!=r?r:3180,n=encodeURIComponent(t);if(n.length<=s)return[{name:e,value:t}];let i=[];for(;n.length>0;){let e=n.slice(0,s),t=e.lastIndexOf("%");t>s-3&&(e=e.slice(0,t));let r="";for(;e.length>0;)try{r=decodeURIComponent(e);break}catch(t){if(t instanceof URIError&&"%"===e.at(-3)&&e.length>3)e=e.slice(0,e.length-3);else throw t}i.push(r),n=n.slice(e.length)}return i.map((t,r)=>({name:"".concat(e,".").concat(r),value:t}))}async function rb(e,t){let r=await t(e);if(r)return r;let s=[];for(let r=0;;r++){let n="".concat(e,".").concat(r),i=await t(n);if(!i)break;s.push(i)}return s.length>0?s.join(""):null}let rv="base64-";async function r_(e,t){var r;let{getAll:s,setAll:n,setItems:i,removedItems:a}=e,o=t.cookieEncoding,l=null!=(r=t.cookieOptions)?r:null,c=await s([...i?Object.keys(i):[],...a?Object.keys(a):[]]),u=(null==c?void 0:c.map(e=>{let{name:t}=e;return t}))||[],h=Object.keys(a).flatMap(e=>u.filter(t=>rm(t,e))),d=Object.keys(i).flatMap(e=>{let t=new Set(u.filter(t=>rm(t,e))),r=i[e];"base64url"===o&&(r=rv+rh(r));let s=rw(e,r);return s.forEach(e=>{t.delete(e.name)}),h.push(...t),s}),f={...rg,...l,maxAge:0},p={...rg,...l,maxAge:rg.maxAge};delete f.name,delete p.name,await n([...h.map(e=>({name:e,value:"",options:f})),...d.map(e=>{let{name:t,value:r}=e;return{name:t,value:r,options:p}})])}function rS(e){return"object"==typeof e&&null!==e}function rk(e){let t=rS(e)&&"string"==typeof e.message?e.message:"",r=rS(e)&&"string"==typeof e.code?e.code:"";return{message:t.toLowerCase(),code:r.toLowerCase()}}function rE(e){if(!rS(e))return null;let t=e.status;return"number"==typeof t?t:null}function rT(e){let{message:t,code:r}=rk(e);return!function(e){let{message:t,code:r}=rk(e);return r.includes("refresh_token_already_used")||t.includes("refresh_token_already_used")||t.includes("invalid refresh token: already used")||t.includes("already used")&&t.includes("refresh token")}(e)&&(r.includes("invalid_grant")||r.includes("session_not_found")||r.includes("refresh_token_not_found")||t.includes("invalid refresh token")||t.includes("refresh token not found")||t.includes("refresh token has been revoked")||t.includes("token has been revoked")||t.includes("refresh token revoked")||t.includes("refresh token expired")||t.includes("session_expired")||t.includes("jwt expired")&&t.includes("refresh"))}function rA(e){let{message:t,code:r}=rk(e);return 429===rE(e)||r.includes("over_request_rate_limit")||r.includes("too_many_requests")||t.includes("429")||t.includes("rate limit")||t.includes("too many requests")}function rO(e){return 400===rE(e)}e.s(["createBrowserClient",0,function(e,t,s){var n,i,a;let o=(null==s?void 0:s.isSingleton)===!0||(!s||!("isSingleton"in s))&&rp();if(o&&r)return r;if(!e||!t)throw Error("@supabase/ssr: Your project's URL and API key are required to create a Supabase client!\n\nCheck your Supabase project's API settings to find these values\n\nhttps://supabase.com/dashboard/project/_/settings/api");let{storage:l}=function(e,t){var r;let s,n,i=null!=(r=e.cookies)?r:null,a=e.cookieEncoding,o={},l={};if(i)if("get"in i){let e=async e=>{let t=e.flatMap(e=>[e,...Array.from({length:5}).map((t,r)=>"".concat(e,".").concat(r))]),r=[];for(let e=0;e<t.length;e+=1){let s=await i.get(t[e]);(s||"string"==typeof s)&&r.push({name:t[e],value:s})}return r};if(s=async t=>await e(t),"set"in i&&"remove"in i)n=async e=>{for(let t=0;t<e.length;t+=1){let{name:r,value:s,options:n}=e[t];s?await i.set(r,s,n):await i.remove(r,n)}};else if(t)n=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for c
2orrectness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in i)if(s=async()=>await i.getAll(),"setAll"in i)n=i.setAll;else if(t)n=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)");else throw Error("@supabase/ssr: ".concat(t?"createServerClient":"createBrowserClient"," requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).").concat(rp()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""));else if(!t&&rp())s=()=>{let e;return Object.keys(e=(0,rf.parse)(document.cookie)).map(t=>{var r;return{name:t,value:null!=(r=e[t])?r:""}})},n=e=>{e.forEach(e=>{let{name:t,value:r,options:s}=e;document.cookie=(0,rf.serialize)(t,r,s)})};else if(t)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else s=()=>[],n=()=>{throw Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")};return t?{getAll:s,setAll:n,setItems:o,removedItems:l,storage:{isServer:!0,getItem:async e=>{if("string"==typeof o[e])return o[e];if(l[e])return null;let t=await s([e]),r=await rb(e,async e=>{let r=(null==t?void 0:t.find(t=>{let{name:r}=t;return r===e}))||null;return r?r.value:null});if(!r)return null;let n=r;return"string"==typeof r&&r.startsWith(rv)&&(n=rd(r.substring(rv.length))),n},setItem:async(t,r)=>{if(t.endsWith("-code-verifier")){var i;await r_({getAll:s,setAll:n,setItems:{[t]:r},removedItems:{}},{cookieOptions:null!=(i=null==e?void 0:e.cookieOptions)?i:null,cookieEncoding:a})}o[t]=r,delete l[t]},removeItem:async e=>{delete o[e],l[e]=!0}}}:{getAll:s,setAll:n,setItems:o,removedItems:l,storage:{isServer:!1,getItem:async e=>{let t=await s([e]),r=await rb(e,async e=>{let r=(null==t?void 0:t.find(t=>{let{name:r}=t;return r===e}))||null;return r?r.value:null});if(!r)return null;let n=r;return r.startsWith(rv)&&(n=rd(r.substring(rv.length))),n},setItem:async(t,r)=>{let i=await s([t]),o=new Set(((null==i?void 0:i.map(e=>{let{name:t}=e;return t}))||[]).filter(e=>rm(e,t))),l=r;"base64url"===a&&(l=rv+rh(r));let c=rw(t,l);c.forEach(e=>{let{name:t}=e;o.delete(t)});let u={...rg,...null==e?void 0:e.cookieOptions,maxAge:0},h={...rg,...null==e?void 0:e.cookieOptions,maxAge:rg.maxAge};delete u.name,delete h.name;let d=[...[...o].map(e=>({name:e,value:"",options:u})),...c.map(e=>{let{name:t,value:r}=e;return{name:t,value:r,options:h}})];d.length>0&&await n(d)},removeItem:async t=>{let r=await s([t]),i=((null==r?void 0:r.map(e=>{let{name:t}=e;return t}))||[]).filter(e=>rm(e,t)),a={...rg,...null==e?void 0:e.cookieOptions,maxAge:0};delete a.name,i.length>0&&await n(i.map(e=>({name:e,value:"",options:a})))}}}}({...s,cookieEncoding:null!=(n=null==s?void 0:s.cookieEncoding)?n:"base64url"},!1),c=new ro(e,t,{...s,global:{...null==s?void 0:s.global,headers:{...null==s||null==(i=s.global)?void 0:i.headers,"X-Client-Info":"supabase-ssr/".concat("0.7.0"," createBrowserClient")}},auth:{...null==s?void 0:s.auth,...(null==s||null==(a=s.cookieOptions)?void 0:a.name)?{storageKey:s.cookieOptions.name}:null,flowType:"pkce",autoRefreshToken:rp(),detectSessionInUrl:rp(),persistSession:!0,storage:l}});return o&&(r=c),c}],972390),e.s([],529225),e.s(["getSupabaseAnonKey",0,function(){return"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZ4dnhtb2drbnlta3Zpamt1Ym5sIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjI4NDAxMDksImV4cCI6MjA3ODQxNjEwOX0.pq8PGq27N6d_lpZxwTdCSmTqVmBHwpyh8GH9-yv_rpc"},"getSupabaseUrl",0,function(){return"https://fxvxmogknymkvijkubnl.supabase.co"}],14602),e.s(["isBadRequestError",0,rO,"isDefinitiveInvalidRefreshTokenError",0,rT,"isRefreshRateLimitError",0,rA,"isTransientAuthUserFetchError",0,function(e){if(!e)return!1;if(rA(e))return!0;let t=rE(e);if("number"==typeof t&&t>=500&&t<=599)return!0;let{message:r}=rk(e);return r.includes("fetch")||r.includes("network")||r.includes("failed to fetch")||r.includes("timeout")||r.includes("timed out")||r.includes("load failed")},"isTransientRefreshError",0,function(e){if(rT(e))return!1;if(rA(e))return!0;
2if(rO(e))return!1;let{message:t}=rk(e),r=rE(e);return"number"==typeof r&&r>=500&&r<=599||t.includes("network")||t.includes("timeout")||t.includes("timed out")||t.includes("failed to fetch")||t.includes("fetch failed")||t.includes("temporary")}],999309)},909156,(e,t,r)=>{"use strict";let s;Object.defineProperty(r,"__esModule",{value:!0}),r.parseCookie=h,r.parse=h,r.stringifyCookie=function(e,t){let r=(null==t?void 0:t.encode)||encodeURIComponent,s=[];for(let t of Object.keys(e)){let a=e[t];if(void 0===a)continue;if(!n.test(t))throw TypeError("cookie name is invalid: ".concat(t));let o=r(a);if(!i.test(o))throw TypeError("cookie val is invalid: ".concat(a));s.push("".concat(t,"=").concat(o))}return s.join("; ")},r.stringifySetCookie=d,r.serialize=d,r.parseSetCookie=function(e,t){let r=(null==t?void 0:t.decode)||y,s=e.length,n=f(e,0,s),i=p(e,0,n),a=-1===i?{name:"",value:r(g(e,0,n))}:{name:g(e,0,i),value:r(g(e,i+1,n))},o=n+1;for(;o<s;){let t=f(e,o,s),r=p(e,o,t),n=-1===r?g(e,o,t):g(e,o,r),i=-1===r?void 0:g(e,r+1,t);switch(n.toLowerCase()){case"httponly":a.httpOnly=!0;break;case"secure":a.secure=!0;break;case"partitioned":a.partitioned=!0;break;case"domain":a.domain=i;break;case"path":a.path=i;break;case"max-age":i&&l.test(i)&&(a.maxAge=Number(i));break;case"expires":if(!i)break;let c=new Date(i);Number.isFinite(c.valueOf())&&(a.expires=c);break;case"priority":if(!i)break;let u=i.toLowerCase();("low"===u||"medium"===u||"high"===u)&&(a.priority=u);break;case"samesite":if(!i)break;let h=i.toLowerCase();("lax"===h||"strict"===h||"none"===h)&&(a.sameSite=h)}o=t+1}return a},r.stringifySetCookie=d,r.serialize=d;let n=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,i=/^[\u0021-\u003A\u003C-\u007E]*$/,a=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,o=/^[\u0020-\u003A\u003D-\u007E]*$/,l=/^-?\d+$/,c=Object.prototype.toString,u=((s=function(){}).prototype=Object.create(null),s);function h(e,t){let r=new u,s=e.length;if(s<2)return r;let n=(null==t?void 0:t.decode)||y,i=0;do{let t=p(e,i,s);if(-1===t)break;let a=f(e,i,s);if(t>a){i=e.lastIndexOf(";",t-1)+1;continue}let o=g(e,i,t);void 0===r[o]&&(r[o]=n(g(e,t+1,a))),i=a+1}while(i<s)return r}function d(e,t,r){let s="object"==typeof e?e:{...r,name:e,value:String(t)},l="object"==typeof t?t:r,u=(null==l?void 0:l.encode)||encodeURIComponent;if(!n.test(s.name))throw TypeError("argument name is invalid: ".concat(s.name));let h=s.value?u(s.value):"";if(!i.test(h))throw TypeError("argument val is invalid: ".concat(s.value));let d=s.name+"="+h;if(void 0!==s.maxAge){if(!Number.isInteger(s.maxAge))throw TypeError("option maxAge is invalid: ".concat(s.maxAge));d+="; Max-Age="+s.maxAge}if(s.domain){if(!a.test(s.domain))throw TypeError("option domain is invalid: ".concat(s.domain));d+="; Domain="+s.domain}if(s.path){if(!o.test(s.path))throw TypeError("option path is invalid: ".concat(s.path));d+="; Path="+s.path}if(s.expires){var f;if(f=s.expires,"[object Date]"!==c.call(f)||!Number.isFinite(s.expires.valueOf()))throw TypeError("option expires is invali
2d: ".concat(s.expires));d+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(d+="; HttpOnly"),s.secure&&(d+="; Secure"),s.partitioned&&(d+="; Partitioned"),s.priority)switch("string"==typeof s.priority?s.priority.toLowerCase():void 0){case"low":d+="; Priority=Low";break;case"medium":d+="; Priority=Medium";break;case"high":d+="; Priority=High";break;default:throw TypeError("option priority is invalid: ".concat(s.priority))}if(s.sameSite)switch("string"==typeof s.sameSite?s.sameSite.toLowerCase():s.sameSite){case!0:case"strict":d+="; SameSite=Strict";break;case"lax":d+="; SameSite=Lax";break;case"none":d+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid: ".concat(s.sameSite))}return d}function f(e,t,r){let s=e.indexOf(";",t);return -1===s?r:s}function p(e,t,r){let s=e.indexOf("=",t);return s<r?s:-1}function g(e,t,r){let s=t,n=r;do{let t=e.charCodeAt(s);if(32!==t&&9!==t)break}while(++s<n)for(;n>s;){let t=e.charCodeAt(n-1);if(32!==t&&9!==t)break;n--}return e.slice(s,n)}function y(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch(t){return e}}},467034,(e,t,r)=>{var s={872:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],s=t[1];return(r+s)*3/4-s},t.toByteArray=function(e){var t,r,i=l(e),a=i[0],o=i[1],c=new n((a+o)*3/4-o),u=0,h=o>0?a-4:a;for(r=0;r<h;r+=4)t=s[e.charCodeAt(r)]<<18|s[e.charCodeAt(r+1)]<<12|s[e.charCodeAt(r+2)]<<6|s[e.charCodeAt(r+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=255&t;return 2===o&&(t=s[e.charCodeAt(r)]<<2|s[e.charCodeAt(r+1)]>>4,c[u++]=255&t),1===o&&(t=s[e.charCodeAt(r)]<<10|s[e.charCodeAt(r+1)]<<4|s[e.charCodeAt(r+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t),c},t.fromByteArray=function(e){for(var t,s=e.length,n=s%3,i=[],a=0,o=s-n;a<o;a+=16383)i.push(function(e,t,s){for(var n,i=[],a=t;a<s;a+=3)n=(e[a]<<16&0xff0000)+(e[a+1]<<8&65280)+(255&e[a+2]),i.push(r[n>>18&63]+r[n>>12&63]+r[n>>6&63]+r[63&n]);return i.join("")}(e,a,a+16383>o?o:a+16383));return 1===n?i.push(r[(t=e[s-1])>>2]+r[t<<4&63]+"=="):2===n&&i.push(r[(t=(e[s-2]<<8)+e[s-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),i.join("")};for(var r=[],s=[],n="u">typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,o=i.length;a<o;++a)r[a]=i[a],s[i.charCodeAt(a)]=a;function l(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var s=r===t?0:4-r%4;return[r,s]}s[45]=62,s[95]=63},230:function(e,t,r){"use strict";var s=r(872),n=r(321),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function a(e){if(e>0x7fffffff)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,o.prototype),t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return u(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e){var s=e,n=t;if(("string"!=typeof n||""===n)&&(n="utf8"),!o.isEncoding(n))throw TypeError("Unknown encoding: "+n);var i=0|f(s,n),l=a(i),c=l.write(s,n);return c!==i&&(l=l.slice(0,c)),l}if(ArrayBuffer.isView(e))return h(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(I(e,ArrayBuffer)||e&&I(e.buffer,ArrayBuffer)||"u">typeof SharedArrayBuffer&&(I(e,SharedArrayBuffer)||e&&I(e.buffer,SharedArrayBuffer)))return function(e,t,r){var s;if(t<0||e.byteLength<t)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(s=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),o.prototype),s}(e,t,r);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var u=e.valueOf&&e.valueOf();if(null!=u&&u!==e)return o.from(u,t,r);var p=function(e){if(o.isBuffer(e)){var t=0|d(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||function(e){return e!=e}(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(p)return p;if("u">typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');
vendor: 16,509 bytes, line 2
2if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return c(e),a(e<0?0:0|d(e))}function h(e){for(var t=e.length<0?0:0|d(e.length),r=a(t),s=0;s<t;s+=1)r[s]=255&e[s];return r}t.Buffer=o,t.SlowBuffer=function(e){return+e!=e&&(e=0),o.alloc(+e)},t.INSPECT_MAX_BYTES=50,t.kMaxLength=0x7fffffff,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!o.TYPED_ARRAY_SUPPORT&&"u">typeof console&&"function"==typeof console.error&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(e,t,r){return(c(e),e<=0)?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)},o.allocUnsafe=function(e){return u(e)},o.allocUnsafeSlow=function(e){return u(e)};function d(e){if(e>=0x7fffffff)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function f(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||I(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,s=arguments.length>2&&!0===arguments[2];if(!s&&0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return T(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return O(e).length;default:if(n)return s?-1:T(e).length;t=(""+t).toLowerCase(),n=!0}}function p(e,t,r){var n,i,a,o=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var s=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>s)&&(r=s);for(var n="",i=t;i<r;++i)n+=C[e[i]];return n}(this,t,r);case"utf8":case"utf-8":return w(this,t,r);case"ascii":return function(e,t,r){var s="";r=Math.min(e.length,r);for(var n=t;n<r;++n)s+=String.fromCharCode(127&e[n]);return s}(this,t,r);case"latin1":case"binary":return function(e,t,r){var s="";r=Math.min(e.length,r);for(var n=t;n<r;++n)s+=String.fromCharCode(e[n]);return s}(this,t,r);case"base64":return n=this,i=t,a=r,0===i&&a===n.length?s.fromByteArray(n):s.fromByteArray(n.slice(i,a));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,r){for(var s=e.slice(t,r),n="",i=0;i<s.length;i+=2)n+=String.fromCharCode(s[i]+256*s[i+1]);return n}(this,t,r);default:if(o)throw TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function g(e,t,r){var s=e[t];e[t]=e[r],e[r]=s}function y(e,t,r,s,n){var i;if(0===e.length)return -1;if("string"==typeof r?(s=r,r=0):r>0x7fffffff?r=0x7fffffff:r<-0x80000000&&(r=-0x80000000),(i=r*=1)!=i&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length)if(n)return -1;else r=e.length-1;else if(r<0)if(!n)return -1;else r=0;if("string"==typeof t&&(t=o.from(t,s)),o.isBuffer(t))return 0===t.length?-1:m(e,t,r,s,n);if("number"==typeof t){if(t&=255,"function"==typeof Uint8Array.prototype.indexOf)if(n)return Uint8Array.prototype.indexOf.call(e,t,r);else return Uint8Array.prototype.lastIndexOf.call(e,t,r);return m(e,[t],r,s,n)}throw TypeError("val must be string, number or Buffer")}function m(e,t,r,s,n){var i,a=1,o=e.length,l=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return -1;a=2,o/=2,l/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(n){var u=-1;for(i=r;i<o;i++)if(c(e,i)===c(t,-1===u?0:i-u)){if(-1===u&&(u=i),i-u+1===l)return u*a}else -1!==u&&(i-=i-u),u=-1}else for(r+l>o&&(r=o-l),i=r;i>=0;i--){for(var h=!0,d=0;d<l;d++)if(c(e,i+d)!==c(t,d)){h=!1;break}if(h)return i}return -1}o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(I(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),I(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,s=t.length,n=0,i=Math.min(r,s);n<i;++n)if(e[n]!==t[n]){r=e[n],s=t[n];break}return r<s?-1:+(s<r)},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);if(void 0===t)for(r=0,t=0;r<e.length;++r)t+=e[r].length;var r,s=o.allocUnsafe(t),n=0;for(r=0;r<e.length;++r){var i=e[r];if(I(i,Uint8Array)&&(i=o.from(i)),!o.isBuffer(i))throw TypeError('"list" argument must be an Array of Buffers');i.copy(s,n),n+=i.length}return s},o.byteLength=f,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0==arguments.length?w(this,0,e):p.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},i&&(o.prototype[i]=o.prototype.inspect),o.prototype.compare=function(e,t,r,s,n){if(I(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===s&&(s=0),void 0===n&&(n=this.length),t<0||r>e.length||s<0||n>this.length)throw RangeError("out of range index");if(s>=n&&t>=r)return 0;if(s>=n)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,s>>>=0,n>>>=0,this===e)return 0;for(var i=n-s,a=r-t,l=Math.min(i,a),c=this.slice(s,n),u=e.slice(t,r),h=0;h<l;++h)if(c[h]!==u[h]){i=c[h],a=u[h];break}return i<a?-1:+(a<i)},o.prototype.includes=function(e,t,r){return -1!==this.indexOf(e,t,r)},o.prototype.indexOf=function(e,t,r){return y(this,e,t,r,!0)},o.prototype.lastIndexOf=function(e,t,r){return y(this,e,t,r,!1)};function w(e,t,r){r=Math.min(e.length,r);for(var s=[],n=t;n<r;){var i,a,o,l,c=e[n],u=null,h=c>239?4:c>223?3:c>191?2:1;if(n+h<=r)switch(h){case 1:c<128&&(u=c);break;case 2:(192&(i=e[n+1]))==128&&(l=(31&c)<<6|63&i)>127&&(u=l);break;case 3:i=e[n+1],a=e[n+2],(192&i)==128&&(192&a)==128&&(l=(15&c)<<12|(63&i)<<6|63&a)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:i=e[n+1],a=e[n+2],o=e[n+3],(192&i)==128&&(192&a)==128&&(192&o)==128&&(l=(15&c)<<18|(63&i)<<12|(63&a)<<6|63&o)>65535&&l<1114112&&(u=l)}null===u?(u=65533,h=1):u>65535&&(u-=65536,s.push(u>>>10&1023|55296),u=56320|1023&u),s.push(u),n+=h}var d=s,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var p="",g=0;g<f;)p+=String.fromCharCode.apply(String,d.slice(g,g+=4096));return p}function b(e,t,r){if(e%1!=0||e<0)throw RangeError("offset is not uint");if(e+t>r)throw RangeError("Trying to access beyond buffer length")}function v(e,t,r,s,n,i){if(!o.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<i)throw RangeError('"value" argument is out of bounds');if(r+s>e.length)throw RangeError("Index out of range")}function _(e,t,r,s,n,i){if(r+s>e.length||r<0)throw RangeError("Index out of range")}function S(e,t,r,s,i){return t*=1,r>>>=0,i||_(e,t,r,4,34028234663852886e22,-34028234663852886e22),n.write(e,t,r,s,23,4),r+4}function k(e,t,r,s,i){return t*=1,r>>>=0,i||_(e,t,r,8,17976931348623157e292,-17976931348623157e292),n.write(e,t,r,s,52,8),r+8}o.prototype.write=function(e,t,r,s){if(void 0===t)s="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)s=t,r=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(r)?(r>>>=0,void 0===s&&(s="utf8")):(s=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var n,i,a,o,l,c,u,h,d=this.length-t;if((void 0===r||r>d)&&(r=d),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var f=!1;;)switch(s){case"hex":return function(e,t,r,s){r=Number(r)||0;var n=e.length-r;s?(s=Number(s))>n&&(s=n):s=n;var i=t.length;s>i/2&&(s=i/2);for(var a=0;a<s;++a){var o,l=parseInt(t.substr(2*a,2),16);if((o=l)!=o)break;e[r+a]=l}return a}(this,e,t,r);case"utf8":case"utf-8":return n=t,i=r,R(T(e,this.length-n),this,n,i);case"ascii":return a=t,o=r,R(A(e),this,a,o);case"latin1":case"binary":return function(e,t,r,s){return R(A(t),e,r,s)}(this,e,t,r);case"base64":return l=t,c=r,R(O(e),this,l,c);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u=t,h=r,R(function(e,t){for(var r,s,n=[],i=0;i<e.length&&!((t-=2)<0);++i)s=(r=e.charCodeAt(i))>>8,n.push(r%256),n.push(s);return n}(e,this.length-u),this,u,h);default:if(f)throw TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),f=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);var s=this.subarray(e,t);return Object.setPrototypeOf(s,o.prototype),s},o.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e],n=1,i=0;++i<t&&(n*=256);)s+=this[e+i]*n;return s},o.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e+--t],n=1;t>0&&(n*=256);)s+=this[e+--t]*n;return s},o.prototype.readUInt8=function(e,t){return e>>>=0,t||b(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+0x1000000*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),0x1000000*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e],n=1,i=0;++i<t&&(n*=256);)s+=this[e+i]*n;return s>=(n*=128)&&(s-=Math.pow(2,8*t)),s},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=t,n=1,i=this[e+--s];s>0&&(n*=256);)i+=this[e+--s]*n;return i>=(n*=128)&&(i-=Math.pow(2,8*t)),i},o.prototype.readInt8=function(e,t){return(e>>>=0,t||b(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||b(e,4,this.length),n.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||b(e,4,this.length),n.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||b(e,8,this.length),n.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||b(e,8,this.length),n.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,s){if(e*=1,t>>>=0,r>>>=0,!s){var n=Math.pow(2,8*r)-1;v(this,e,t,r,n,0)}var i=1,a=0;for(this[t]=255&e;++a<r&&(i*=256);)this[t+a]=e/i&255;return t+r},o.prototype.writeUIntBE=function(e,t,r,s){if(e*=1,t>>>=0,r>>>=0,!s){var n=Math.pow(2,8*r)-1;v(this,e,t,r,n,0)}var i=r-1,a=1;for(this[t+i]=255&e;--i>=0&&(a*=256);)this[t+i]=e/a&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,s){if(e*=1,t>>>=0,!s){var n=Math.pow(2,8*r-1);v(this,e,t,r,n-1,-n)}var i=0,a=1,o=0;for(this[t]=255&e;++i<r&&(a*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/a|0)-o&255;return t+r},o.prototype.writeIntBE=function(e,t,r,s){if(e*=1,t>>>=0,!s){var n=Math.pow(2,8*r-1);v(this,e,t,r,n-1,-n)}var i=r-1,a=1,o=0;for(this[t+i]=255&e;--i>=0&&(a*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/a|0)-o&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),e<0&&(e=0xffffffff+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return S(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return S(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return k(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return k(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,s){if(!o.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s<r&&(s=r),s===r||0===e.length||0===this.length)return 0;if(t<0)throw RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw RangeError("Index out of range");if(s<0)throw RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t<s-r&&(s=e.length-t+r);var n=s-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,s);else if(this===e&&r<t&&t<s)for(var i=n-1;i>=0;--i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,s),t);return n},o.prototype.fill=function(e,t,r,s){if("string"==typeof e){if("string"==typeof t?(s=t,t=0,r=this.length):"string"==typeof r&&(s=r,r=this.length),void 0!==s&&"string"!=typeof s)throw TypeError("encoding must be a string");if("string"==typeof s&&!o.isEncoding(s))throw TypeError("Unknown encoding: "+s);if(1===e.length){var n,i=e.charCodeAt(0);("utf8"===s&&i<128||"latin1"===s)&&(e=i)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw RangeError("Out of range index");if(r<=t)return this;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{var a=o.isBuffer(e)?e:o.from(e,s),l=a.length;
2if(0===l)throw TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=a[n%l]}return this};var E=/[^+/0-9A-Za-z-_]/g;function T(e,t){t=t||1/0;for(var r,s=e.length,n=null,i=[],a=0;a<s;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!n){if(r>56319||a+1===s){(t-=3)>-1&&i.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),n=r;continue}r=(n-55296<<10|r-56320)+65536}else n&&(t-=3)>-1&&i.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return i}function A(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}function O(e){return s.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(E,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function R(e,t,r,s){for(var n=0;n<s&&!(n+r>=t.length)&&!(n>=e.length);++n)t[n+r]=e[n];return n}function I(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var C=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var s=16*r,n=0;n<16;++n)t[s+n]=e[r]+e[n];return t}()},321:function(e,t){t.read=function(e,t,r,s,n){var i,a,o=8*n-s-1,l=(1<<o)-1,c=l>>1,u=-7,h=r?n-1:0,d=r?-1:1,f=e[t+h];for(h+=d,i=f&(1<<-u)-1,f>>=-u,u+=o;u>0;i=256*i+e[t+h],h+=d,u-=8);for(a=i&(1<<-u)-1,i>>=-u,u+=s;u>0;a=256*a+e[t+h],h+=d,u-=8);if(0===i)i=1-c;else{if(i===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,s),i-=c}return(f?-1:1)*a*Math.pow(2,i-s)},t.write=function(e,t,r,s,n,i){var a,o,l,c=8*i-n-1,u=(1<<c)-1,h=u>>1,d=5960464477539062e-23*(23===n),f=s?0:i-1,p=s?1:-1,g=+(t<0||0===t&&1/t<0);for(isNaN(t=Math.abs(t))||t===1/0?(o=+!!isNaN(t),a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+h>=1?t+=d/l:t+=d*Math.pow(2,1-h),t*l>=2&&(a++,l/=2),a+h>=u?(o=0,a=u):a+h>=1?(o=(t*l-1)*Math.pow(2,n),a+=h):(o=t*Math.pow(2,h-1)*Math.pow(2,n),a=0));n>=8;e[r+f]=255&o,f+=p,o/=256,n-=8);for(a=a<<n|o,c+=n;c>0;e[r+f]=255&a,f+=p,a/=256,c-=8);e[r+f-p]|=128*g}}},n={};function i(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}},a=!0;try{s[e](r,r.exports,i),a=!1}finally{a&&delete n[e]}return r.exports}i.ab="/ROOT/node_modules/next/dist/compiled/buffer/",t.exports=i(230)},402157,e=>{"use strict";e.s(["getCurrentUser",()=>l,"getSession",()=>c,"signIn",()=>a,"signOut",()=>o,"signUp",()=>i]);var t=e.i(333815),r=e.i(994860),s=e.i(999309),n=e.i(340974);async function i(s,i,a,o){Date.now();try{var l,c,u,h,d,f;let{validateEmail:p}=await e.A(35900),g=p(s);if(!g.isValid)return{success:!1,message:g.error||"Invalid email address. Please use a real email address."};Date.now();let y={"Content-Type":"application/json"},m=(0,n.nativePlatformHeader)();m&&(y["X-Platform"]=m);let w=await fetch((0,r.getApiUrl)("/api/auth/signup"),{method:"POST",headers:y,body:JSON.stringify({email:s.toLowerCase().trim(),password:i,turnstileToken:a,agreeToTerms:null!=(l=null==o?void 0:o.agreeToTerms)&&l,marketingOptIn:null!=(c=null==o?void 0:o.marketingOptIn)&&c,firstName:null==o||null==(u=o.firstName)?void 0:u.trim(),lastName:null==o||null==(h=o.lastName)?void 0:h.trim(),dateOfBirth:null==o?void 0:o.dateOfBirth})});Date.now();let b=await w.json();if(Date.now(),!w.ok)return{success:!1,message:b.error||"We couldn't create your account. Please try again."};if(!b.user)return{success:!1,message:"Account creation failed. Please try again."};if((null==(d=b.session)?void 0:d.access_token)&&(null==(f=b.session)?void 0:f.refresh_token))try{let{clearAuthBackoff:r,withSetSessionGuard:s}=await e.A(628400);r();let{data:n,error:i}=await s(()=>t.supabase.auth.setSession({access_token:b.session.access_token,refresh_token:b.session.refresh_token}));i?console.warn("[signUp] Error setting session:",i):n.session}catch(e){console.warn("[signUp] Error setting session:",e)}else{let{data:{session:e}}=await t.supabase.auth.getSession()}return{success:!0,message:b.message||"Account created! Redirecting you to onboarding...",user:{id:b.user.id,email:b.user.email||s},session:b.session,preauthToken:b.preauthToken,resumed:!0===b.resumed,needsEmailConfirmation:!0===b.needsEmailConfirmation}}catch(t){console.error("Sign up error:",t);let e=t instanceof Error?t.message:"An unexpected error occurred";return{success:!1,message:e.includes("Database error")?"Profile creation failed. Your account was created, but we couldn't set up your profile. Please contact support.":e||"An unexpected error occurred. Please try again."}}}async function a(e,t,s){Date.now(),s&&(s.length,s.substring(0,6),s.substring(s.length-6));try{let i;Date.now();let a=e.toLowerCase().trim(),o={"Content-Type":"application/json"},l=(0,n.nativePlatformHeader)();l&&(o["X-Platform"]=l);let c=await fetch((0,r.getApiUrl)("/api/auth/signin"),{method:"POST",headers:o,body:JSON.stringify({email:a,password:t,turnstileToken:s}),credentials:"include"});Date.now();let u=c.headers.get("content-type"),h=null==u?void 0:u.includes("application/json");try{if(h)i=await c.json();else{let e=await c.text();return console.error("[signIn] ❌ Non-JSON response received",{status:c.status,contentType:u,textPreview:e.substring(0,200),timestamp:new Date().toISOString()}),{success:!1,message:500===c.status?"Server error. Please try again later.":"Sign in failed. Please try again."}}}catch(e){return console.error("[signIn] ❌ Failed to parse response",{error:e instanceof Error?e.message:String(e),status:c.status,contentType:u,timestamp:new Date().toISOString()}),{success:!1,message:"Invalid response from server. Please try again."}}if(Date.now(),!c.ok)return console.error("[EMAIL LOGIN] [INVESTIGATION] API returned error",{status:c.status,errorMessage:null==i?void 0:i.error,errorCode:null==i?void 0:i.errorCode,details:null==i?void 0:i.details,timestamp:new Date().toISOString()}),{success:!1,message:(null==i?void 0:i.error)||(null==i?void 0:i.message)||"Invalid email or password. Please try again.",errorCode:null==i?void 0:i.errorCode,details:null==i?void 0:i.details};if(!i.user)return console.error("[signIn] No user returned from API:",{timestamp:new Date().toISOString()}),{success:!1,message:"Sign in failed. Please try again."};return{success:!0,message:i.message||"Signed in successfully.",user:{id:i.user.id,email:i.user.email||e},session:i.session,requiresStepUp:i.requiresStepUp,requiresPhone:i.requiresPhone,preauthToken:i.preauthToken,stepUpReason:i.stepUpReason}}catch(e){return console.error("[signIn] ❌ Sign in error:",{error:e,errorType:typeof e,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0,errorStringified:JSON.stringify(e,Object.getOwnPropertyNames(e)),timestamp:new Date().toISOString()}),{success:!1,message:(e instanceof Error?e.message:"string"==typeof e?e:"An unexpected error occurred")||"An unexpected error occurred. Please try again."}}}async function o(){{let{logSignOutCall:t}=await e.A(275325);t("auth.signOut","Explicit signOut call")}await t.supabase.auth.signOut({scope:"global"})}async function l(){try{let{data:{user:r},error:n}=await t.supabase.auth.getUser();if(n){if((0,s.isDefinitiveInvalidRefreshTokenError)(n)){console.warn("[getCurrentUser] Invalid refresh token detected, clearing session",{error:n.message});{let{logSignOutCall:t}=await e.A(275325);t("auth.getCurrentUser.invalidToken","Invalid refresh token in getCurrentUser")}return await t.supabase.auth.signOut(),null}{let{data:{session:e}}=await t.supabase.auth.getSession();if(null==e?void 0:e.user)return e.user;return null}}return r}catch(r){if((0,s.isDefinitiveInvalidRefreshTokenError)(r)){console.warn("[getCurrentUser] Invalid refresh token detected (catch), clearing session",{error:r.message});{let{logSignOutCall:t}=await e.A(275325);t("auth.getCurrentUser.catch.invalidToken","Invalid refresh token in getCurrentUser catch")}return await t.supabase.auth.signOut(),null}try{let{data:{session:e}}=await t.supabase.auth.getSession();if(null==e?void 0:e.user)return e.user}catch(e){}return null}}async function c(){try{let{data:{session:r},error:n}=await t.supabase.auth.getSession();if(n){if((0,s.isDefinitiveInvalidRefreshTokenError)(n)){console.warn("[getSession] Invalid refresh token detected, clearing session",{error:n.message});{let{logSignOutCall:t}=await e.A(275325);t("auth.getSession.invalidToken","Invalid refresh token in getSession")}await t.supabase.auth.signOut()}return null}return r}catch(r){if((0,s.isDefinitiveInvalidRefreshTokenError)(r)){console.warn("[getSession] Invalid refresh token detected (exception), clearing session",{error:r.message});{let{logSignOutCall:t}=await e.A(275325);
2t("auth.getSession.catch.invalidToken","Invalid refresh token in getSession catch")}await t.supabase.auth.signOut()}return null}}},333815,e=>{"use strict";e.s(["clearAuthBackoff",()=>A,"clearAuthBackoffAfterSessionRemoval",()=>T,"hasStoredRefreshToken",()=>k,"isAuthBackoffActive",()=>S,"isSetSessionInProgress",()=>b,"refreshSessionWithLock",()=>D,"sessionRestorePromise",()=>B,"supabase",()=>P,"withSetSessionGuard",()=>v],333815),e.i(529225);var t,r,s,n=e.i(972390),i=e.i(14602),a=e.i(882943),o=e.i(999309);async function l(e){return{body:await e.arrayBuffer(),headers:new Headers(e.headers),status:e.status,statusText:e.statusText}}function c(e){return new Response(e.body.byteLength>0?e.body.slice(0):null,{headers:new Headers(e.headers),status:e.status,statusText:e.statusText})}function u(e,t){return{body:new TextEncoder().encode(JSON.stringify(t)).buffer,headers:new Headers({"Content-Type":"application/json"}),status:e,statusText:400===e?"Bad Request":429===e?"Too Many Requests":"Service Unavailable"}}function h(){return u(503,{code:"request_timeout",message:"Authentication is temporarily unavailable."})}let d=(0,i.getSupabaseUrl)(),f=(0,i.getSupabaseAnonKey)(),p="growthsync-auth-429-suppress";function g(){var e;
2let t=null==(e=d.match(/https:\/\/([^.]+)\.supabase\.co/))?void 0:e[1];return t?"sb-".concat(t,"-auth-token"):null}let y=!1,m=0,w=()=>{};function b(){return m>0}function v(e){return m++,e().finally(()=>{m--})}function _(){if(y)return!0;try{let e=sessionStorage.getItem(p);if(!e)return!1;let t=parseInt(e,10);if(Date.now()-t>6e4)return sessionStorage.removeItem(p),y=!1,!1;return!0}catch{return!1}}function S(){return y||_()}function k(){try{let e=g();if(!e)return!1;let t=window.localStorage.getItem(e);if(!t)return!1;let r=JSON.parse(t);return!!(null==r?void 0:r.refresh_token)}catch{return!1}}function E(){y=!1;try{sessionStorage.removeItem(p)}catch{}}function T(){E()}function A(){E(),w()}function O(){try{sessionStorage.setItem(p,Date.now().toString())}catch{}}function R(){y||(y=!0,O(),console.warn("[Supabase Client] Rate limited on token refresh. Pausing refreshes; session kept."))}{let r,s,n=(t={fetch:window.fetch.bind(window),isTokenRequest:e=>e.startsWith("".concat(d,"/auth/v1/token")),isSuppressed:_,onInvalidToken:()=>{m>0||(!function(){if(void 0===window.Capacitor)return;let t=g();t&&e.A(840402).then(e=>{let{Preferences:r}=e;return r.remove({key:t})}).catch(()=>{})}(),N("invalid_session"))},onRateLimited:()=>{m>0||R()}},r=null,s=!1,{fetch:async function(){for(var e,n=arguments.length,i=Array(n),a=0;a<n;a++)i[a]=arguments[a];let o="string"==typeof(e=i[0])?e:e instanceof URL?e.href:e.url;if(!t.isTokenRequest(o))return t.fetch(...i);if(s)return c(h());if(t.isSuppressed())return c(u(429,{code:"over_request_rate_limit",message:"Token refresh is temporarily paused."}));let d=null!==r;if(!r){let e=(async()=>{let e;try{e=await l(await t.fetch(...i))}catch{return h()}return 400===e.status?(s=!0,t.onInvalidToken()):429===e.status&&t.onRateLimited(),e})();r=e,e.finally(()=>{r===e&&(r=null)})}let f=await r;return d&&400===f.status?c(h()):c(f)},resetInvalidTokenCircuit:()=>{s=!1}});w=n.resetInvalidTokenCircuit,window.fetch=n.fetch}let I=void 0!==window.Capacitor||(null==(s=window.Capacitor)||null==(r=s.isNativePlatform)?void 0:r.call(s))===!0,C=I?(async()=>{try{let t=(async()=>{var t;let{Preferences:r}=await Promise.race([e.A(840402),new Promise((e,t)=>setTimeout(()=>t(Error("Capacitor Preferences import timeout")),2e3))]),s=null==(t=d.match(/https:\/\/([^.]+)\.supabase\.co/))?void 0:t[1],n=s?"sb-".concat(s,"-auth-token"):null,i=0,a=Symbol("capacitor-preferences-timeout"),o=!1;if(n)try{let e=r.get({key:n}),t=await Promise.race([e,new Promise(e=>setTimeout(()=>e(a),1500))]),{value:s}=t===a?await e:t;if(!s)return;window.localStorage.setItem(n,s),i++}catch{o=!0}let l=[];try{l=Object.keys(window.localStorage).filter(e=>(e.includes("sb-")||e.includes("supabase"))&&e!==n)}catch{}for(let e of[...o&&n?[n]:[],...l])try{let{value:t}=await r.get({key:e});t&&window.localStorage.getItem(e)!==t&&(window.localStorage.setItem(e,t),e!==n&&i++)}catch{}})();await Promise.race([t,new Promise((e,t)=>setTimeout(()=>t(Error("Capacitor Preferences restore timeout")),2500))]).catch(e=>{console.warn("[Supabase Client] Capacitor Preferences restore timeout or error (non-fatal):",e)})}catch(e){console.warn("[Supabase Client] Error loading tokens from Capacitor Preferences:",e)}})():Promise.resolve(),P=(0,n.createBrowserClient)(d,f,{auth:{storage:(()=>{if(I){let t=g();return{getItem:e=>{try{if(t&&e===t){let t=window.localStorage.getItem(e);if(t)try{let e=JSON.parse(t);if(!(null==e?void 0:e.refresh_token))return null}catch{return null}}return window.localStorage.getItem(e)}catch(e){return console.warn("[Supabase Storage] Error reading from localStorage:",e),null}},setItem:(t,r)=>{try{window.localStorage.setItem(t,r)}catch(e){console.warn("[Supabase Storage] Error writing to localStorage:",e)}Promise.resolve().then(async()=>{try{let{Preferences:s}=await e.A(840402);await s.set({key:t,value:r})}catch{setTimeout(async()=>{try{let{Preferences:s}=await e.A(840402);await s.set({key:t,value:r})}catch(e){console.error("[Supabase Storage] Failed to persist token after retry:",e)}},500)}})},removeItem:t=>{try{window.localStorage.removeItem(t)}catch(e){console.warn("[Supabase Storage] Error removing from localStorage:",e)}(async()=>{try{let{Preferences:r}=await e.A(840402);await r.remove({key:t})}catch(e){console.warn("[Supabase Storage] Error removing from Capacitor Preferences:",e)}})()}}}let t=g();return{getItem:e=>{try{if(t&&e===t){let t=window.localStorage.getItem(e);if(t)try{let e=JSON.parse(t);if(!(null==e?void 0:e.refresh_token))return null}catch{return null}}return window.localStorage.getItem(e)}catch(e){return console.warn("[Supabase Storage] Error reading from localStorage:",e),null}},setItem:(e,t)=>
2{try{window.localStorage.setItem(e,t)}catch(e){console.warn("[Supabase Storage] Error writing to localStorage:",e)}},removeItem:e=>{try{window.localStorage.removeItem(e)}catch(e){console.warn("[Supabase Storage] Error removing from localStorage:",e)}}}})(),autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!1}}),j=[400,1e3],x=null;async function U(){let e=0;for(let t=0;t<3;t++){let t=await P.auth.refreshSession(),r=t.error;if(!r)return t;if((0,o.isDefinitiveInvalidRefreshTokenError)(r))return N("invalid_session"),t;if((0,o.isBadRequestError)(r))return console.warn("[Auth Refresh] Bad request (400) - clearing session, no retry"),N("invalid_session"),t;if((0,o.isRefreshRateLimitError)(r))return console.warn("[Auth Refresh] Rate limited (429) - pausing refreshes, session kept"),R(),t;if((0,o.isTransientRefreshError)(r)&&e<j.length){let t=j[e];console.warn("[Auth Refresh] Transient refresh failure, retrying",{attempt:e+=1,retryDelayMs:t}),await function(e){return new Promise(t=>setTimeout(t,e))}(t);continue}return t}return P.auth.refreshSession()}function N(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid_session";if(!(m>0)){if("invalid_session"===e)E();else{if(y)return;y=!0,O()}let t=g();if(t)try{window.localStorage.removeItem(t)}catch{}try{let e=a.useAuthStore.getState();(e.isAuthenticated||e.user)&&a.useAuthStore.setState({user:null,isAuthenticated:!1,membershipTier:"free"})}catch{}try{P.auth.stopAutoRefresh(),P.auth.signOut({scope:"local"})}catch{}}}async function D(){return x||(!function(){if(_())return!1;try{let e=g();if(!e)return!1;let t=window.localStorage.getItem(e);if(!t)return!1;let r=JSON.parse(t);return!!(null==r?void 0:r.refresh_token)}catch{return!1}}()?{data:{user:null,session:null},error:{message:"No refresh token",name:"AuthSessionMissing",status:0}}:x=U().finally(()=>{x=null}))}let B=(async()=>{try{var t;let{isIntentionalLogout:r,clearIntentionalLogoutFlag:s}=await e.A(571383);if(r())return void s();if(I&&(await C,await new Promise(e=>setTimeout(e,100))),!k()){try{P.auth.stopAutoRefresh()}catch{}return}null==(t=d.match(/https:\/\/([^.]+)\.supabase\.co/))||t[1];let{data:{session:n},error:i}=await P.auth.getSession();if(n&&n.refresh_token){let e=n.expires_at?1e3*n.expires_at:null,t=Date.now();if(e&&e<t)try{let{data:{session:e},error:t}=await D();e&&!t?await a.useAuthStore.getState().syncSession().catch(()=>{}):t&&((0,o.isDefinitiveInvalidRefreshTokenError)(t)?await a.useAuthStore.getState().clearClientAuthSession().catch(()=>{}):await a.useAuthStore.getState().syncSession().catch(()=>{}))}catch{await a.useAuthStore.getState().syncSession().catch(()=>{})}else((null==n?void 0:n.access_token)||!(null==n?void 0:n.access_token))&&await a.useAuthStore.getState().syncSession().catch(()=>{})}else(null==n?void 0:n.access_token)&&await a.useAuthStore.getState().syncSession().catch(()=>{})}catch(e){console.warn("[Auth Boot] Error during boot sequence:",e)}})();if(!window.__growthsyncAuthListenerInitialized){window.__growthsyncAuthListenerInitialized=!0;let e=!0,t=0,r=0,s=0;P.auth.onAuthStateChange((n,i)=>{if("SIGNED_IN"===n){A();try{P.auth.startAutoRefresh()}catch{}if(!e||!a.useAuthStore.getState().isAuthenticated){let e=Date.now();e-t>3e3&&(t=e,a.useAuthStore.getState().syncSession().catch(()=>{}))}}else if("SIGNED_OUT"===n){if(y||m>0)return void s++;let e=Date.now();if(e-r<2e3&&r>0)return void s++;s=0,r=e,N("invalid_session")}else if("TOKEN_REFRESHED"===n){let e=Date.now();e-t>3e3&&(t=e,a.useAuthStore.getState().syncSession().catch(()=>{}))}e&&(e=!1)})}},882943,e=>{"use strict";e.s(["useAuthStore",()=>f]);var t,r,s=e.i(247167),n=e.i(768834),i=e.i(579473),a=e.i(103053),o=e.i(402157),l=e.i(999309),c=e.i(333815),u=e.i(994860);let h=null;async function d(){try{let{getApiUrl:t}=await e.A(454413);await fetch(t("/api/auth/logout"),{method:"POST",credentials:"include"})}catch{}try{await (0,o.signOut)()}catch{}try{let{clearAuthCookiesClient:r}=await e.A(571383),s=["growthsync-add-phone-dismissed-until","growthsync-add-phone-dismissed-permanently"],n=[];for(let e=0;e<window.localStorage.length;e++){let t=window.localStorage.key(e);t&&(t.startsWith("growthsync-")||t.startsWith("auth-")||t.startsWith("profile-")||t.includes("supabase")||t.includes("sb-")||t.includes("auth-token"))&&!s.includes(t)&&n.push(t)}
2n.forEach(e=>{try{window.localStorage.removeItem(e)}catch{}});try{window.sessionStorage.clear()}catch{}r();try{if(void 0!==window.Capacitor){var t;let{Preferences:r}=await e.A(840402),s=null==(t="https://fxvxmogknymkvijkubnl.supabase.co".match(/https:\/\/([^.]+)\.supabase\.co/))?void 0:t[1],n=s?"sb-".concat(s,"-auth-token"):null;n&&await r.remove({key:n})}}catch{}}catch{}}let f=(0,n.create)()((0,i.persist)((t,r)=>({user:null,isAuthenticated:!1,membershipTier:"free",_hasHydrated:!1,login:e=>t({user:e,isAuthenticated:!0,membershipTier:e.membershipTier||"free"}),clearClientAuthSession:async()=>{h=null,(0,c.clearAuthBackoffAfterSessionRemoval)(),t({user:null,isAuthenticated:!1,membershipTier:"free"});try{let{useProfileStore:t}=await e.A(281845),r=t.getState();r.setCurrentProfile&&r.setCurrentProfile(null),t.setState({loading:!1,error:null})}catch(e){console.warn("[Auth Store] Error clearing profile on clearClientAuthSession:",e)}try{let{clearProfileMemoryCache:t}=await e.A(80236);t()}catch{}await d()},logout:async()=>{{let{setIntentionalLogoutFlag:t}=await e.A(571383);t()}await r().clearClientAuthSession(),window.location.replace("/auth/login")},updateMembershipTier:e=>t(t=>({...t.user?{user:{...t.user,membershipTier:e,updatedAt:new Date().toISOString()}}:{},membershipTier:e})),refreshMembership:async()=>{try{let t=await fetch((0,u.getApiUrl)("/api/refresh-membership"),{method:"GET",headers:{"Content-Type":"application/json"},credentials:"include"});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error||"Failed to refresh membership")}let s=await t.json();if(s.success&&s.membershipTier){let t=s.membershipTier;r().updateMembershipTier(t);let{useProfileStore:n}=await e.A(281845),i=n.getState();return i.currentProfile&&await i.updateCurrentProfile({membershipTier:t}),t}return null}catch(e){throw console.error("Error refreshing membership:",e),e}},resolveMembershipOnLogin:async t=>{let s=r().membershipTier;try{let{authFetch:n}=await e.A(753625);(null==t?void 0:t.forceSync)&&await n("/api/billing/sync",{method:"POST",credentials:"include"}).catch(()=>null);let i=await n("/api/me/entitlements",{credentials:"include"});if(!i.ok)return s;let a=await i.json(),o=(null==a?void 0:a.plan_tier)||s||"free";return o!==s&&r().updateMembershipTier(o),o}catch(e){return s}},syncSession:async()=>{if((0,c.isAuthBackoffActive)())return;try{let{isIntentionalLogout:t}=await e.A(571383);if(t())return}catch{}let s=Date.now();if(h&&s-h.timestamp<8e3)return h.promise;let n=(async()=>{var s,n,i,a,u;let{logDiagnostic:h,detectEnvironment:d}=await e.A(202547),f=d();h("syncSession","Starting session sync",{isMobile:f.isMobile,isIOS:f.isIOS,isTestFlight:f.isTestFlight});let p=r();if(p.user&&p.isAuthenticated){h("syncSession","User already authenticated, performing sync check",{userId:p.user.id,userEmail:p.user.email});try{let r=await Promise.race([(0,o.getSession)(),new Promise((e,t)=>setTimeout(()=>t(Error("Timeout")),2e3))]).catch(()=>null);if(null==r?void 0:r.access_token)return;if(!(0,c.hasStoredRefreshToken)()){h("syncSession","AUTH DESYNC: No Supabase session and no token - clearing stale auth",{hadUserId:null==(s=p.user)?void 0:s.id}),console.warn("[syncSession] AUTH DESYNC: No Supabase session and no refresh token. Clearing stale auth state.",{userId:null==(n=p.user)?void 0:n.id}),t({user:null,isAuthenticated:!1,membershipTier:"free"});try{let{useProfileStore:t}=await e.A(281845);t.setState({currentProfile:null})}catch{}}return}catch(r){if(h("syncSession","Error during session validation",{error:r instanceof Error?r.message:String(r)}),(0,l.isDefinitiveInvalidRefreshTokenError)(r)){h("syncSession","Invalid refresh token detected, clearing auth state"),console.warn("[syncSession] Invalid refresh token detected, clearing auth state");try{{let{logSignOutCall:t}=await e.A(275325);t("AuthStore.syncSession.invalidToken","Invalid refresh token during sync")}await (0,o.signOut)()}catch(e){}t({user:null,isAuthenticated:!1,membershipTier:"free"})}return}}try{if(!(0,c.hasStoredRefreshToken)())return;h("syncSession","Performing full session sync",{hasExistingAuth:!!(p.user&&p.isAuthenticated),isMobile:f.isMobile});let s=f.isMobile?8e3:5e3,n=await Promise.race([(0,o.getSession)(),new Promise((e,t)=>
2setTimeout(()=>t(Error("Timeout")),s))]).catch(()=>null);h("syncSession","Session retrieved",{hasSession:!!n,hasAccessToken:!!(null==n?void 0:n.access_token),userId:null==n||null==(i=n.user)?void 0:i.id});let l=null;if((null==n?void 0:n.access_token)&&(l=await Promise.race([(0,o.getCurrentUser)(),new Promise((e,t)=>setTimeout(()=>t(Error("Timeout")),s))]).catch(e=>(null==n?void 0:n.user)||null)),h("syncSession","User retrieved",{hasUser:!!l,userId:null==l?void 0:l.id,userEmail:null==l?void 0:l.email}),!n&&!l){if(p.user&&p.isAuthenticated&&!(0,c.hasStoredRefreshToken)()){h("syncSession","AUTH DESYNC: No Supabase session and no token - clearing stale auth",{hadUserId:null==(a=p.user)?void 0:a.id}),console.warn("[syncSession] AUTH DESYNC: No Supabase session and no refresh token. Clearing stale auth state.",{userId:null==(u=p.user)?void 0:u.id}),t({user:null,isAuthenticated:!1,membershipTier:"free"});try{let{useProfileStore:t}=await e.A(281845);t.setState({currentProfile:null})}catch{}}return}if(n&&l){if(p.user&&p.user.id!==l.id)return void console.warn("Session sync found different user (".concat(l.id,") but current user is ").concat(p.user.id,". Preserving current user."));try{let{authFetch:s}=await e.A(753625),n=await s("/api/profiles/".concat(l.id),{credentials:"include"});if(n.ok){let s=await n.json();if(s.userId!==l.id&&s.id!==l.id){console.warn("Profile userId (".concat(s.userId,") doesn't match Supabase user (").concat(l.id,"). Skipping profile update.")),t({user:{id:l.id,email:l.email||"",profileId:l.id,membershipTier:"free",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},isAuthenticated:!0});return}let i="admin"===s.accountType||"admin"===s.user_role,a=i?"elite":s.membershipTier||"free";t({user:{id:l.id,email:l.email||"",profileId:s.id||l.id,membershipTier:a,createdAt:s.createdAt||new Date().toISOString(),updatedAt:s.updatedAt||new Date().toISOString()},isAuthenticated:!0,membershipTier:a});try{await r().resolveMembershipOnLogin({forceSync:"free"===a})}catch{}h("syncSession","Session sync completed successfully",{userId:l.id,email:l.email,membershipTier:a,profileAccountType:s.accountType,profileUserRole:s.user_role,isAdmin:i,effectiveMembershipTier:a});try{let{authFetch:s}=await e.A(753625),n=await s("/api/me/entitlements",{credentials:"include"});if(n.ok){let e=await n.json();e.plan_tier&&e.plan_tier!==a&&t({membershipTier:e.plan_tier,...r().user?{user:{...r().user,membershipTier:e.plan_tier}}:{}})}}catch{}try{let{useProfileStore:t}=await e.A(281845);await t.getState().fetchCurrentProfile(l.id)}catch{}}else console.warn("[Auth Store] User authenticated but profile not found. Profile should be created during signup."),t({user:{id:l.id,email:l.email||"",profileId:l.id,membershipTier:p.membershipTier||"free",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},isAuthenticated:!0,membershipTier:p.membershipTier||"free"}),setTimeout(async()=>{try{let{authFetch:r}=await e.A(753625),s=await r("/api/profiles/".concat(l.id),{credentials:"include"});if(s.ok){let r=await s.json(),n=r.membershipTier||"free";t({user:{id:l.id,email:l.email||"",profileId:r.id||l.id,membershipTier:n,createdAt:r.createdAt||new Date().toISOString(),updatedAt:r.updatedAt||new Date().toISOString()},membershipTier:n});let{useProfileStore:i}=await e.A(281845);await i.getState().fetchCurrentProfile(l.id)}}catch(e){console.warn("Profile retry fetch failed:",e)}},2e3)}catch(e){console.error("Failed to fetch profile during session sync (non-fatal):",e),t({user:{id:l.id,email:l.email||"",profileId:l.id,membershipTier:p.membershipTier||"free",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},isAuthenticated:!0,membershipTier:p.membershipTier||"free"})}}}catch(r){if(console.error("Error syncing session:",r),(0,l.isDefinitiveInvalidRefreshTokenError)(r)){console.warn("Invalid refresh token detected, clearing auth state");try{{let{logSignOutCall:t}=await e.A(275325);t("AuthStore.syncSession.catch.invalidToken","Invalid refresh token in catch block")}await (0,o.signOut)()}catch(e){}t({user:null,isAuthenticated:!1,membershipTier:"free"})}}})();return h={promise:n,timestamp:s},n.finally(()=>{setTimeout(()=>{(null==h?void 0:h.promise)===n&&(h=null)},500)}),n}}),{name:"growthsync-auth",storage:(0,a.createPersistStorage)(),version:1,partialize:e=>({user:e.user,isAuthenticated:e.isAuthenticated,membershipTier:e.membershipTier}),migrate:(e,t)=>
21!==t?{user:null,isAuthenticated:!1,membershipTier:"free"}:e,onRehydrateStorage:()=>(e,t)=>{if(f.setState({_hasHydrated:!0}),e){let e=s.default.env.NEXT_PUBLIC_APP_VERSION||"0.1.0",t=window.localStorage.getItem("growthsync-build-version");window.localStorage.setItem("growthsync-build-version",e)}}}));{let e=/Safari/i.test(navigator.userAgent)&&!/Chrome/i.test(navigator.userAgent),s=/Android/i.test(navigator.userAgent)&&(null==(r=window.Capacitor)||null==(t=r.getPlatform)?void 0:t.call(r))==="android";setTimeout(()=>{f.getState()._hasHydrated||f.setState({_hasHydrated:!0})},e||s?450:150)}}]);
3
4//# debugId=c533d350-387c-ec81-4448-761cc60e773d

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.