diff options
author | Baitinq <manuelpalenzuelamerino@gmail.com> | 2024-06-06 20:30:29 +0200 |
---|---|---|
committer | Baitinq <manuelpalenzuelamerino@gmail.com> | 2024-06-06 20:30:29 +0200 |
commit | d7223386c96c2bdbc8af385c1e014334fd352c46 (patch) | |
tree | b734ff88e72f48a5fe56f484da8fb05bc7f4dd66 | |
parent | Updates (diff) | |
download | fs-tracer-frontend-d7223386c96c2bdbc8af385c1e014334fd352c46.tar.gz fs-tracer-frontend-d7223386c96c2bdbc8af385c1e014334fd352c46.tar.bz2 fs-tracer-frontend-d7223386c96c2bdbc8af385c1e014334fd352c46.zip |
Updates
-rw-r--r-- | assets/browser-DG571wtW.js (renamed from assets/browser-PEqAXY5b.js) | 2 | ||||
-rw-r--r-- | assets/index-ClZtce0o.js (renamed from assets/index-BsekK5hw.js) | 2 | ||||
-rw-r--r-- | index.html | 6 |
3 files changed, 5 insertions, 5 deletions
diff --git a/assets/browser-PEqAXY5b.js b/assets/browser-DG571wtW.js index d639e14..3b22981 100644 --- a/assets/browser-PEqAXY5b.js +++ b/assets/browser-DG571wtW.js @@ -1 +1 @@ -import{g as a}from"./index-BsekK5hw.js";function f(t,s){for(var o=0;o<s.length;o++){const e=s[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const n=Object.getOwnPropertyDescriptor(e,r);n&&Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var c=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")};const i=a(c),u=f({__proto__:null,default:i},[c]);export{u as b}; +import{g as a}from"./index-ClZtce0o.js";function f(t,s){for(var o=0;o<s.length;o++){const e=s[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const n=Object.getOwnPropertyDescriptor(e,r);n&&Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var c=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")};const i=a(c),u=f({__proto__:null,default:i},[c]);export{u as b}; diff --git a/assets/index-BsekK5hw.js b/assets/index-ClZtce0o.js index dad64aa..907a159 100644 --- a/assets/index-BsekK5hw.js +++ b/assets/index-ClZtce0o.js @@ -64,4 +64,4 @@ Error generating stack: `+s.message+` * LICENSE.md file in the root directory of this source tree. * * @license MIT - */const Im="6";try{window.__reactRouterVersion=Im}catch{}const $m="startTransition",au=jh[$m];function Nm(e){let{basename:t,children:n,future:r,window:i}=e,s=x.useRef();s.current==null&&(s.current=Vp({window:i,v5Compat:!0}));let o=s.current,[l,a]=x.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},c=x.useCallback(d=>{u&&au?au(()=>a(d)):a(d)},[a,u]);return x.useLayoutEffect(()=>o.listen(c),[o,c]),x.createElement(jm,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var uu;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(uu||(uu={}));var cu;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(cu||(cu={}));const Am="modulepreload",Um=function(e){return"/"+e},du={},Rn=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),o=(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"));i=Promise.all(n.map(l=>{if(l=Um(l),l in du)return;du[l]=!0;const a=l.endsWith(".css"),u=a?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const c=document.createElement("link");if(c.rel=a?"stylesheet":Am,a||(c.as="script",c.crossOrigin=""),c.href=l,o&&c.setAttribute("nonce",o),document.head.appendChild(c),a)return new Promise((d,f)=>{c.addEventListener("load",d),c.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${l}`)))})}))}return i.then(()=>t()).catch(s=>{const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=s,window.dispatchEvent(o),!o.defaultPrevented)throw s})},Dm=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class Bl extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class zm extends Bl{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class Fm extends Bl{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Mm extends Bl{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var bo;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(bo||(bo={}));var bm=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Bm{constructor(t,{headers:n={},customFetch:r,region:i=bo.Any}={}){this.url=t,this.headers=n,this.region=i,this.fetch=Dm(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return bm(this,void 0,void 0,function*(){try{const{headers:i,method:s,body:o}=n;let l={},{region:a}=n;a||(a=this.region),a&&a!=="any"&&(l["x-region"]=a);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(l["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(l["Content-Type"]="application/json",u=JSON.stringify(o)));const c=yield this.fetch(`${this.url}/${t}`,{method:s||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:u}).catch(g=>{throw new zm(g)}),d=c.headers.get("x-relay-error");if(d&&d==="true")throw new Fm(c);if(!c.ok)throw new Mm(c);let f=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),v;return f==="application/json"?v=yield c.json():f==="application/octet-stream"?v=yield c.blob():f==="text/event-stream"?v=c:f==="multipart/form-data"?v=yield c.formData():v=yield c.text(),{data:v,error:null}}catch(i){return{data:null,error:i}}})}}var Vm=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},jn=Vm();const Hm=jn.fetch,Vl=jn.fetch.bind(jn),eh=jn.Headers,Wm=jn.Request,Km=jn.Response,Ur=Object.freeze(Object.defineProperty({__proto__:null,Headers:eh,Request:Wm,Response:Km,default:Vl,fetch:Hm},Symbol.toStringTag,{value:"Module"}));class Qm extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}class Gm{constructor(t){this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=t.headers,this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=t.shouldThrowOnError,this.signal=t.signal,this.isMaybeSingle=t.isMaybeSingle,t.fetch?this.fetch=t.fetch:typeof fetch>"u"?this.fetch=Vl:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{var o,l,a;let u=null,c=null,d=null,f=s.status,v=s.statusText;if(s.ok){if(this.method!=="HEAD"){const p=await s.text();p===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=p:c=JSON.parse(p))}const y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(l=s.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");y&&_&&_.length>1&&(d=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(u={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,d=null,f=406,v="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{const y=await s.text();try{u=JSON.parse(y),Array.isArray(u)&&s.status===404&&(c=[],u=null,f=200,v="OK")}catch{s.status===404&&y===""?(f=204,v="No Content"):u={message:y}}if(u&&this.isMaybeSingle&&(!((a=u==null?void 0:u.details)===null||a===void 0)&&a.includes("0 rows"))&&(u=null,f=200,v="OK"),u&&this.shouldThrowOnError)throw new Qm(u)}return{error:u,data:c,count:d,status:f,statusText:v}});return this.shouldThrowOnError||(i=i.catch(s=>{var o,l,a;return{error:{message:`${(o=s==null?void 0:s.name)!==null&&o!==void 0?o:"FetchError"}: ${s==null?void 0:s.message}`,details:`${(l=s==null?void 0:s.stack)!==null&&l!==void 0?l:""}`,hint:"",code:`${(a=s==null?void 0:s.code)!==null&&a!==void 0?a:""}`},data:null,count:null,status:0,statusText:""}})),i.then(t,n)}}class Jm extends Gm{select(t){let n=!1;const r=(t??"*").split("").map(i=>/\s/.test(i)&&!n?"":(i==='"'&&(n=!n),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:n=!0,nullsFirst:r,foreignTable:i,referencedTable:s=i}={}){const o=s?`${s}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${t}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:n,referencedTable:r=n}={}){const i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,n,{foreignTable:r,referencedTable:i=r}={}){const s=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(o,`${n-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:n=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:o="text"}={}){var l;const a=[t?"analyze":null,n?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),u=(l=this.headers.Accept)!==null&&l!==void 0?l:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${a};`,o==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class tn extends Jm{eq(t,n){return this.url.searchParams.append(t,`eq.${n}`),this}neq(t,n){return this.url.searchParams.append(t,`neq.${n}`),this}gt(t,n){return this.url.searchParams.append(t,`gt.${n}`),this}gte(t,n){return this.url.searchParams.append(t,`gte.${n}`),this}lt(t,n){return this.url.searchParams.append(t,`lt.${n}`),this}lte(t,n){return this.url.searchParams.append(t,`lte.${n}`),this}like(t,n){return this.url.searchParams.append(t,`like.${n}`),this}likeAllOf(t,n){return this.url.searchParams.append(t,`like(all).{${n.join(",")}}`),this}likeAnyOf(t,n){return this.url.searchParams.append(t,`like(any).{${n.join(",")}}`),this}ilike(t,n){return this.url.searchParams.append(t,`ilike.${n}`),this}ilikeAllOf(t,n){return this.url.searchParams.append(t,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(t,n){return this.url.searchParams.append(t,`ilike(any).{${n.join(",")}}`),this}is(t,n){return this.url.searchParams.append(t,`is.${n}`),this}in(t,n){const r=Array.from(new Set(n)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}contains(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cs.{${n.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(n)}`),this}containedBy(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cd.{${n.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(n)}`),this}rangeGt(t,n){return this.url.searchParams.append(t,`sr.${n}`),this}rangeGte(t,n){return this.url.searchParams.append(t,`nxl.${n}`),this}rangeLt(t,n){return this.url.searchParams.append(t,`sl.${n}`),this}rangeLte(t,n){return this.url.searchParams.append(t,`nxr.${n}`),this}rangeAdjacent(t,n){return this.url.searchParams.append(t,`adj.${n}`),this}overlaps(t,n){return typeof n=="string"?this.url.searchParams.append(t,`ov.${n}`):this.url.searchParams.append(t,`ov.{${n.join(",")}}`),this}textSearch(t,n,{config:r,type:i}={}){let s="";i==="plain"?s="pl":i==="phrase"?s="ph":i==="websearch"&&(s="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${o}.${n}`),this}match(t){return Object.entries(t).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(t,n,r){return this.url.searchParams.append(t,`not.${n}.${r}`),this}or(t,{foreignTable:n,referencedTable:r=n}={}){const i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,n,r){return this.url.searchParams.append(t,`${n}.${r}`),this}}class qm{constructor(t,{headers:n={},schema:r,fetch:i}){this.url=t,this.headers=n,this.schema=r,this.fetch=i}select(t,{head:n=!1,count:r}={}){const i=n?"HEAD":"GET";let s=!1;const o=(t??"*").split("").map(l=>/\s/.test(l)&&!s?"":(l==='"'&&(s=!s),l)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new tn({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:n,defaultToNull:r=!0}={}){const i="POST",s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),n&&s.push(`count=${n}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(t)){const o=t.reduce((l,a)=>l.concat(Object.keys(a)),[]);if(o.length>0){const l=[...new Set(o)].map(a=>`"${a}"`);this.url.searchParams.set("columns",l.join(","))}}return new tn({method:i,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){const o="POST",l=[`resolution=${r?"ignore":"merge"}-duplicates`];if(n!==void 0&&this.url.searchParams.set("on_conflict",n),this.headers.Prefer&&l.push(this.headers.Prefer),i&&l.push(`count=${i}`),s||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(t)){const a=t.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(a.length>0){const u=[...new Set(a)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new tn({method:o,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:n}={}){const r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),n&&i.push(`count=${n}`),this.headers.Prefer=i.join(","),new tn({method:r,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const n="DELETE",r=[];return t&&r.push(`count=${t}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new tn({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const Ym="1.15.2",Xm={"X-Client-Info":`postgrest-js/${Ym}`};class Hl{constructor(t,{headers:n={},schema:r,fetch:i}={}){this.url=t,this.headers=Object.assign(Object.assign({},Xm),n),this.schemaName=r,this.fetch=i}from(t){const n=new URL(`${this.url}/${t}`);return new qm(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new Hl(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,n={},{head:r=!1,get:i=!1,count:s}={}){let o;const l=new URL(`${this.url}/rpc/${t}`);let a;r||i?(o=r?"HEAD":"GET",Object.entries(n).filter(([c,d])=>d!==void 0).map(([c,d])=>[c,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([c,d])=>{l.searchParams.append(c,d)})):(o="POST",a=n);const u=Object.assign({},this.headers);return s&&(u.Prefer=`count=${s}`),new tn({method:o,url:l,headers:u,schema:this.schemaName,body:a,fetch:this.fetch,allowEmpty:!1})}}const Zm="2.9.5",ev={"X-Client-Info":`realtime-js/${Zm}`},tv="1.0.0",th=1e4,nv=1e3;var kn;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(kn||(kn={}));var _e;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(_e||(_e={}));var Fe;(function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"})(Fe||(Fe={}));var Bo;(function(e){e.websocket="websocket"})(Bo||(Bo={}));var Ut;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(Ut||(Ut={}));class nh{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class rv{constructor(){this.HEADER_LENGTH=1}decode(t,n){return t.constructor===ArrayBuffer?n(this._binaryDecode(t)):n(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const n=new DataView(t),r=new TextDecoder;return this._decodeBroadcast(t,n,r)}_decodeBroadcast(t,n,r){const i=n.getUint8(1),s=n.getUint8(2);let o=this.HEADER_LENGTH+2;const l=r.decode(t.slice(o,o+i));o=o+i;const a=r.decode(t.slice(o,o+s));o=o+s;const u=JSON.parse(r.decode(t.slice(o,t.byteLength)));return{ref:null,topic:l,event:a,payload:u}}}class Fs{constructor(t,n,r={},i=th){this.channel=t,this.event=n,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,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(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var hu;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(hu||(hu={}));class ur{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ur.syncState(this.state,i,s,o),this.pendingDiffs.forEach(a=>{this.state=ur.syncDiff(this.state,a,s,o)}),this.pendingDiffs=[],l()}),this.channel._on(r.diff,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=ur.syncDiff(this.state,i,s,o),l())}),this.onJoin((i,s,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:s,newPresences:o})}),this.onLeave((i,s,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:s,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,i){const s=this.cloneDeep(t),o=this.transformState(n),l={},a={};return this.map(s,(u,c)=>{o[u]||(a[u]=c)}),this.map(o,(u,c)=>{const d=s[u];if(d){const f=c.map(_=>_.presence_ref),v=d.map(_=>_.presence_ref),g=c.filter(_=>v.indexOf(_.presence_ref)<0),y=d.filter(_=>f.indexOf(_.presence_ref)<0);g.length>0&&(l[u]=g),y.length>0&&(a[u]=y)}else l[u]=c}),this.syncDiff(s,{joins:l,leaves:a},r,i)}static syncDiff(t,n,r,i){const{joins:s,leaves:o}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(s,(l,a)=>{var u;const c=(u=t[l])!==null&&u!==void 0?u:[];if(t[l]=this.cloneDeep(a),c.length>0){const d=t[l].map(v=>v.presence_ref),f=c.filter(v=>d.indexOf(v.presence_ref)<0);t[l].unshift(...f)}r(l,c,a)}),this.map(o,(l,a)=>{let u=t[l];if(!u)return;const c=a.map(d=>d.presence_ref);u=u.filter(d=>c.indexOf(d.presence_ref)<0),t[l]=u,i(l,u,a),u.length===0&&delete t[l]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const i=t[r];return"metas"in i?n[r]=i.metas.map(s=>(s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s)):n[r]=i,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var z;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(z||(z={}));const fu=(e,t,n={})=>{var r;const i=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((s,o)=>(s[o]=iv(o,e,t,i),s),{})},iv=(e,t,n,r)=>{const i=t.find(l=>l.name===e),s=i==null?void 0:i.type,o=n[e];return s&&!r.includes(s)?rh(s,o):Vo(o)},rh=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return av(t,n)}switch(e){case z.bool:return sv(t);case z.float4:case z.float8:case z.int2:case z.int4:case z.int8:case z.numeric:case z.oid:return ov(t);case z.json:case z.jsonb:return lv(t);case z.timestamp:return uv(t);case z.abstime:case z.date:case z.daterange:case z.int4range:case z.int8range:case z.money:case z.reltime:case z.text:case z.time:case z.timestamptz:case z.timetz:case z.tsrange:case z.tstzrange:return Vo(t);default:return Vo(t)}},Vo=e=>e,sv=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ov=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},lv=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},av=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let s;const o=e.slice(1,n);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(l=>rh(t,l))}return e},uv=e=>typeof e=="string"?e.replace(" ","T"):e;var pu;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(pu||(pu={}));var mu;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes"})(mu||(mu={}));var vu;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(vu||(vu={}));class Wl{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=_e.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},n.config),this.timeout=this.socket.timeout,this.joinPush=new Fs(this,Fe.join,this.params,this.timeout),this.rejoinTimer=new nh(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=_e.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=_e.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=_e.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=_e.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Fe.reply,{},(i,s)=>{this._trigger(this._replyEventName(s),i)}),this.presence=new ur(this),this.broadcastEndpointURL=this._broadcastEndpointURL()}subscribe(t,n=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:s,presence:o}}=this.params;this._onError(u=>t&&t("CHANNEL_ERROR",u)),this._onClose(()=>t&&t("CLOSED"));const l={},a={broadcast:s,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&i!==void 0?i:[]};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:a},l)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",({postgres_changes:u})=>{var c;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){t&&t("SUBSCRIBED");return}else{const d=this.bindings.postgres_changes,f=(c=d==null?void 0:d.length)!==null&&c!==void 0?c:0,v=[];for(let g=0;g<f;g++){const y=d[g],{filter:{event:_,schema:p,table:h,filter:m}}=y,w=u&&u[g];if(w&&w.event===_&&w.schema===p&&w.table===h&&w.filter===m)v.push(Object.assign(Object.assign({},y),{id:w.id}));else{this.unsubscribe(),t&&t("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,t&&t("SUBSCRIBED");return}}).receive("error",u=>{t&&t("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t&&t("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this._on(t,n,r)}async send(t,n={}){var r,i;if(!this._canPush()&&t.type==="broadcast"){const{event:s,payload:o}=t,l={method:"POST",headers:{apikey:(r=this.socket.apiKey)!==null&&r!==void 0?r:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o}]})};try{return(await this._fetchWithTimeout(this.broadcastEndpointURL,l,(i=n.timeout)!==null&&i!==void 0?i:this.timeout)).ok?"ok":"error"}catch(a){return a.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,l,a;const u=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((a=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||a===void 0)&&a.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=_e.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Fe.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const i=new Fs(this,Fe.leave,{},t);i.receive("ok",()=>{n(),r("ok")}).receive("timeout",()=>{n(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}_broadcastEndpointURL(){let t=this.socket.endPoint;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")+"/api/broadcast"}async _fetchWithTimeout(t,n,r){const i=new AbortController,s=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:i.signal}));return clearTimeout(s),o}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Fs(this,t,n,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var i,s;const o=t.toLocaleLowerCase(),{close:l,error:a,leave:u,join:c}=Fe;if(r&&[l,a,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,n,r);if(n&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(v=>{var g,y,_;return((g=v.filter)===null||g===void 0?void 0:g.event)==="*"||((_=(y=v.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(v=>v.callback(f,r)):(s=this.bindings[o])===null||s===void 0||s.filter(v=>{var g,y,_,p,h,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in v){const w=v.id,S=(g=v.filter)===null||g===void 0?void 0:g.event;return w&&((y=n.ids)===null||y===void 0?void 0:y.includes(w))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((_=n.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const w=(h=(p=v==null?void 0:v.filter)===null||p===void 0?void 0:p.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return w==="*"||w===((m=n==null?void 0:n.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return v.type.toLocaleLowerCase()===o}).map(v=>{if(typeof f=="object"&&"ids"in f){const g=f.data,{schema:y,table:_,commit_timestamp:p,type:h,errors:m}=g;f=Object.assign(Object.assign({},{schema:y,table:_,commit_timestamp:p,eventType:h,new:{},old:{},errors:m}),this._getPayloadRecords(g))}v.callback(f,r)})}_isClosed(){return this.state===_e.closed}_isJoined(){return this.state===_e.joined}_isJoining(){return this.state===_e.joining}_isLeaving(){return this.state===_e.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const i=t.toLocaleLowerCase(),s={type:i,filter:n,callback:r};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var s;return!(((s=i.type)===null||s===void 0?void 0:s.toLocaleLowerCase())===r&&Wl.isEqual(i.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(Fe.close,{},t)}_onError(t){this._on(Fe.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=_e.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=fu(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=fu(t.columns,t.old_record)),n}}const cv=()=>{},dv=typeof WebSocket<"u";class hv{constructor(t,n){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.headers=ev,this.params={},this.timeout=th,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=cv,this.conn=null,this.sendBuffer=[],this.serializer=new rv,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=s=>{let o;return s?o=s:typeof fetch>"u"?o=(...l)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0).then(({default:a})=>a(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${t}/${Bo.websocket}`,n!=null&&n.transport?this.transport=n.transport:this.transport=null,n!=null&&n.params&&(this.params=n.params),n!=null&&n.headers&&(this.headers=Object.assign(Object.assign({},this.headers),n.headers)),n!=null&&n.timeout&&(this.timeout=n.timeout),n!=null&&n.logger&&(this.logger=n.logger),n!=null&&n.heartbeatIntervalMs&&(this.heartbeatIntervalMs=n.heartbeatIntervalMs);const i=(r=n==null?void 0:n.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=n!=null&&n.reconnectAfterMs?n.reconnectAfterMs:s=>[1e3,2e3,5e3,1e4][s-1]||1e4,this.encode=n!=null&&n.encode?n.encode:(s,o)=>o(JSON.stringify(s)),this.decode=n!=null&&n.decode?n.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new nh(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(dv){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new fv(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Rn(()=>import("./browser-PEqAXY5b.js").then(t=>t.b),[]).then(({default:t})=>{this.conn=new t(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(t,n){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,n??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case kn.connecting:return Ut.Connecting;case kn.open:return Ut.Open;case kn.closing:return Ut.Closing;default:return Ut.Closed}}isConnected(){return this.connectionState()===Ut.Open}channel(t,n={config:{}}){const r=new Wl(`realtime:${t}`,n,this);return this.channels.push(r),r}push(t){const{topic:n,event:r,payload:i,ref:s}=t,o=()=>{this.encode(t,l=>{var a;(a=this.conn)===null||a===void 0||a.send(l)})};this.log("push",`${n} ${r} (${s})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(t){this.accessToken=t,this.channels.forEach(n=>{t&&n.updateJoinPayload({access_token:t}),n.joinedOnce&&n._isJoined()&&n._push(Fe.access_token,{access_token:t})})}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n._joinRef()!==t._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:tv}))}_onConnMessage(t){this.decode(t.data,n=>{let{topic:r,event:i,payload:s,ref:o}=n;(o&&o===this.pendingHeartbeatRef||i===(s==null?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,s),this.channels.filter(l=>l._isMember(r)).forEach(l=>l._trigger(i,s,o)),this.stateChangeCallbacks.message.forEach(l=>l(n))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(n=>n(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(n=>n(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(Fe.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",i=new URLSearchParams(n);return`${t}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_sendHeartbeat(){var t;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(t=this.conn)===null||t===void 0||t.close(nv,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}}class fv{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=kn.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class Kl extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function ae(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}class pv extends Kl{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class gu extends Kl{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var mv=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const ih=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},vv=()=>mv(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Rn(()=>Promise.resolve().then(()=>Ur),void 0)).Response:Response});var Un=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Ms=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),gv=(e,t)=>Un(void 0,void 0,void 0,function*(){const n=yield vv();e instanceof n?e.json().then(r=>{t(new pv(Ms(r),e.status||500))}).catch(r=>{t(new gu(Ms(r),r))}):t(new gu(Ms(e),e))}),yv=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};function ls(e,t,n,r,i,s){return Un(this,void 0,void 0,function*(){return new Promise((o,l)=>{e(n,yv(t,r,i,s)).then(a=>{if(!a.ok)throw a;return r!=null&&r.noResolveJson?a:a.json()}).then(a=>o(a)).catch(a=>gv(a,l))})})}function Ho(e,t,n,r){return Un(this,void 0,void 0,function*(){return ls(e,"GET",t,n,r)})}function ut(e,t,n,r,i){return Un(this,void 0,void 0,function*(){return ls(e,"POST",t,r,i,n)})}function wv(e,t,n,r,i){return Un(this,void 0,void 0,function*(){return ls(e,"PUT",t,r,i,n)})}function sh(e,t,n,r,i){return Un(this,void 0,void 0,function*(){return ls(e,"DELETE",t,r,i,n)})}var Te=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const _v={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class kv{constructor(t,n={},r,i){this.url=t,this.headers=n,this.bucketId=r,this.fetch=ih(i)}uploadOrUpdate(t,n,r,i){return Te(this,void 0,void 0,function*(){try{let s;const o=Object.assign(Object.assign({},yu),i),l=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.append("cacheControl",o.cacheControl)):(s=r,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType);const a=this._removeEmptyFolders(n),u=this._getFinalPath(a),c=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:s,headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{})),d=yield c.json();return c.ok?{data:{path:a,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(s){if(ae(s))return{data:null,error:s};throw s}})}upload(t,n,r){return Te(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,i){return Te(this,void 0,void 0,function*(){const s=this._removeEmptyFolders(t),o=this._getFinalPath(s),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",n);try{let a;const u=Object.assign({upsert:yu.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",u.cacheControl),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.append("cacheControl",u.cacheControl)):(a=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType);const d=yield this.fetch(l.toString(),{method:"PUT",body:a,headers:c}),f=yield d.json();return d.ok?{data:{path:s,fullPath:f.Key},error:null}:{data:null,error:f}}catch(a){if(ae(a))return{data:null,error:a};throw a}})}createSignedUploadUrl(t){return Te(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const r=yield ut(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:this.headers}),i=new URL(this.url+r.url),s=i.searchParams.get("token");if(!s)throw new Kl("No token returned by API");return{data:{signedUrl:i.toString(),path:t,token:s},error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}update(t,n,r){return Te(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n){return Te(this,void 0,void 0,function*(){try{return{data:yield ut(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}copy(t,n){return Te(this,void 0,void 0,function*(){try{return{data:{path:(yield ut(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers})).Key},error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}createSignedUrl(t,n,r){return Te(this,void 0,void 0,function*(){try{let i=this._getFinalPath(t),s=yield ut(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return s={signedUrl:encodeURI(`${this.url}${s.signedURL}${o}`)},{data:s,error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}createSignedUrls(t,n,r){return Te(this,void 0,void 0,function*(){try{const i=yield ut(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),s=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${s}`):null})),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}download(t,n){return Te(this,void 0,void 0,function*(){const i=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),o=s?`?${s}`:"";try{const l=this._getFinalPath(t);return{data:yield(yield Ho(this.fetch,`${this.url}/${i}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(ae(l))return{data:null,error:l};throw l}})}getPublicUrl(t,n){const r=this._getFinalPath(t),i=[],s=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";s!==""&&i.push(s);const l=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});a!==""&&i.push(a);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${r}${u}`)}}}remove(t){return Te(this,void 0,void 0,function*(){try{return{data:yield sh(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}list(t,n,r){return Te(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},_v),n),{prefix:t||""});return{data:yield ut(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const n=[];return t.width&&n.push(`width=${t.width}`),t.height&&n.push(`height=${t.height}`),t.resize&&n.push(`resize=${t.resize}`),t.format&&n.push(`format=${t.format}`),t.quality&&n.push(`quality=${t.quality}`),n.join("&")}}const Sv="2.5.5",Ev={"X-Client-Info":`storage-js/${Sv}`};var Xt=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Cv{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},Ev),n),this.fetch=ih(r)}listBuckets(){return Xt(this,void 0,void 0,function*(){try{return{data:yield Ho(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(ae(t))return{data:null,error:t};throw t}})}getBucket(t){return Xt(this,void 0,void 0,function*(){try{return{data:yield Ho(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return Xt(this,void 0,void 0,function*(){try{return{data:yield ut(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return Xt(this,void 0,void 0,function*(){try{return{data:yield wv(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}emptyBucket(t){return Xt(this,void 0,void 0,function*(){try{return{data:yield ut(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}deleteBucket(t){return Xt(this,void 0,void 0,function*(){try{return{data:yield sh(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}}class xv extends Cv{constructor(t,n={},r){super(t,n,r)}from(t){return new kv(this.url,this.headers,t,this.fetch)}}const Pv="2.43.4";let Zn="";typeof Deno<"u"?Zn="deno":typeof document<"u"?Zn="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Zn="react-native":Zn="node";const Tv={"X-Client-Info":`supabase-js-${Zn}/${Pv}`},Ov={headers:Tv},Rv={schema:"public"},jv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Lv={};var Iv=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const $v=e=>{let t;return e?t=e:typeof fetch>"u"?t=Vl:t=fetch,(...n)=>t(...n)},Nv=()=>typeof Headers>"u"?eh:Headers,Av=(e,t,n)=>{const r=$v(n),i=Nv();return(s,o)=>Iv(void 0,void 0,void 0,function*(){var l;const a=(l=yield t())!==null&&l!==void 0?l:e;let u=new i(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${a}`),r(s,Object.assign(Object.assign({},o),{headers:u}))})};function Uv(e){return e.replace(/\/$/,"")}function Dv(e,t){const{db:n,auth:r,realtime:i,global:s}=e,{db:o,auth:l,realtime:a,global:u}=t;return{db:Object.assign(Object.assign({},o),n),auth:Object.assign(Object.assign({},l),r),realtime:Object.assign(Object.assign({},a),i),global:Object.assign(Object.assign({},u),s)}}const oh="2.64.2",zv="http://localhost:9999",Fv="supabase.auth.token",Mv={"X-Client-Info":`gotrue-js/${oh}`},wu=10,Wo="X-Supabase-Api-Version",lh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function bv(e){return Math.round(Date.now()/1e3)+e}function Bv(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}const Ue=()=>typeof document<"u",Lt={tested:!1,writable:!1},cr=()=>{if(!Ue())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Lt.tested)return Lt.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Lt.tested=!0,Lt.writable=!0}catch{Lt.tested=!0,Lt.writable=!1}return Lt.writable};function bs(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((i,s)=>{t[s]=i})}catch{}return n.searchParams.forEach((r,i)=>{t[i]=r}),t}const ah=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Vv=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",uh=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},ni=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Bs=async(e,t)=>{await e.removeItem(t)};function Hv(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let n="",r,i,s,o,l,a,u,c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)o=t.indexOf(e.charAt(c++)),l=t.indexOf(e.charAt(c++)),a=t.indexOf(e.charAt(c++)),u=t.indexOf(e.charAt(c++)),r=o<<2|l>>4,i=(l&15)<<4|a>>2,s=(a&3)<<6|u,n=n+String.fromCharCode(r),a!=64&&i!=0&&(n=n+String.fromCharCode(i)),u!=64&&s!=0&&(n=n+String.fromCharCode(s));return n}class as{constructor(){this.promise=new as.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}as.promiseConstructor=Promise;function _u(e){const t=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,n=e.split(".");if(n.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!t.test(n[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=n[1];return JSON.parse(Hv(r))}async function Wv(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function Kv(e,t){return new Promise((r,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{const o=await e(s);if(!t(s,null,o)){r(o);return}}catch(o){if(!t(s,o)){i(o);return}}})()})}function Qv(e){return("0"+e.toString(16)).substr(-2)}function Gv(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let i="";for(let s=0;s<56;s++)i+=n.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(t),Array.from(t,Qv).join("")}async function Jv(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),i=new Uint8Array(r);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}function qv(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Yv(e){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const n=await Jv(e);return qv(n)}async function Zt(e,t,n=!1){const r=Gv();let i=r;n&&(i+="/PASSWORD_RECOVERY"),await uh(e,`${t}-code-verifier`,i);const s=await Yv(r);return[s,r===s?"plain":"s256"]}const Xv=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Zv(e){const t=e.headers.get(Wo);if(!t||!t.match(Xv))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}class Ql extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function L(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class eg extends Ql{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function tg(e){return L(e)&&e.name==="AuthApiError"}class ch extends Ql{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class qt extends Ql{constructor(t,n,r,i){super(t,r,i),this.name=n,this.status=r}}class It extends qt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class Vs extends qt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ri extends qt{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class ii extends qt{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class ku extends qt{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ko extends qt{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Hs(e){return L(e)&&e.name==="AuthRetryableFetchError"}class Su extends qt{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}var ng=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const At=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),rg=[502,503,504];async function Eu(e){var t;if(!Vv(e))throw new Ko(At(e),0);if(rg.includes(e.status))throw new Ko(At(e),e.status);let n;try{n=await e.json()}catch(s){throw new ch(At(s),s)}let r;const i=Zv(e);if(i&&i.getTime()>=lh["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new Su(At(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[])}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",!0))throw new Su(At(n),e.status,n.weak_password.reasons);throw new eg(At(n),e.status||500,r)}const ig=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function N(e,t,n,r){var i;const s=Object.assign({},r==null?void 0:r.headers);s[Wo]||(s[Wo]=lh["2024-01-01"].name),r!=null&&r.jwt&&(s.Authorization=`Bearer ${r.jwt}`);const o=(i=r==null?void 0:r.query)!==null&&i!==void 0?i:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",a=await sg(e,t,n+l,{headers:s,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(a):{data:Object.assign({},a),error:null}}async function sg(e,t,n,r,i,s){const o=ig(t,r,i,s);let l;try{l=await e(n,Object.assign({},o))}catch(a){throw console.error(a),new Ko(At(a),0)}if(l.ok||await Eu(l),r!=null&&r.noResolveJson)return l;try{return await l.json()}catch(a){await Eu(a)}}function ot(e){var t;let n=null;ug(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=bv(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function Cu(e){const t=ot(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function ht(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function og(e){return{data:e,error:null}}function lg(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s}=e,o=ng(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s},a=Object.assign({},o);return{data:{properties:l,user:a},error:null}}function ag(e){return e}function ug(e){return e.access_token&&e.refresh_token&&e.expires_in}var cg=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};class dg{constructor({url:t="",headers:n={},fetch:r}){this.url=t,this.headers=n,this.fetch=ah(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(t,n="global"){try{return await N(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(L(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await N(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:ht})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=cg(t,["options"]),i=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),await N(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:lg,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(L(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await N(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:ht})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,i,s,o,l,a;try{const u={nextPage:null,lastPage:0,total:0},c=await N(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=t==null?void 0:t.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:ag});if(c.error)throw c.error;const d=await c.json(),f=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,v=(a=(l=c.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&a!==void 0?a:[];return v.length>0&&(v.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(L(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){try{return await N(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:ht})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await N(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:ht})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await N(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:ht})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await N(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:n,error:r}}catch(n){if(L(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await N(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(L(n))return{data:null,error:n};throw n}}}const hg={getItem:e=>cr()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{cr()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{cr()&&globalThis.localStorage.removeItem(e)}};function xu(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}function fg(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const en={debug:!!(globalThis&&cr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class dh extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class pg extends dh{}async function mg(e,t,n){en.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),en.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){en.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await n()}finally{en.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}else{if(t===0)throw en.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new pg(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(en.debug)try{const s=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(s,null," "))}catch(s){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",s)}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 n()}})}fg();const vg={url:zv,storageKey:Fv,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Mv,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Qn=30*1e3,Pu=3;async function Tu(e,t,n){return await n()}class jr{constructor(t){var n,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=jr.nextInstanceID,jr.nextInstanceID+=1,this.instanceID>0&&Ue()&&console.warn("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.");const i=Object.assign(Object.assign({},vg),t);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new dg({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ah(i.fetch),this.lock=i.lock||Tu,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Ue()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=mg:this.lock=Tu,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:cr()?this.storage=hg:(this.memoryStorage={},this.storage=xu(this.memoryStorage)):(this.memoryStorage={},this.storage=xu(this.memoryStorage)),Ue()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",s)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async s=>{this._debug("received broadcast notification from other tab or client",s),await this._notifyAllSubscribers(s.data.event,s.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${oh}) ${new Date().toISOString()}`,...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{const t=Ue()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",t),t||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:n,error:r}=await this._getSessionFromURL(t);if(r)return this._debug("#_initialize()","error detecting session from URL",r),(r==null?void 0:r.message)==="Identity is already linked"||(r==null?void 0:r.message)==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});const{session:i,redirectType:s}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",s),await this._saveSession(i),setTimeout(async()=>{s==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return L(t)?{error:t}:{error:new ch("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,i;try{await this._removeSession();const s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=t==null?void 0:t.options)===null||i===void 0?void 0:i.captchaToken}},xform:ot}),{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(L(s))return{data:{user:null,session:null},error:s};throw s}}async signUp(t){var n,r,i;try{await this._removeSession();let s;if("email"in t){const{email:c,password:d,options:f}=t;let v=null,g=null;this.flowType==="pkce"&&([v,g]=await Zt(this.storage,this.storageKey)),s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:c,password:d,data:(n=f==null?void 0:f.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:v,code_challenge_method:g},xform:ot})}else if("phone"in t){const{phone:c,password:d,options:f}=t;s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},channel:(i=f==null?void 0:f.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:ot})}else throw new ri("You must provide either an email or phone number and a password");const{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(L(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithPassword(t){try{await this._removeSession();let n;if("email"in t){const{email:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Cu})}else if("phone"in t){const{phone:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Cu})}else throw new ri("You must provide either an email or phone number and a password");const{data:r,error:i}=n;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Vs}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(t){var n,r,i,s;return await this._removeSession(),await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=t.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=t.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const n=await ni(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(n??"").split("/"),{data:s,error:o}=await N(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:ot});return await Bs(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!s||!s.session||!s.user?{data:{user:null,session:null,redirectType:null},error:new Vs}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}async signInWithIdToken(t){await this._removeSession();try{const{options:n,provider:r,token:i,access_token:s,nonce:o}=t,l=await N(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:ot}),{data:a,error:u}=l;return u?{data:{user:null,session:null},error:u}:!a||!a.session||!a.user?{data:{user:null,session:null},error:new Vs}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:u})}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(t){var n,r,i,s,o;try{if(await this._removeSession(),"email"in t){const{email:l,options:a}=t;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await Zt(this.storage,this.storageKey));const{error:d}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(n=a==null?void 0:a.data)!==null&&n!==void 0?n:{},create_user:(r=a==null?void 0:a.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:a==null?void 0:a.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in t){const{phone:l,options:a}=t,{data:u,error:c}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=a==null?void 0:a.data)!==null&&i!==void 0?i:{},create_user:(s=a==null?void 0:a.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},channel:(o=a==null?void 0:a.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c}}throw new ri("You must provide either an email or phone number.")}catch(l){if(L(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(t){var n,r;try{t.type!=="email_change"&&t.type!=="phone_change"&&await this._removeSession();let i,s;"options"in t&&(i=(n=t.options)===null||n===void 0?void 0:n.redirectTo,s=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:ot});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const a=o.session,u=o.user;return a!=null&&a.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(i){if(L(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(t){var n,r,i;try{await this._removeSession();let s=null,o=null;return this.flowType==="pkce"&&([s,o]=await Zt(this.storage,this.storageKey)),await N(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=t==null?void 0:t.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:s,code_challenge_method:o}),headers:this.headers,xform:og})}catch(s){if(L(s))return{data:null,error:s};throw s}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new It;const{error:i}=await N(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:i}})}catch(t){if(L(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{t.type!="email_change"&&t.type!="phone_change"&&await this._removeSession();const n=`${this.url}/resend`;if("email"in t){const{email:r,type:i,options:s}=t,{error:o}=await N(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},redirectTo:s==null?void 0:s.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in t){const{phone:r,type:i,options:s}=t,{data:o,error:l}=await N(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l}}throw new ri("You must provide either an email or phone number and a type")}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await ni(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",t.expires_at),!r){if(this.storage.isServer){const o=this.suppressGetSessionWarning;t=new Proxy(t,{get(a,u,c){return!o&&u==="user"&&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 many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),Reflect.get(a,u,c)}})}return{data:{session:t},error:null}}const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{session:null},error:s}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:ht}):await this._useSession(async n=>{var r,i,s;const{data:o,error:l}=n;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new It}:await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:ht})})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:i,error:s}=r;if(s)throw s;if(!i.session)throw new It;const o=i.session;let l=null,a=null;this.flowType==="pkce"&&t.email!=null&&([l,a]=await Zt(this.storage,this.storageKey));const{data:u,error:c}=await N(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:l,code_challenge_method:a}),jwt:o.access_token,xform:ht});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}_decodeJWT(t){return _u(t)}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new It;const n=Date.now()/1e3;let r=n,i=!0,s=null;const o=_u(t.access_token);if(o.exp&&(r=o.exp,i=r<=n),i){const{session:l,error:a}=await this._callRefreshToken(t.refresh_token);if(a)return{data:{user:null,session:null},error:a};if(!l)return{data:{user:null,session:null},error:null};s=l}else{const{data:l,error:a}=await this._getUser(t.access_token);if(a)throw a;s={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return{data:{user:s.user,session:s},error:null}}catch(n){if(L(n))return{data:{session:null,user:null},error:n};throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:l}=n;if(l)throw l;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new It;const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{user:null,session:null},error:s}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t){try{if(!Ue())throw new ii("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ii("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!t)throw new ku("Not a valid PKCE flow url.");const n=bs(window.location.href);if(t){if(!n.code)throw new ku("No code detected.");const{data:h,error:m}=await this._exchangeCodeForSession(n.code);if(m)throw m;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:h.session,redirectType:null},error:null}}if(n.error||n.error_description||n.error_code)throw new ii(n.error_description||"Error in URL with unspecified error_description",{error:n.error||"unspecified_error",code:n.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:l,expires_at:a,token_type:u}=n;if(!s||!l||!o||!u)throw new ii("No session defined in URL");const c=Math.round(Date.now()/1e3),d=parseInt(l);let f=c+d;a&&(f=parseInt(a));const v=f-c;v*1e3<=Qn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${v}s, should have been closer to ${d}s`);const g=f-d;c-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,c):c-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,f,c);const{data:y,error:_}=await this._getUser(s);if(_)throw _;const p={provider_token:r,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:f,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:p,redirectType:n.type},error:null}}catch(n){if(L(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantFlow(){const t=bs(window.location.href);return!!(Ue()&&(t.access_token||t.error_description))}async _isPKCEFlow(){const t=bs(window.location.href),n=await ni(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{error:s};const o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:l}=await this.admin.signOut(o,t);if(l&&!(tg(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return t!=="others"&&(await this._removeSession(),await Bs(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(t){const n=Bv(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,i;try{const{data:{session:s},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",t,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(t))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",s),console.error(s)}})}async resetPasswordForEmail(t,n={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Zt(this.storage,this.storageKey,!0));try{return await N(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(s){if(L(s))return{data:null,error:s};throw s}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(n){if(L(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:i}=await this._useSession(async s=>{var o,l,a,u,c;const{data:d,error:f}=s;if(f)throw f;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=t.options)===null||l===void 0?void 0:l.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:!0});return await N(this.fetch,"GET",v,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(i)throw i;return Ue()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:t.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(L(r))return{data:{provider:t.provider,url:null},error:r};throw r}}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)throw o;return await N(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(i=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Kv(async i=>(i>0&&await Wv(200*Math.pow(2,i-1)),this._debug(n,"refreshing attempt",i),await N(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:ot})),(i,s)=>{const o=200*Math.pow(2,i);return s&&Hs(s)&&Date.now()+o-r<Qn})}catch(r){if(this._debug(n,"error",r),L(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(n,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,n){const r=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",n,"url",r),Ue()&&!n.skipBrowserRedirect&&window.location.assign(r),{data:{provider:t,url:r},error:null}}async _recoverAndRefresh(){var t;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const r=await ni(this.storage,this.storageKey);if(this._debug(n,"session from storage",r),!this._isValidSession(r)){this._debug(n,"session is not valid"),r!==null&&await this._removeSession();return}const i=Math.round(Date.now()/1e3),s=((t=r.expires_at)!==null&&t!==void 0?t:1/0)<i+wu;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${wu}s`),s){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Hs(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(n,"error",r),console.error(r);return}finally{this._debug(n,"end")}}async _callRefreshToken(t){var n,r;if(!t)throw new It;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${t.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new as;const{data:s,error:o}=await this._refreshAccessToken(t);if(o)throw o;if(!s.session)throw new It;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);const l={session:s.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(s){if(this._debug(i,"error",s),L(s)){const o={session:null,error:s};return Hs(s)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(t,n,r=!0){const i=`#_notifyAllSubscribers(${t})`;this._debug(i,"begin",n,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:t,session:n});const s=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,n)}catch(a){s.push(a)}});if(await Promise.all(o),s.length>0){for(let l=0;l<s.length;l+=1)console.error(s[l]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0,await uh(this.storage,this.storageKey,t)}async _removeSession(){this._debug("#_removeSession()"),await Bs(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&Ue()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Qn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(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{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-t)/Qn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Qn}ms, refresh threshold is ${Pu} ticks`),i<=Pu&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof dh)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ue()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){const i=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[s,o]=await Zt(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(l.toString())}if(r!=null&&r.queryParams){const s=new URLSearchParams(r.queryParams);i.push(s.toString())}return r!=null&&r.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${i.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)return{data:null,error:o};const{data:l,error:a}=await N(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:t.friendlyName,factor_type:t.factorType,issuer:t.issuer},headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{data:null,error:s};const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(n){if(L(n))return{data:null,error:n};throw n}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(L(n))return{data:null,error:n};throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?{data:null,error:r}:await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(t==null?void 0:t.factors)||[],i=r.filter(s=>s.factor_type==="totp"&&s.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var n,r;const{data:{session:i},error:s}=t;if(s)return{data:null,error:s};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const o=this._decodeJWT(i.access_token);let l=null;o.aal&&(l=o.aal);let a=l;((r=(n=i.user.factors)===null||n===void 0?void 0:n.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(a="aal2");const c=o.amr||[];return{data:{currentLevel:l,nextLevel:a,currentAuthenticationMethods:c},error:null}}))}}jr.nextInstanceID=0;const gg=jr;class yg extends gg{constructor(t){super(t)}}var wg=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class _g{constructor(t,n,r){var i,s,o;if(this.supabaseUrl=t,this.supabaseKey=n,!t)throw new Error("supabaseUrl is required.");if(!n)throw new Error("supabaseKey is required.");const l=Uv(t);this.realtimeUrl=`${l}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${l}/auth/v1`,this.storageUrl=`${l}/storage/v1`,this.functionsUrl=`${l}/functions/v1`;const a=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:Rv,realtime:Lv,auth:Object.assign(Object.assign({},jv),{storageKey:a}),global:Ov},c=Dv(r??{},u);this.storageKey=(i=c.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Av(n,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new Hl(`${l}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Bm(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new xv(this.storageUrl,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,n={},r={}){return this.rest.rpc(t,n,r)}channel(t,n={config:{}}){return this.realtime.channel(t,n)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,n;return wg(this,void 0,void 0,function*(){const{data:r}=yield this.auth.getSession();return(n=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&n!==void 0?n:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,storageKey:s,flowType:o,debug:l},a,u){var c;const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new yg({url:this.authUrl,headers:Object.assign(Object.assign({},d),a),storageKey:s,autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,flowType:o,debug:l,fetch:u,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(t){return new hv(this.realtimeUrl,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(t,n,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):t==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const kg=(e,t,n)=>new _g(e,t,n);function Sg(e){const t=Yd(),[n,r]=x.useState([]);x.useEffect(()=>{e.session||t("/login")},[e.session]);const i=x.useCallback(async()=>{const{data:s,error:o}=await e.supabase.from("file").select();if(o){console.error(o);return}r(s.map(l=>l))},[e.supabase]);return x.useEffect(()=>{i()},[]),D.jsx(D.Fragment,{children:D.jsxs("div",{children:[D.jsx("h1",{children:"Home"}),D.jsx("p",{children:"Logged in!"}),n.map(s=>D.jsx("div",{children:D.jsxs("p",{children:["file: ",s.absolute_path]})},s.id))]})})}function Eg(e){const t=Yd();return x.useEffect(()=>{window.HandleSignInWithGoogle=async r=>{await e.supabase.auth.signInWithIdToken({provider:"google",token:r.credential})},e.supabase.auth.getSession().then(({data:{session:r}})=>{e.setSession(r),console.log("LOGIN SESSION",r)});const{data:{subscription:n}}=e.supabase.auth.onAuthStateChange((r,i)=>{e.setSession(i),console.log("SESSION CHANGE",i)});return()=>n.unsubscribe()},[]),x.useEffect(()=>{e.session&&t("/")},[e.session]),D.jsxs(D.Fragment,{children:[D.jsxs("div",{children:[D.jsx("h1",{children:"Login"}),D.jsxs("p",{children:["Log in to access your account! ",JSON.stringify(e.session)]})]}),D.jsx("div",{id:"g_id_onload","data-client_id":"952965459060-nrnrsdoq22mf646vfa72hk410pvdda5q.apps.googleusercontent.com","data-context":"signin","data-ux_mode":"popup","data-callback":"HandleSignInWithGoogle","data-auto_prompt":"false"}),D.jsx("div",{className:"g_id_signin","data-type":"standard","data-shape":"pill","data-theme":"outline","data-text":"signin","data-size":"large","data-logo_alignment":"center"})]})}const Ou=kg("https://slpoocycjgqsuoedhkbn.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNscG9vY3ljamdxc3VvZWRoa2JuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTUyMDU0MjUsImV4cCI6MjAzMDc4MTQyNX0.xZYRTRN65rlms1Hb96IBAQvw3EGtMzUxlGPP5TVey34");function Cg(){const[e,t]=x.useState(null);return D.jsx(D.Fragment,{children:D.jsx(Nm,{children:D.jsx(Lm,{children:D.jsxs(Xn,{path:"/",children:[D.jsx(Xn,{index:!0,element:D.jsx(Sg,{supabase:Ou,session:e})}),D.jsx(Xn,{path:"login",element:D.jsx(Eg,{supabase:Ou,session:e,setSession:t})}),D.jsx(Xn,{path:"*",element:D.jsx("p",{children:"notfound"})})]})})})})}Ws.createRoot(document.getElementById("root")).render(D.jsx(Fu.StrictMode,{children:D.jsx(Cg,{})}));export{ph as g}; + */const Im="6";try{window.__reactRouterVersion=Im}catch{}const $m="startTransition",au=jh[$m];function Nm(e){let{basename:t,children:n,future:r,window:i}=e,s=x.useRef();s.current==null&&(s.current=Vp({window:i,v5Compat:!0}));let o=s.current,[l,a]=x.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},c=x.useCallback(d=>{u&&au?au(()=>a(d)):a(d)},[a,u]);return x.useLayoutEffect(()=>o.listen(c),[o,c]),x.createElement(jm,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}var uu;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(uu||(uu={}));var cu;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(cu||(cu={}));const Am="modulepreload",Um=function(e,t){return new URL(e,t).href},du={},Rn=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){const s=document.getElementsByTagName("link"),o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=Promise.all(n.map(a=>{if(a=Um(a,r),a in du)return;du[a]=!0;const u=a.endsWith(".css"),c=u?'[rel="stylesheet"]':"";if(!!r)for(let v=s.length-1;v>=0;v--){const g=s[v];if(g.href===a&&(!u||g.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${a}"]${c}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Am,u||(f.as="script",f.crossOrigin=""),f.href=a,l&&f.setAttribute("nonce",l),document.head.appendChild(f),u)return new Promise((v,g)=>{f.addEventListener("load",v),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${a}`)))})}))}return i.then(()=>t()).catch(s=>{const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=s,window.dispatchEvent(o),!o.defaultPrevented)throw s})},Dm=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class Bl extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class zm extends Bl{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class Fm extends Bl{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Mm extends Bl{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var bo;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(bo||(bo={}));var bm=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Bm{constructor(t,{headers:n={},customFetch:r,region:i=bo.Any}={}){this.url=t,this.headers=n,this.region=i,this.fetch=Dm(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return bm(this,void 0,void 0,function*(){try{const{headers:i,method:s,body:o}=n;let l={},{region:a}=n;a||(a=this.region),a&&a!=="any"&&(l["x-region"]=a);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(l["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(l["Content-Type"]="application/json",u=JSON.stringify(o)));const c=yield this.fetch(`${this.url}/${t}`,{method:s||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:u}).catch(g=>{throw new zm(g)}),d=c.headers.get("x-relay-error");if(d&&d==="true")throw new Fm(c);if(!c.ok)throw new Mm(c);let f=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),v;return f==="application/json"?v=yield c.json():f==="application/octet-stream"?v=yield c.blob():f==="text/event-stream"?v=c:f==="multipart/form-data"?v=yield c.formData():v=yield c.text(),{data:v,error:null}}catch(i){return{data:null,error:i}}})}}var Vm=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},jn=Vm();const Hm=jn.fetch,Vl=jn.fetch.bind(jn),eh=jn.Headers,Wm=jn.Request,Km=jn.Response,Ur=Object.freeze(Object.defineProperty({__proto__:null,Headers:eh,Request:Wm,Response:Km,default:Vl,fetch:Hm},Symbol.toStringTag,{value:"Module"}));class Qm extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}class Gm{constructor(t){this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=t.headers,this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=t.shouldThrowOnError,this.signal=t.signal,this.isMaybeSingle=t.isMaybeSingle,t.fetch?this.fetch=t.fetch:typeof fetch>"u"?this.fetch=Vl:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{var o,l,a;let u=null,c=null,d=null,f=s.status,v=s.statusText;if(s.ok){if(this.method!=="HEAD"){const p=await s.text();p===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=p:c=JSON.parse(p))}const y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(l=s.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");y&&_&&_.length>1&&(d=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(u={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,d=null,f=406,v="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{const y=await s.text();try{u=JSON.parse(y),Array.isArray(u)&&s.status===404&&(c=[],u=null,f=200,v="OK")}catch{s.status===404&&y===""?(f=204,v="No Content"):u={message:y}}if(u&&this.isMaybeSingle&&(!((a=u==null?void 0:u.details)===null||a===void 0)&&a.includes("0 rows"))&&(u=null,f=200,v="OK"),u&&this.shouldThrowOnError)throw new Qm(u)}return{error:u,data:c,count:d,status:f,statusText:v}});return this.shouldThrowOnError||(i=i.catch(s=>{var o,l,a;return{error:{message:`${(o=s==null?void 0:s.name)!==null&&o!==void 0?o:"FetchError"}: ${s==null?void 0:s.message}`,details:`${(l=s==null?void 0:s.stack)!==null&&l!==void 0?l:""}`,hint:"",code:`${(a=s==null?void 0:s.code)!==null&&a!==void 0?a:""}`},data:null,count:null,status:0,statusText:""}})),i.then(t,n)}}class Jm extends Gm{select(t){let n=!1;const r=(t??"*").split("").map(i=>/\s/.test(i)&&!n?"":(i==='"'&&(n=!n),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:n=!0,nullsFirst:r,foreignTable:i,referencedTable:s=i}={}){const o=s?`${s}.order`:"order",l=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${l?`${l},`:""}${t}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:n,referencedTable:r=n}={}){const i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,n,{foreignTable:r,referencedTable:i=r}={}){const s=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(o,`${n-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:n=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:o="text"}={}){var l;const a=[t?"analyze":null,n?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),u=(l=this.headers.Accept)!==null&&l!==void 0?l:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${a};`,o==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class tn extends Jm{eq(t,n){return this.url.searchParams.append(t,`eq.${n}`),this}neq(t,n){return this.url.searchParams.append(t,`neq.${n}`),this}gt(t,n){return this.url.searchParams.append(t,`gt.${n}`),this}gte(t,n){return this.url.searchParams.append(t,`gte.${n}`),this}lt(t,n){return this.url.searchParams.append(t,`lt.${n}`),this}lte(t,n){return this.url.searchParams.append(t,`lte.${n}`),this}like(t,n){return this.url.searchParams.append(t,`like.${n}`),this}likeAllOf(t,n){return this.url.searchParams.append(t,`like(all).{${n.join(",")}}`),this}likeAnyOf(t,n){return this.url.searchParams.append(t,`like(any).{${n.join(",")}}`),this}ilike(t,n){return this.url.searchParams.append(t,`ilike.${n}`),this}ilikeAllOf(t,n){return this.url.searchParams.append(t,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(t,n){return this.url.searchParams.append(t,`ilike(any).{${n.join(",")}}`),this}is(t,n){return this.url.searchParams.append(t,`is.${n}`),this}in(t,n){const r=Array.from(new Set(n)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}contains(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cs.{${n.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(n)}`),this}containedBy(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cd.{${n.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(n)}`),this}rangeGt(t,n){return this.url.searchParams.append(t,`sr.${n}`),this}rangeGte(t,n){return this.url.searchParams.append(t,`nxl.${n}`),this}rangeLt(t,n){return this.url.searchParams.append(t,`sl.${n}`),this}rangeLte(t,n){return this.url.searchParams.append(t,`nxr.${n}`),this}rangeAdjacent(t,n){return this.url.searchParams.append(t,`adj.${n}`),this}overlaps(t,n){return typeof n=="string"?this.url.searchParams.append(t,`ov.${n}`):this.url.searchParams.append(t,`ov.{${n.join(",")}}`),this}textSearch(t,n,{config:r,type:i}={}){let s="";i==="plain"?s="pl":i==="phrase"?s="ph":i==="websearch"&&(s="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${o}.${n}`),this}match(t){return Object.entries(t).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(t,n,r){return this.url.searchParams.append(t,`not.${n}.${r}`),this}or(t,{foreignTable:n,referencedTable:r=n}={}){const i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,n,r){return this.url.searchParams.append(t,`${n}.${r}`),this}}class qm{constructor(t,{headers:n={},schema:r,fetch:i}){this.url=t,this.headers=n,this.schema=r,this.fetch=i}select(t,{head:n=!1,count:r}={}){const i=n?"HEAD":"GET";let s=!1;const o=(t??"*").split("").map(l=>/\s/.test(l)&&!s?"":(l==='"'&&(s=!s),l)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new tn({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:n,defaultToNull:r=!0}={}){const i="POST",s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),n&&s.push(`count=${n}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(t)){const o=t.reduce((l,a)=>l.concat(Object.keys(a)),[]);if(o.length>0){const l=[...new Set(o)].map(a=>`"${a}"`);this.url.searchParams.set("columns",l.join(","))}}return new tn({method:i,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){const o="POST",l=[`resolution=${r?"ignore":"merge"}-duplicates`];if(n!==void 0&&this.url.searchParams.set("on_conflict",n),this.headers.Prefer&&l.push(this.headers.Prefer),i&&l.push(`count=${i}`),s||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(t)){const a=t.reduce((u,c)=>u.concat(Object.keys(c)),[]);if(a.length>0){const u=[...new Set(a)].map(c=>`"${c}"`);this.url.searchParams.set("columns",u.join(","))}}return new tn({method:o,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:n}={}){const r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),n&&i.push(`count=${n}`),this.headers.Prefer=i.join(","),new tn({method:r,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const n="DELETE",r=[];return t&&r.push(`count=${t}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new tn({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const Ym="1.15.2",Xm={"X-Client-Info":`postgrest-js/${Ym}`};class Hl{constructor(t,{headers:n={},schema:r,fetch:i}={}){this.url=t,this.headers=Object.assign(Object.assign({},Xm),n),this.schemaName=r,this.fetch=i}from(t){const n=new URL(`${this.url}/${t}`);return new qm(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new Hl(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,n={},{head:r=!1,get:i=!1,count:s}={}){let o;const l=new URL(`${this.url}/rpc/${t}`);let a;r||i?(o=r?"HEAD":"GET",Object.entries(n).filter(([c,d])=>d!==void 0).map(([c,d])=>[c,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([c,d])=>{l.searchParams.append(c,d)})):(o="POST",a=n);const u=Object.assign({},this.headers);return s&&(u.Prefer=`count=${s}`),new tn({method:o,url:l,headers:u,schema:this.schemaName,body:a,fetch:this.fetch,allowEmpty:!1})}}const Zm="2.9.5",ev={"X-Client-Info":`realtime-js/${Zm}`},tv="1.0.0",th=1e4,nv=1e3;var kn;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(kn||(kn={}));var _e;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(_e||(_e={}));var Fe;(function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"})(Fe||(Fe={}));var Bo;(function(e){e.websocket="websocket"})(Bo||(Bo={}));var Ut;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(Ut||(Ut={}));class nh{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class rv{constructor(){this.HEADER_LENGTH=1}decode(t,n){return t.constructor===ArrayBuffer?n(this._binaryDecode(t)):n(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const n=new DataView(t),r=new TextDecoder;return this._decodeBroadcast(t,n,r)}_decodeBroadcast(t,n,r){const i=n.getUint8(1),s=n.getUint8(2);let o=this.HEADER_LENGTH+2;const l=r.decode(t.slice(o,o+i));o=o+i;const a=r.decode(t.slice(o,o+s));o=o+s;const u=JSON.parse(r.decode(t.slice(o,t.byteLength)));return{ref:null,topic:l,event:a,payload:u}}}class Fs{constructor(t,n,r={},i=th){this.channel=t,this.event=n,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,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(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var hu;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(hu||(hu={}));class ur{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ur.syncState(this.state,i,s,o),this.pendingDiffs.forEach(a=>{this.state=ur.syncDiff(this.state,a,s,o)}),this.pendingDiffs=[],l()}),this.channel._on(r.diff,{},i=>{const{onJoin:s,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=ur.syncDiff(this.state,i,s,o),l())}),this.onJoin((i,s,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:s,newPresences:o})}),this.onLeave((i,s,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:s,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,i){const s=this.cloneDeep(t),o=this.transformState(n),l={},a={};return this.map(s,(u,c)=>{o[u]||(a[u]=c)}),this.map(o,(u,c)=>{const d=s[u];if(d){const f=c.map(_=>_.presence_ref),v=d.map(_=>_.presence_ref),g=c.filter(_=>v.indexOf(_.presence_ref)<0),y=d.filter(_=>f.indexOf(_.presence_ref)<0);g.length>0&&(l[u]=g),y.length>0&&(a[u]=y)}else l[u]=c}),this.syncDiff(s,{joins:l,leaves:a},r,i)}static syncDiff(t,n,r,i){const{joins:s,leaves:o}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(s,(l,a)=>{var u;const c=(u=t[l])!==null&&u!==void 0?u:[];if(t[l]=this.cloneDeep(a),c.length>0){const d=t[l].map(v=>v.presence_ref),f=c.filter(v=>d.indexOf(v.presence_ref)<0);t[l].unshift(...f)}r(l,c,a)}),this.map(o,(l,a)=>{let u=t[l];if(!u)return;const c=a.map(d=>d.presence_ref);u=u.filter(d=>c.indexOf(d.presence_ref)<0),t[l]=u,i(l,u,a),u.length===0&&delete t[l]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const i=t[r];return"metas"in i?n[r]=i.metas.map(s=>(s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s)):n[r]=i,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var z;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(z||(z={}));const fu=(e,t,n={})=>{var r;const i=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((s,o)=>(s[o]=iv(o,e,t,i),s),{})},iv=(e,t,n,r)=>{const i=t.find(l=>l.name===e),s=i==null?void 0:i.type,o=n[e];return s&&!r.includes(s)?rh(s,o):Vo(o)},rh=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return av(t,n)}switch(e){case z.bool:return sv(t);case z.float4:case z.float8:case z.int2:case z.int4:case z.int8:case z.numeric:case z.oid:return ov(t);case z.json:case z.jsonb:return lv(t);case z.timestamp:return uv(t);case z.abstime:case z.date:case z.daterange:case z.int4range:case z.int8range:case z.money:case z.reltime:case z.text:case z.time:case z.timestamptz:case z.timetz:case z.tsrange:case z.tstzrange:return Vo(t);default:return Vo(t)}},Vo=e=>e,sv=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ov=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},lv=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},av=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let s;const o=e.slice(1,n);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(l=>rh(t,l))}return e},uv=e=>typeof e=="string"?e.replace(" ","T"):e;var pu;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(pu||(pu={}));var mu;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes"})(mu||(mu={}));var vu;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(vu||(vu={}));class Wl{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=_e.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},n.config),this.timeout=this.socket.timeout,this.joinPush=new Fs(this,Fe.join,this.params,this.timeout),this.rejoinTimer=new nh(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=_e.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=_e.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=_e.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=_e.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Fe.reply,{},(i,s)=>{this._trigger(this._replyEventName(s),i)}),this.presence=new ur(this),this.broadcastEndpointURL=this._broadcastEndpointURL()}subscribe(t,n=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:s,presence:o}}=this.params;this._onError(u=>t&&t("CHANNEL_ERROR",u)),this._onClose(()=>t&&t("CLOSED"));const l={},a={broadcast:s,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&i!==void 0?i:[]};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:a},l)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",({postgres_changes:u})=>{var c;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){t&&t("SUBSCRIBED");return}else{const d=this.bindings.postgres_changes,f=(c=d==null?void 0:d.length)!==null&&c!==void 0?c:0,v=[];for(let g=0;g<f;g++){const y=d[g],{filter:{event:_,schema:p,table:h,filter:m}}=y,w=u&&u[g];if(w&&w.event===_&&w.schema===p&&w.table===h&&w.filter===m)v.push(Object.assign(Object.assign({},y),{id:w.id}));else{this.unsubscribe(),t&&t("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,t&&t("SUBSCRIBED");return}}).receive("error",u=>{t&&t("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t&&t("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this._on(t,n,r)}async send(t,n={}){var r,i;if(!this._canPush()&&t.type==="broadcast"){const{event:s,payload:o}=t,l={method:"POST",headers:{apikey:(r=this.socket.apiKey)!==null&&r!==void 0?r:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o}]})};try{return(await this._fetchWithTimeout(this.broadcastEndpointURL,l,(i=n.timeout)!==null&&i!==void 0?i:this.timeout)).ok?"ok":"error"}catch(a){return a.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,l,a;const u=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((a=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||a===void 0)&&a.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=_e.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Fe.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const i=new Fs(this,Fe.leave,{},t);i.receive("ok",()=>{n(),r("ok")}).receive("timeout",()=>{n(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}_broadcastEndpointURL(){let t=this.socket.endPoint;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")+"/api/broadcast"}async _fetchWithTimeout(t,n,r){const i=new AbortController,s=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:i.signal}));return clearTimeout(s),o}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Fs(this,t,n,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var i,s;const o=t.toLocaleLowerCase(),{close:l,error:a,leave:u,join:c}=Fe;if(r&&[l,a,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,n,r);if(n&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(v=>{var g,y,_;return((g=v.filter)===null||g===void 0?void 0:g.event)==="*"||((_=(y=v.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(v=>v.callback(f,r)):(s=this.bindings[o])===null||s===void 0||s.filter(v=>{var g,y,_,p,h,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in v){const w=v.id,S=(g=v.filter)===null||g===void 0?void 0:g.event;return w&&((y=n.ids)===null||y===void 0?void 0:y.includes(w))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((_=n.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const w=(h=(p=v==null?void 0:v.filter)===null||p===void 0?void 0:p.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return w==="*"||w===((m=n==null?void 0:n.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return v.type.toLocaleLowerCase()===o}).map(v=>{if(typeof f=="object"&&"ids"in f){const g=f.data,{schema:y,table:_,commit_timestamp:p,type:h,errors:m}=g;f=Object.assign(Object.assign({},{schema:y,table:_,commit_timestamp:p,eventType:h,new:{},old:{},errors:m}),this._getPayloadRecords(g))}v.callback(f,r)})}_isClosed(){return this.state===_e.closed}_isJoined(){return this.state===_e.joined}_isJoining(){return this.state===_e.joining}_isLeaving(){return this.state===_e.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const i=t.toLocaleLowerCase(),s={type:i,filter:n,callback:r};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var s;return!(((s=i.type)===null||s===void 0?void 0:s.toLocaleLowerCase())===r&&Wl.isEqual(i.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(Fe.close,{},t)}_onError(t){this._on(Fe.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=_e.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=fu(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=fu(t.columns,t.old_record)),n}}const cv=()=>{},dv=typeof WebSocket<"u";class hv{constructor(t,n){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.headers=ev,this.params={},this.timeout=th,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=cv,this.conn=null,this.sendBuffer=[],this.serializer=new rv,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=s=>{let o;return s?o=s:typeof fetch>"u"?o=(...l)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0,import.meta.url).then(({default:a})=>a(...l)):o=fetch,(...l)=>o(...l)},this.endPoint=`${t}/${Bo.websocket}`,n!=null&&n.transport?this.transport=n.transport:this.transport=null,n!=null&&n.params&&(this.params=n.params),n!=null&&n.headers&&(this.headers=Object.assign(Object.assign({},this.headers),n.headers)),n!=null&&n.timeout&&(this.timeout=n.timeout),n!=null&&n.logger&&(this.logger=n.logger),n!=null&&n.heartbeatIntervalMs&&(this.heartbeatIntervalMs=n.heartbeatIntervalMs);const i=(r=n==null?void 0:n.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=n!=null&&n.reconnectAfterMs?n.reconnectAfterMs:s=>[1e3,2e3,5e3,1e4][s-1]||1e4,this.encode=n!=null&&n.encode?n.encode:(s,o)=>o(JSON.stringify(s)),this.decode=n!=null&&n.decode?n.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new nh(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(dv){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new fv(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Rn(()=>import("./browser-DG571wtW.js").then(t=>t.b),[],import.meta.url).then(({default:t})=>{this.conn=new t(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(t,n){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,n??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case kn.connecting:return Ut.Connecting;case kn.open:return Ut.Open;case kn.closing:return Ut.Closing;default:return Ut.Closed}}isConnected(){return this.connectionState()===Ut.Open}channel(t,n={config:{}}){const r=new Wl(`realtime:${t}`,n,this);return this.channels.push(r),r}push(t){const{topic:n,event:r,payload:i,ref:s}=t,o=()=>{this.encode(t,l=>{var a;(a=this.conn)===null||a===void 0||a.send(l)})};this.log("push",`${n} ${r} (${s})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(t){this.accessToken=t,this.channels.forEach(n=>{t&&n.updateJoinPayload({access_token:t}),n.joinedOnce&&n._isJoined()&&n._push(Fe.access_token,{access_token:t})})}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n._joinRef()!==t._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:tv}))}_onConnMessage(t){this.decode(t.data,n=>{let{topic:r,event:i,payload:s,ref:o}=n;(o&&o===this.pendingHeartbeatRef||i===(s==null?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,s),this.channels.filter(l=>l._isMember(r)).forEach(l=>l._trigger(i,s,o)),this.stateChangeCallbacks.message.forEach(l=>l(n))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(n=>n(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(n=>n(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(Fe.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",i=new URLSearchParams(n);return`${t}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_sendHeartbeat(){var t;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(t=this.conn)===null||t===void 0||t.close(nv,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}}class fv{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=kn.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class Kl extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function ae(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}class pv extends Kl{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class gu extends Kl{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var mv=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const ih=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},vv=()=>mv(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Rn(()=>Promise.resolve().then(()=>Ur),void 0,import.meta.url)).Response:Response});var Un=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const Ms=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),gv=(e,t)=>Un(void 0,void 0,void 0,function*(){const n=yield vv();e instanceof n?e.json().then(r=>{t(new pv(Ms(r),e.status||500))}).catch(r=>{t(new gu(Ms(r),r))}):t(new gu(Ms(e),e))}),yv=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};function ls(e,t,n,r,i,s){return Un(this,void 0,void 0,function*(){return new Promise((o,l)=>{e(n,yv(t,r,i,s)).then(a=>{if(!a.ok)throw a;return r!=null&&r.noResolveJson?a:a.json()}).then(a=>o(a)).catch(a=>gv(a,l))})})}function Ho(e,t,n,r){return Un(this,void 0,void 0,function*(){return ls(e,"GET",t,n,r)})}function ut(e,t,n,r,i){return Un(this,void 0,void 0,function*(){return ls(e,"POST",t,r,i,n)})}function wv(e,t,n,r,i){return Un(this,void 0,void 0,function*(){return ls(e,"PUT",t,r,i,n)})}function sh(e,t,n,r,i){return Un(this,void 0,void 0,function*(){return ls(e,"DELETE",t,r,i,n)})}var Te=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const _v={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class kv{constructor(t,n={},r,i){this.url=t,this.headers=n,this.bucketId=r,this.fetch=ih(i)}uploadOrUpdate(t,n,r,i){return Te(this,void 0,void 0,function*(){try{let s;const o=Object.assign(Object.assign({},yu),i),l=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.append("cacheControl",o.cacheControl)):(s=r,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType);const a=this._removeEmptyFolders(n),u=this._getFinalPath(a),c=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:s,headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{})),d=yield c.json();return c.ok?{data:{path:a,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(s){if(ae(s))return{data:null,error:s};throw s}})}upload(t,n,r){return Te(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,i){return Te(this,void 0,void 0,function*(){const s=this._removeEmptyFolders(t),o=this._getFinalPath(s),l=new URL(this.url+`/object/upload/sign/${o}`);l.searchParams.set("token",n);try{let a;const u=Object.assign({upsert:yu.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",u.cacheControl),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.append("cacheControl",u.cacheControl)):(a=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType);const d=yield this.fetch(l.toString(),{method:"PUT",body:a,headers:c}),f=yield d.json();return d.ok?{data:{path:s,fullPath:f.Key},error:null}:{data:null,error:f}}catch(a){if(ae(a))return{data:null,error:a};throw a}})}createSignedUploadUrl(t){return Te(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const r=yield ut(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:this.headers}),i=new URL(this.url+r.url),s=i.searchParams.get("token");if(!s)throw new Kl("No token returned by API");return{data:{signedUrl:i.toString(),path:t,token:s},error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}update(t,n,r){return Te(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n){return Te(this,void 0,void 0,function*(){try{return{data:yield ut(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}copy(t,n){return Te(this,void 0,void 0,function*(){try{return{data:{path:(yield ut(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n},{headers:this.headers})).Key},error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}createSignedUrl(t,n,r){return Te(this,void 0,void 0,function*(){try{let i=this._getFinalPath(t),s=yield ut(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return s={signedUrl:encodeURI(`${this.url}${s.signedURL}${o}`)},{data:s,error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}createSignedUrls(t,n,r){return Te(this,void 0,void 0,function*(){try{const i=yield ut(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),s=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${s}`):null})),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}download(t,n){return Te(this,void 0,void 0,function*(){const i=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),o=s?`?${s}`:"";try{const l=this._getFinalPath(t);return{data:yield(yield Ho(this.fetch,`${this.url}/${i}/${l}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(l){if(ae(l))return{data:null,error:l};throw l}})}getPublicUrl(t,n){const r=this._getFinalPath(t),i=[],s=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";s!==""&&i.push(s);const l=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});a!==""&&i.push(a);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${l}/public/${r}${u}`)}}}remove(t){return Te(this,void 0,void 0,function*(){try{return{data:yield sh(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}list(t,n,r){return Te(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},_v),n),{prefix:t||""});return{data:yield ut(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(ae(i))return{data:null,error:i};throw i}})}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const n=[];return t.width&&n.push(`width=${t.width}`),t.height&&n.push(`height=${t.height}`),t.resize&&n.push(`resize=${t.resize}`),t.format&&n.push(`format=${t.format}`),t.quality&&n.push(`quality=${t.quality}`),n.join("&")}}const Sv="2.5.5",Ev={"X-Client-Info":`storage-js/${Sv}`};var Xt=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class Cv{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},Ev),n),this.fetch=ih(r)}listBuckets(){return Xt(this,void 0,void 0,function*(){try{return{data:yield Ho(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(ae(t))return{data:null,error:t};throw t}})}getBucket(t){return Xt(this,void 0,void 0,function*(){try{return{data:yield Ho(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return Xt(this,void 0,void 0,function*(){try{return{data:yield ut(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return Xt(this,void 0,void 0,function*(){try{return{data:yield wv(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(ae(r))return{data:null,error:r};throw r}})}emptyBucket(t){return Xt(this,void 0,void 0,function*(){try{return{data:yield ut(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}deleteBucket(t){return Xt(this,void 0,void 0,function*(){try{return{data:yield sh(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(ae(n))return{data:null,error:n};throw n}})}}class xv extends Cv{constructor(t,n={},r){super(t,n,r)}from(t){return new kv(this.url,this.headers,t,this.fetch)}}const Pv="2.43.4";let Zn="";typeof Deno<"u"?Zn="deno":typeof document<"u"?Zn="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Zn="react-native":Zn="node";const Tv={"X-Client-Info":`supabase-js-${Zn}/${Pv}`},Ov={headers:Tv},Rv={schema:"public"},jv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Lv={};var Iv=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};const $v=e=>{let t;return e?t=e:typeof fetch>"u"?t=Vl:t=fetch,(...n)=>t(...n)},Nv=()=>typeof Headers>"u"?eh:Headers,Av=(e,t,n)=>{const r=$v(n),i=Nv();return(s,o)=>Iv(void 0,void 0,void 0,function*(){var l;const a=(l=yield t())!==null&&l!==void 0?l:e;let u=new i(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${a}`),r(s,Object.assign(Object.assign({},o),{headers:u}))})};function Uv(e){return e.replace(/\/$/,"")}function Dv(e,t){const{db:n,auth:r,realtime:i,global:s}=e,{db:o,auth:l,realtime:a,global:u}=t;return{db:Object.assign(Object.assign({},o),n),auth:Object.assign(Object.assign({},l),r),realtime:Object.assign(Object.assign({},a),i),global:Object.assign(Object.assign({},u),s)}}const oh="2.64.2",zv="http://localhost:9999",Fv="supabase.auth.token",Mv={"X-Client-Info":`gotrue-js/${oh}`},wu=10,Wo="X-Supabase-Api-Version",lh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function bv(e){return Math.round(Date.now()/1e3)+e}function Bv(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=Math.random()*16|0;return(e=="x"?t:t&3|8).toString(16)})}const Ue=()=>typeof document<"u",Lt={tested:!1,writable:!1},cr=()=>{if(!Ue())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Lt.tested)return Lt.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Lt.tested=!0,Lt.writable=!0}catch{Lt.tested=!0,Lt.writable=!1}return Lt.writable};function bs(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((i,s)=>{t[s]=i})}catch{}return n.searchParams.forEach((r,i)=>{t[i]=r}),t}const ah=e=>{let t;return e?t=e:typeof fetch>"u"?t=(...n)=>Rn(()=>Promise.resolve().then(()=>Ur),void 0,import.meta.url).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Vv=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",uh=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},ni=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Bs=async(e,t)=>{await e.removeItem(t)};function Hv(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let n="",r,i,s,o,l,a,u,c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)o=t.indexOf(e.charAt(c++)),l=t.indexOf(e.charAt(c++)),a=t.indexOf(e.charAt(c++)),u=t.indexOf(e.charAt(c++)),r=o<<2|l>>4,i=(l&15)<<4|a>>2,s=(a&3)<<6|u,n=n+String.fromCharCode(r),a!=64&&i!=0&&(n=n+String.fromCharCode(i)),u!=64&&s!=0&&(n=n+String.fromCharCode(s));return n}class as{constructor(){this.promise=new as.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}as.promiseConstructor=Promise;function _u(e){const t=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,n=e.split(".");if(n.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!t.test(n[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=n[1];return JSON.parse(Hv(r))}async function Wv(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function Kv(e,t){return new Promise((r,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{const o=await e(s);if(!t(s,null,o)){r(o);return}}catch(o){if(!t(s,o)){i(o);return}}})()})}function Qv(e){return("0"+e.toString(16)).substr(-2)}function Gv(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let i="";for(let s=0;s<56;s++)i+=n.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(t),Array.from(t,Qv).join("")}async function Jv(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),i=new Uint8Array(r);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}function qv(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Yv(e){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const n=await Jv(e);return qv(n)}async function Zt(e,t,n=!1){const r=Gv();let i=r;n&&(i+="/PASSWORD_RECOVERY"),await uh(e,`${t}-code-verifier`,i);const s=await Yv(r);return[s,r===s?"plain":"s256"]}const Xv=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Zv(e){const t=e.headers.get(Wo);if(!t||!t.match(Xv))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}class Ql extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function L(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class eg extends Ql{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function tg(e){return L(e)&&e.name==="AuthApiError"}class ch extends Ql{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class qt extends Ql{constructor(t,n,r,i){super(t,r,i),this.name=n,this.status=r}}class It extends qt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class Vs extends qt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ri extends qt{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class ii extends qt{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class ku extends qt{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ko extends qt{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Hs(e){return L(e)&&e.name==="AuthRetryableFetchError"}class Su extends qt{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}var ng=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};const At=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),rg=[502,503,504];async function Eu(e){var t;if(!Vv(e))throw new Ko(At(e),0);if(rg.includes(e.status))throw new Ko(At(e),e.status);let n;try{n=await e.json()}catch(s){throw new ch(At(s),s)}let r;const i=Zv(e);if(i&&i.getTime()>=lh["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new Su(At(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[])}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",!0))throw new Su(At(n),e.status,n.weak_password.reasons);throw new eg(At(n),e.status||500,r)}const ig=(e,t,n,r)=>{const i={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function N(e,t,n,r){var i;const s=Object.assign({},r==null?void 0:r.headers);s[Wo]||(s[Wo]=lh["2024-01-01"].name),r!=null&&r.jwt&&(s.Authorization=`Bearer ${r.jwt}`);const o=(i=r==null?void 0:r.query)!==null&&i!==void 0?i:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",a=await sg(e,t,n+l,{headers:s,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(a):{data:Object.assign({},a),error:null}}async function sg(e,t,n,r,i,s){const o=ig(t,r,i,s);let l;try{l=await e(n,Object.assign({},o))}catch(a){throw console.error(a),new Ko(At(a),0)}if(l.ok||await Eu(l),r!=null&&r.noResolveJson)return l;try{return await l.json()}catch(a){await Eu(a)}}function ot(e){var t;let n=null;ug(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=bv(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function Cu(e){const t=ot(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function ht(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function og(e){return{data:e,error:null}}function lg(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s}=e,o=ng(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s},a=Object.assign({},o);return{data:{properties:l,user:a},error:null}}function ag(e){return e}function ug(e){return e.access_token&&e.refresh_token&&e.expires_in}var cg=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n};class dg{constructor({url:t="",headers:n={},fetch:r}){this.url=t,this.headers=n,this.fetch=ah(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(t,n="global"){try{return await N(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(L(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await N(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:ht})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=cg(t,["options"]),i=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),await N(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:lg,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(L(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await N(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:ht})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,i,s,o,l,a;try{const u={nextPage:null,lastPage:0,total:0},c=await N(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=t==null?void 0:t.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:ag});if(c.error)throw c.error;const d=await c.json(),f=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,v=(a=(l=c.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&a!==void 0?a:[];return v.length>0&&(v.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);u[`${_}Page`]=y}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(L(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){try{return await N(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:ht})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await N(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:ht})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await N(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:ht})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await N(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:n,error:r}}catch(n){if(L(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await N(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(L(n))return{data:null,error:n};throw n}}}const hg={getItem:e=>cr()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{cr()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{cr()&&globalThis.localStorage.removeItem(e)}};function xu(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}function fg(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const en={debug:!!(globalThis&&cr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class dh extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class pg extends dh{}async function mg(e,t,n){en.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),en.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){en.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,i.name);try{return await n()}finally{en.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,i.name)}}else{if(t===0)throw en.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new pg(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(en.debug)try{const s=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(s,null," "))}catch(s){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",s)}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 n()}})}fg();const vg={url:zv,storageKey:Fv,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Mv,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Qn=30*1e3,Pu=3;async function Tu(e,t,n){return await n()}class jr{constructor(t){var n,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=jr.nextInstanceID,jr.nextInstanceID+=1,this.instanceID>0&&Ue()&&console.warn("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.");const i=Object.assign(Object.assign({},vg),t);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new dg({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ah(i.fetch),this.lock=i.lock||Tu,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Ue()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=mg:this.lock=Tu,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:cr()?this.storage=hg:(this.memoryStorage={},this.storage=xu(this.memoryStorage)):(this.memoryStorage={},this.storage=xu(this.memoryStorage)),Ue()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",s)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async s=>{this._debug("received broadcast notification from other tab or client",s),await this._notifyAllSubscribers(s.data.event,s.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${oh}) ${new Date().toISOString()}`,...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{const t=Ue()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",t),t||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:n,error:r}=await this._getSessionFromURL(t);if(r)return this._debug("#_initialize()","error detecting session from URL",r),(r==null?void 0:r.message)==="Identity is already linked"||(r==null?void 0:r.message)==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});const{session:i,redirectType:s}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",s),await this._saveSession(i),setTimeout(async()=>{s==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return L(t)?{error:t}:{error:new ch("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,i;try{await this._removeSession();const s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=t==null?void 0:t.options)===null||i===void 0?void 0:i.captchaToken}},xform:ot}),{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(L(s))return{data:{user:null,session:null},error:s};throw s}}async signUp(t){var n,r,i;try{await this._removeSession();let s;if("email"in t){const{email:c,password:d,options:f}=t;let v=null,g=null;this.flowType==="pkce"&&([v,g]=await Zt(this.storage,this.storageKey)),s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:c,password:d,data:(n=f==null?void 0:f.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:v,code_challenge_method:g},xform:ot})}else if("phone"in t){const{phone:c,password:d,options:f}=t;s=await N(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},channel:(i=f==null?void 0:f.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:ot})}else throw new ri("You must provide either an email or phone number and a password");const{data:o,error:l}=s;if(l||!o)return{data:{user:null,session:null},error:l};const a=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(s){if(L(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithPassword(t){try{await this._removeSession();let n;if("email"in t){const{email:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Cu})}else if("phone"in t){const{phone:s,password:o,options:l}=t;n=await N(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:Cu})}else throw new ri("You must provide either an email or phone number and a password");const{data:r,error:i}=n;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Vs}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(t){var n,r,i,s;return await this._removeSession(),await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=t.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=t.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const n=await ni(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(n??"").split("/"),{data:s,error:o}=await N(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:ot});return await Bs(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!s||!s.session||!s.user?{data:{user:null,session:null,redirectType:null},error:new Vs}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}async signInWithIdToken(t){await this._removeSession();try{const{options:n,provider:r,token:i,access_token:s,nonce:o}=t,l=await N(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:ot}),{data:a,error:u}=l;return u?{data:{user:null,session:null},error:u}:!a||!a.session||!a.user?{data:{user:null,session:null},error:new Vs}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:u})}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(t){var n,r,i,s,o;try{if(await this._removeSession(),"email"in t){const{email:l,options:a}=t;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await Zt(this.storage,this.storageKey));const{error:d}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:l,data:(n=a==null?void 0:a.data)!==null&&n!==void 0?n:{},create_user:(r=a==null?void 0:a.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:a==null?void 0:a.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in t){const{phone:l,options:a}=t,{data:u,error:c}=await N(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:l,data:(i=a==null?void 0:a.data)!==null&&i!==void 0?i:{},create_user:(s=a==null?void 0:a.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken},channel:(o=a==null?void 0:a.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c}}throw new ri("You must provide either an email or phone number.")}catch(l){if(L(l))return{data:{user:null,session:null},error:l};throw l}}async verifyOtp(t){var n,r;try{t.type!=="email_change"&&t.type!=="phone_change"&&await this._removeSession();let i,s;"options"in t&&(i=(n=t.options)===null||n===void 0?void 0:n.redirectTo,s=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:ot});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const a=o.session,u=o.user;return a!=null&&a.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:u,session:a},error:null}}catch(i){if(L(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(t){var n,r,i;try{await this._removeSession();let s=null,o=null;return this.flowType==="pkce"&&([s,o]=await Zt(this.storage,this.storageKey)),await N(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=t==null?void 0:t.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:s,code_challenge_method:o}),headers:this.headers,xform:og})}catch(s){if(L(s))return{data:null,error:s};throw s}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new It;const{error:i}=await N(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:i}})}catch(t){if(L(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{t.type!="email_change"&&t.type!="phone_change"&&await this._removeSession();const n=`${this.url}/resend`;if("email"in t){const{email:r,type:i,options:s}=t,{error:o}=await N(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},redirectTo:s==null?void 0:s.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in t){const{phone:r,type:i,options:s}=t,{data:o,error:l}=await N(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:l}}throw new ri("You must provide either an email or phone number and a type")}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await ni(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",t.expires_at),!r){if(this.storage.isServer){const o=this.suppressGetSessionWarning;t=new Proxy(t,{get(a,u,c){return!o&&u==="user"&&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 many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),Reflect.get(a,u,c)}})}return{data:{session:t},error:null}}const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{session:null},error:s}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:ht}):await this._useSession(async n=>{var r,i,s;const{data:o,error:l}=n;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new It}:await N(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:ht})})}catch(n){if(L(n))return{data:{user:null},error:n};throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:i,error:s}=r;if(s)throw s;if(!i.session)throw new It;const o=i.session;let l=null,a=null;this.flowType==="pkce"&&t.email!=null&&([l,a]=await Zt(this.storage,this.storageKey));const{data:u,error:c}=await N(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:l,code_challenge_method:a}),jwt:o.access_token,xform:ht});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(L(r))return{data:{user:null},error:r};throw r}}_decodeJWT(t){return _u(t)}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new It;const n=Date.now()/1e3;let r=n,i=!0,s=null;const o=_u(t.access_token);if(o.exp&&(r=o.exp,i=r<=n),i){const{session:l,error:a}=await this._callRefreshToken(t.refresh_token);if(a)return{data:{user:null,session:null},error:a};if(!l)return{data:{user:null,session:null},error:null};s=l}else{const{data:l,error:a}=await this._getUser(t.access_token);if(a)throw a;s={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return{data:{user:s.user,session:s},error:null}}catch(n){if(L(n))return{data:{session:null,user:null},error:n};throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:l}=n;if(l)throw l;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new It;const{session:i,error:s}=await this._callRefreshToken(t.refresh_token);return s?{data:{user:null,session:null},error:s}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(n){if(L(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t){try{if(!Ue())throw new ii("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ii("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!t)throw new ku("Not a valid PKCE flow url.");const n=bs(window.location.href);if(t){if(!n.code)throw new ku("No code detected.");const{data:h,error:m}=await this._exchangeCodeForSession(n.code);if(m)throw m;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:h.session,redirectType:null},error:null}}if(n.error||n.error_description||n.error_code)throw new ii(n.error_description||"Error in URL with unspecified error_description",{error:n.error||"unspecified_error",code:n.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:l,expires_at:a,token_type:u}=n;if(!s||!l||!o||!u)throw new ii("No session defined in URL");const c=Math.round(Date.now()/1e3),d=parseInt(l);let f=c+d;a&&(f=parseInt(a));const v=f-c;v*1e3<=Qn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${v}s, should have been closer to ${d}s`);const g=f-d;c-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,c):c-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,f,c);const{data:y,error:_}=await this._getUser(s);if(_)throw _;const p={provider_token:r,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:f,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:p,redirectType:n.type},error:null}}catch(n){if(L(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantFlow(){const t=bs(window.location.href);return!!(Ue()&&(t.access_token||t.error_description))}async _isPKCEFlow(){const t=bs(window.location.href),n=await ni(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{error:s};const o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:l}=await this.admin.signOut(o,t);if(l&&!(tg(l)&&(l.status===404||l.status===401||l.status===403)))return{error:l}}return t!=="others"&&(await this._removeSession(),await Bs(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(t){const n=Bv(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,i;try{const{data:{session:s},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",t,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(t))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",s),console.error(s)}})}async resetPasswordForEmail(t,n={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Zt(this.storage,this.storageKey,!0));try{return await N(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(s){if(L(s))return{data:null,error:s};throw s}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(n){if(L(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:i}=await this._useSession(async s=>{var o,l,a,u,c;const{data:d,error:f}=s;if(f)throw f;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(l=t.options)===null||l===void 0?void 0:l.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:!0});return await N(this.fetch,"GET",v,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(i)throw i;return Ue()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:t.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(L(r))return{data:{provider:t.provider,url:null},error:r};throw r}}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)throw o;return await N(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(i=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Kv(async i=>(i>0&&await Wv(200*Math.pow(2,i-1)),this._debug(n,"refreshing attempt",i),await N(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:ot})),(i,s)=>{const o=200*Math.pow(2,i);return s&&Hs(s)&&Date.now()+o-r<Qn})}catch(r){if(this._debug(n,"error",r),L(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(n,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,n){const r=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",n,"url",r),Ue()&&!n.skipBrowserRedirect&&window.location.assign(r),{data:{provider:t,url:r},error:null}}async _recoverAndRefresh(){var t;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const r=await ni(this.storage,this.storageKey);if(this._debug(n,"session from storage",r),!this._isValidSession(r)){this._debug(n,"session is not valid"),r!==null&&await this._removeSession();return}const i=Math.round(Date.now()/1e3),s=((t=r.expires_at)!==null&&t!==void 0?t:1/0)<i+wu;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${wu}s`),s){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Hs(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(n,"error",r),console.error(r);return}finally{this._debug(n,"end")}}async _callRefreshToken(t){var n,r;if(!t)throw new It;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${t.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new as;const{data:s,error:o}=await this._refreshAccessToken(t);if(o)throw o;if(!s.session)throw new It;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);const l={session:s.session,error:null};return this.refreshingDeferred.resolve(l),l}catch(s){if(this._debug(i,"error",s),L(s)){const o={session:null,error:s};return Hs(s)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(t,n,r=!0){const i=`#_notifyAllSubscribers(${t})`;this._debug(i,"begin",n,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:t,session:n});const s=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,n)}catch(a){s.push(a)}});if(await Promise.all(o),s.length>0){for(let l=0;l<s.length;l+=1)console.error(s[l]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0,await uh(this.storage,this.storageKey,t)}async _removeSession(){this._debug("#_removeSession()"),await Bs(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&Ue()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Qn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(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{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-t)/Qn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Qn}ms, refresh threshold is ${Pu} ticks`),i<=Pu&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof dh)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ue()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){const i=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[s,o]=await Zt(this.storage,this.storageKey),l=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(l.toString())}if(r!=null&&r.queryParams){const s=new URLSearchParams(r.queryParams);i.push(s.toString())}return r!=null&&r.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${i.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,i;const{data:s,error:o}=n;if(o)return{data:null,error:o};const{data:l,error:a}=await N(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:t.friendlyName,factor_type:t.factorType,issuer:t.issuer},headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(n){if(L(n))return{data:null,error:n};throw n}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return{data:null,error:s};const{data:o,error:l}=await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:l})})}catch(n){if(L(n))return{data:null,error:n};throw n}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?{data:null,error:s}:await N(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(L(n))return{data:null,error:n};throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?{data:null,error:r}:await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(t==null?void 0:t.factors)||[],i=r.filter(s=>s.factor_type==="totp"&&s.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var n,r;const{data:{session:i},error:s}=t;if(s)return{data:null,error:s};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const o=this._decodeJWT(i.access_token);let l=null;o.aal&&(l=o.aal);let a=l;((r=(n=i.user.factors)===null||n===void 0?void 0:n.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(a="aal2");const c=o.amr||[];return{data:{currentLevel:l,nextLevel:a,currentAuthenticationMethods:c},error:null}}))}}jr.nextInstanceID=0;const gg=jr;class yg extends gg{constructor(t){super(t)}}var wg=function(e,t,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function l(c){try{u(r.next(c))}catch(d){o(d)}}function a(c){try{u(r.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(l,a)}u((r=r.apply(e,t||[])).next())})};class _g{constructor(t,n,r){var i,s,o;if(this.supabaseUrl=t,this.supabaseKey=n,!t)throw new Error("supabaseUrl is required.");if(!n)throw new Error("supabaseKey is required.");const l=Uv(t);this.realtimeUrl=`${l}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${l}/auth/v1`,this.storageUrl=`${l}/storage/v1`,this.functionsUrl=`${l}/functions/v1`;const a=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:Rv,realtime:Lv,auth:Object.assign(Object.assign({},jv),{storageKey:a}),global:Ov},c=Dv(r??{},u);this.storageKey=(i=c.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(s=c.global.headers)!==null&&s!==void 0?s:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Av(n,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new Hl(`${l}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Bm(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new xv(this.storageUrl,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,n={},r={}){return this.rest.rpc(t,n,r)}channel(t,n={config:{}}){return this.realtime.channel(t,n)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,n;return wg(this,void 0,void 0,function*(){const{data:r}=yield this.auth.getSession();return(n=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&n!==void 0?n:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,storageKey:s,flowType:o,debug:l},a,u){var c;const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new yg({url:this.authUrl,headers:Object.assign(Object.assign({},d),a),storageKey:s,autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:i,flowType:o,debug:l,fetch:u,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(t){return new hv(this.realtimeUrl,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(t,n,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):t==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const kg=(e,t,n)=>new _g(e,t,n);function Sg(e){const t=Yd(),[n,r]=x.useState([]);x.useEffect(()=>{e.session||t("/login")},[e.session]);const i=x.useCallback(async()=>{const{data:s,error:o}=await e.supabase.from("file").select();if(o){console.error(o);return}r(s.map(l=>l))},[e.supabase]);return x.useEffect(()=>{i()},[]),D.jsx(D.Fragment,{children:D.jsxs("div",{children:[D.jsx("h1",{children:"Home"}),D.jsx("p",{children:"Logged in!"}),n.map(s=>D.jsx("div",{children:D.jsxs("p",{children:["file: ",s.absolute_path]})},s.id))]})})}function Eg(e){const t=Yd();return x.useEffect(()=>{window.HandleSignInWithGoogle=async r=>{await e.supabase.auth.signInWithIdToken({provider:"google",token:r.credential})},e.supabase.auth.getSession().then(({data:{session:r}})=>{e.setSession(r),console.log("LOGIN SESSION",r)});const{data:{subscription:n}}=e.supabase.auth.onAuthStateChange((r,i)=>{e.setSession(i),console.log("SESSION CHANGE",i)});return()=>n.unsubscribe()},[]),x.useEffect(()=>{e.session&&t("/")},[e.session]),D.jsxs(D.Fragment,{children:[D.jsxs("div",{children:[D.jsx("h1",{children:"Login"}),D.jsxs("p",{children:["Log in to access your account! ",JSON.stringify(e.session)]})]}),D.jsx("div",{id:"g_id_onload","data-client_id":"952965459060-nrnrsdoq22mf646vfa72hk410pvdda5q.apps.googleusercontent.com","data-context":"signin","data-ux_mode":"popup","data-callback":"HandleSignInWithGoogle","data-auto_prompt":"false"}),D.jsx("div",{className:"g_id_signin","data-type":"standard","data-shape":"pill","data-theme":"outline","data-text":"signin","data-size":"large","data-logo_alignment":"center"})]})}const Ou=kg("https://slpoocycjgqsuoedhkbn.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNscG9vY3ljamdxc3VvZWRoa2JuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTUyMDU0MjUsImV4cCI6MjAzMDc4MTQyNX0.xZYRTRN65rlms1Hb96IBAQvw3EGtMzUxlGPP5TVey34");function Cg(){const[e,t]=x.useState(null);return D.jsx(D.Fragment,{children:D.jsx(Nm,{children:D.jsx(Lm,{children:D.jsxs(Xn,{path:"/",children:[D.jsx(Xn,{index:!0,element:D.jsx(Sg,{supabase:Ou,session:e})}),D.jsx(Xn,{path:"login",element:D.jsx(Eg,{supabase:Ou,session:e,setSession:t})}),D.jsx(Xn,{path:"*",element:D.jsx("p",{children:"notfound"})})]})})})})}Ws.createRoot(document.getElementById("root")).render(D.jsx(Fu.StrictMode,{children:D.jsx(Cg,{})}));export{ph as g}; diff --git a/index.html b/index.html index 265427e..a8b8274 100644 --- a/index.html +++ b/index.html @@ -2,12 +2,12 @@ <html lang="en"> <head> <meta charset="UTF-8" /> - <link rel="icon" type="image/svg+xml" href="/vite.svg" /> + <link rel="icon" type="image/svg+xml" href="./vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React + TS</title> <script src="https://accounts.google.com/gsi/client" async></script> - <script type="module" crossorigin src="/assets/index-BsekK5hw.js"></script> - <link rel="stylesheet" crossorigin href="/assets/index-Bx9V9zN2.css"> + <script type="module" crossorigin src="./assets/index-ClZtce0o.js"></script> + <link rel="stylesheet" crossorigin href="./assets/index-Bx9V9zN2.css"> </head> <body> <div id="root"></div> |