UNPKG

future41-funnel-ui

Version:

Exact Future41 funnel widgets for React (extracted UI)

10 lines 112 kB
import {a,c,j as j$1,i,b as b$1,f,e}from'./chunk-ECOOEKJ6.js';var ht=a(ct=>{Object.defineProperty(ct,"__esModule",{value:true});var lt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code;}};ct.default=lt;});var dt=a(_e=>{var Nt=_e&&_e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_e,"__esModule",{value:true});var rs=Nt((j$1(),c(i))),ss=Nt(ht()),ut=class{constructor(e){this.shouldThrowOnError=false,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=rs.default:this.fetch=fetch;}throwOnError(){return this.shouldThrowOnError=true,this}setHeader(e,t){return this.headers=Object.assign({},this.headers),this.headers[e]=t,this}then(e,t){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");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let h=null,c=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=k:c=JSON.parse(k));}let w=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");w&&_&&_.length>1&&(u=parseInt(_[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(h={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,u=null,d=406,f="Not Acceptable"):c.length===1?c=c[0]:c=null);}else {let w=await n.text();try{h=JSON.parse(w),Array.isArray(h)&&n.status===404&&(c=[],h=null,d=200,f="OK");}catch{n.status===404&&w===""?(d=204,f="No Content"):h={message:w};}if(h&&this.isMaybeSingle&&(!((l=h?.details)===null||l===void 0)&&l.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new ss.default(h)}return {error:h,data:c,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;return {error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}returns(){return this}overrideTypes(){return this}};_e.default=ut;});var pt=a(ve=>{var is=ve&&ve.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ve,"__esModule",{value:true});var ns=is(dt()),ft=class extends ns.default{select(e){let t=false,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=true,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,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=true,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=false,verbose:t=false,settings:r=false,buffers:i=false,wal:n=false,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${l};`,o==="json"?this:this}rollback(){var e;return ((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};ve.default=ft;});var Me=a(me=>{var os=me&&me.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(me,"__esModule",{value:true});var as=os(pt()),gt=class extends as.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`);}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};me.default=gt;});var vt=a(ye=>{var ls=ye&&ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ye,"__esModule",{value:true});var we=ls(Me()),_t=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i;}select(e,{head:t=false,count:r}={}){let i=t?"HEAD":"GET",n=false,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new we.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:false})}insert(e,{count:t,defaultToNull:r=true}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","));}}return new we.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:false})}upsert(e,{onConflict:t,ignoreDuplicates:r=false,count:i,defaultToNull:n=true}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(l.length>0){let h=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",h.join(","));}}return new we.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:false})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new we.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:false})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new we.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:false})}};ye.default=_t;});var qt=a(Fe=>{Object.defineProperty(Fe,"__esModule",{value:true});Fe.version=void 0;Fe.version="0.0.0-automated";});var Bt=a(He=>{Object.defineProperty(He,"__esModule",{value:true});He.DEFAULT_HEADERS=void 0;var cs=qt();He.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${cs.version}`};});var Ft=a(be=>{var Mt=be&&be.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(be,"__esModule",{value:true});var hs=Mt(vt()),us=Mt(Me()),ds=Bt(),mt=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ds.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i;}from(e){let t=new URL(`${this.url}/${e}`);return new hs.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=false,get:i=false,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([c,u])=>u!==void 0).map(([c,u])=>[c,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([c,u])=>{a.searchParams.append(c,u);})):(o="POST",l=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new us.default({method:o,url:a,headers:h,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:false})}};be.default=mt;});var Vt=a(E=>{var ne=E&&E.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(E,"__esModule",{value:true});E.PostgrestError=E.PostgrestBuilder=E.PostgrestTransformBuilder=E.PostgrestFilterBuilder=E.PostgrestQueryBuilder=E.PostgrestClient=void 0;var Ht=ne(Ft());E.PostgrestClient=Ht.default;var Jt=ne(vt());E.PostgrestQueryBuilder=Jt.default;var Wt=ne(Me());E.PostgrestFilterBuilder=Wt.default;var zt=ne(pt());E.PostgrestTransformBuilder=zt.default;var Gt=ne(dt());E.PostgrestBuilder=Gt.default;var Kt=ne(ht());E.PostgrestError=Kt.default;E.default={PostgrestClient:Ht.default,PostgrestQueryBuilder:Jt.default,PostgrestFilterBuilder:Wt.default,PostgrestTransformBuilder:zt.default,PostgrestBuilder:Gt.default,PostgrestError:Kt.default};});var Zt=a((wi,Qt)=>{Qt.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")};});var Dt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>import('./browser-SUGEPLBN.js').then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var pe=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r;}},De=class extends pe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e);}},Ne=class extends pe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e);}},qe=class extends pe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e);}},Be;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2";})(Be||(Be={}));var ts=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})},ge=class{constructor(e,{headers:t={},customFetch:r,region:i=Be.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Dt(r);}setAuth(e){this.headers.Authorization=`Bearer ${e}`;}invoke(e,t={}){var r;return ts(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(v=>{throw new De(v)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new Ne(c);if(!c.ok)throw new qe(c);let d=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield c.json():d==="application/octet-stream"?f=yield c.blob():d==="text/event-stream"?f=c:d==="multipart/form-data"?f=yield c.formData():f=yield c.text(),{data:f,error:null}}catch(i){return {data:null,error:i}}})}};var Xt=b$1(Vt(),1),{PostgrestClient:Yt,PostgrestQueryBuilder:pi,PostgrestFilterBuilder:gi,PostgrestTransformBuilder:_i,PostgrestBuilder:vi,PostgrestError:fs}=Xt.default;var wt;typeof window>"u"?wt=Zt():wt=window.WebSocket;var er=wt;var tr="2.11.10";var rr={"X-Client-Info":`realtime-js/${tr}`},sr="1.0.0";var We=1e4,ir=1e3,H;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed";})(H||(H={}));var A;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving";})(A||(A={}));var I;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token";})(I||(I={}));var Je;(function(s){s.websocket="websocket";})(Je||(Je={}));var M;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed";})(M||(M={}));var ke=class{constructor(){this.HEADER_LENGTH=1;}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let l=r.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return {ref:null,topic:a,event:l,payload:h}}};var J=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t;}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));}};var b;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange";})(b||(b={}));var bt=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=ps(o,s,e,i),n),{})},ps=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?nr(n,o):yt(o)},nr=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return ms(e,t)}switch(s){case b.bool:return gs(e);case b.float4:case b.float8:case b.int2:case b.int4:case b.int8:case b.numeric:case b.oid:return _s(e);case b.json:case b.jsonb:return vs(e);case b.timestamp:return ws(e);case b.abstime:case b.date:case b.daterange:case b.int4range:case b.int8range:case b.money:case b.reltime:case b.text:case b.time:case b.timestamptz:case b.timetz:case b.tsrange:case b.tstzrange:return yt(e);default:return yt(e)}},yt=s=>s,gs=s=>{switch(s){case "t":return  true;case "f":return  false;default:return s}},_s=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},vs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},ms=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]");}catch{n=o?o.split(","):[];}return n.map(a=>nr(e,a))}return s},ws=s=>typeof s=="string"?s.replace(" ","T"):s,ze=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var W=class{constructor(e,t,r={},i=We){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=false,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null;}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=false,this.send();}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=true,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}));}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e);}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t);};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{});},this.timeout);}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t});}destroy(){this._cancelRefEvent(),this._cancelTimeout();}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{});}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0;}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t));}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var kt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave";})(kt||(kt={}));var oe=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=s.syncDiff(this.state,l,n,o);}),this.pendingDiffs=[],a();}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a());}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o});}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o});}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"});});}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(h,c)=>{o[h]||(l[h]=c);}),this.map(o,(h,c)=>{let u=n[h];if(u){let d=c.map(_=>_.presence_ref),f=u.map(_=>_.presence_ref),v=c.filter(_=>f.indexOf(_.presence_ref)<0),w=u.filter(_=>d.indexOf(_.presence_ref)<0);v.length>0&&(a[h]=v),w.length>0&&(l[h]=w);}else a[h]=c;}),this.syncDiff(n,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var h;let c=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(l),c.length>0){let u=e[a].map(f=>f.presence_ref),d=c.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d);}r(a,c,l);}),this.map(o,(a,l)=>{let h=e[a];if(!h)return;let c=l.map(u=>u.presence_ref);h=h.filter(u=>c.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,l),h.length===0&&delete e[a];}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return "metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e;}onLeave(e){this.caller.onLeave=e;}onSync(e){this.caller.onSync=e;}inPendingSyncState(){return !this.joinRef||this.joinRef!==this.channel._joinRef()}};var St;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE";})(St||(St={}));var xt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system";})(xt||(xt={}));var U;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR";})(U||(U={}));var ae=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=A.closed,this.joinedOnce=false,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:false,self:false},presence:{key:""},private:false},t.config),this.timeout=this.socket.timeout,this.joinPush=new W(this,I.join,this.params,this.timeout),this.rejoinTimer=new J(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=A.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=A.closed,this.socket._remove(this);}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=A.errored,this.rejoinTimer.scheduleTimeout());}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=A.errored,this.rejoinTimer.scheduleTimeout());}),this._on(I.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i);}),this.presence=new oe(this),this.broadcastEndpointURL=ze(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||false;}subscribe(e,t=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";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(c=>e?.(U.CHANNEL_ERROR,c)),this._onClose(()=>e?.(U.CLOSED));let l={},h={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(c=>c.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessTokenValue&&(l.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:h},l)),this.joinedOnce=true,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:c})=>{var u;if(this.socket.setAuth(),c===void 0){e?.(U.SUBSCRIBED);return}else {let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,v=[];for(let w=0;w<f;w++){let _=d[w],{filter:{event:k,schema:O,table:p,filter:y}}=_,T=c&&c[w];if(T&&T.event===k&&T.schema===O&&T.table===p&&T.filter===y)v.push(Object.assign(Object.assign({},_),{id:T.id}));else {this.unsubscribe(),this.state=A.errored,e?.(U.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e(U.SUBSCRIBED);return}}).receive("error",c=>{this.state=A.errored,e?.(U.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(c).join(", ")||"error")));}).receive("timeout",()=>{e?.(U.TIMED_OUT);});}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{let h=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=h.body)===null||i===void 0?void 0:i.cancel()),h.ok?"ok":"error"}catch(h){return h.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"));})}updateJoinPayload(e){this.joinPush.updatePayload(e);}unsubscribe(e=this.timeout){this.state=A.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(I.close,"leave",this._joinRef());};return this.joinPush.destroy(),new Promise(r=>{let i=new W(this,I.leave,{},e);i.receive("ok",()=>{t(),r("ok");}).receive("timeout",()=>{t(),r("timed out");}).receive("error",()=>{r("error");}),i.send(),this._canPush()||i.trigger("ok",{});})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy();}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw `tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new W(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:h,join:c}=I;if(r&&[a,l,h,c].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)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(f=>{var v,w,_;return ((v=f.filter)===null||v===void 0?void 0:v.event)==="*"||((_=(w=f.filter)===null||w===void 0?void 0:w.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var v,w,_,k,O,p;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let y=f.id,T=(v=f.filter)===null||v===void 0?void 0:v.event;return y&&((w=t.ids)===null||w===void 0?void 0:w.includes(y))&&(T==="*"||T?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else {let y=(O=(k=f?.filter)===null||k===void 0?void 0:k.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return y==="*"||y===((p=t?.event)===null||p===void 0?void 0:p.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let v=d.data,{schema:w,table:_,commit_timestamp:k,type:O,errors:p}=v;d=Object.assign(Object.assign({},{schema:w,table:_,commit_timestamp:k,eventType:O,new:{},old:{},errors:p}),this._getPayloadRecords(v));}f.callback(d,r);});}_isClosed(){return this.state===A.closed}_isJoined(){return this.state===A.joined}_isJoining(){return this.state===A.joining}_isLeaving(){return this.state===A.leaving}_replyEventName(e){return `chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return !(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return  false;for(let r in e)if(e[r]!==t[r])return  false;return  true}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin();}_onClose(e){this._on(I.close,{},e);}_onError(e){this._on(I.error,{},t=>e(t));}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=A.joining,this.joinPush.resend(e));}_getPayloadRecords(e){let t={new:{},old:{}};return (e.type==="INSERT"||e.type==="UPDATE")&&(t.new=bt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=bt(e.columns,e.old_record)),t}};var or=()=>{},bs=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`,le=class{constructor(e,t){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=rr,this.params={},this.timeout=We,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=or,this.ref=0,this.logger=or,this.conn=null,this.sendBuffer=[],this.serializer=new ke,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>import('./browser-SUGEPLBN.js').then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Je.websocket}`,this.httpEndpoint=ze(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),(t?.logLevel||t?.log_level)&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;if(i&&(this.accessTokenValue=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new J(async()=>{this.disconnect(),this.connect();},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch),t?.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=t?.worker||false,this.workerUrl=t?.workerUrl;}this.accessToken=t?.accessToken||null;}connect(){if(!this.conn){if(this.transport||(this.transport=er),this.transport){typeof window<"u"&&this.transport===window.WebSocket?this.conn=new this.transport(this.endpointURL()):this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection();return}this.conn=new Et(this.endpointURL(),void 0,{close:()=>{this.conn=null;}});}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:sr}))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(r=>r.teardown()));}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels=this.channels.filter(r=>r._joinRef!==e._joinRef),this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r);}connectionState(){switch(this.conn&&this.conn.readyState){case H.connecting:return M.Connecting;case H.open:return M.Open;case H.closing:return M.Closing;default:return M.Closed}}isConnected(){return this.connectionState()===M.Open}channel(e,t={config:{}}){let r=`realtime:${e}`,i=this.getChannels().find(n=>n.topic===r);if(i)return i;{let n=new ae(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a);});};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o);}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(r=>{t&&r.updateJoinPayload({access_token:t,version:this.headers&&this.headers["X-Client-Info"]}),r.joinedOnce&&r._isJoined()&&r._push(I.access_token,{access_token:t});}));}async sendHeartbeat(){var e;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(e=this.conn)===null||e===void 0||e.close(ir,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth();}onHeartbeat(e){this.heartbeatCallback=e;}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[]);}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe());}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic);}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e));}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;r==="phoenix"&&i==="phx_reply"&&this.heartbeatCallback(t.payload.status=="ok"?"ok":"error"),o&&o===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),Array.from(this.channels).filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t));});}_onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else {this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate();},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat();},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs});}this.stateChangeCallbacks.open.forEach(e=>e());}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e));}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e));}_triggerChanError(){this.channels.forEach(e=>e._trigger(I.error));}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return `${e}${r}${i}`}_workerObjectUrl(e){let t;if(e)t=e;else {let r=new Blob([bs],{type:"application/javascript"});t=URL.createObjectURL(r);}return t}},Et=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=H.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close;}};var ce=class extends Error{constructor(e){super(e),this.__isStorageError=true,this.name="StorageError";}};function x(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Ge=class extends ce{constructor(e,t){super(e),this.name="StorageApiError",this.status=t;}toJSON(){return {name:this.name,message:this.message,status:this.status}}},z=class extends ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t;}};var ks=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})},Ve=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>import('./browser-SUGEPLBN.js').then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},ar=()=>ks(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield import('./browser-SUGEPLBN.js')).Response:Response}),Ke=s=>{if(Array.isArray(s))return s.map(t=>Ke(t));if(typeof s=="function"||s!==Object(s))return s;let e={};return Object.entries(s).forEach(([t,r])=>{let i=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[i]=Ke(r);}),e};var G=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})},Tt=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Ss=(s,e,t)=>G(void 0,void 0,void 0,function*(){let r=yield ar();s instanceof r&&!t?.noResolveJson?s.json().then(i=>{e(new Ge(Tt(i),s.status||500));}).catch(i=>{e(new z(Tt(i),i));}):e(new z(Tt(s),s));}),xs=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r&&(i.body=JSON.stringify(r)),Object.assign(Object.assign({},i),t))};function Se(s,e,t,r,i,n){return G(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,xs(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Ss(l,a,r));})})}function he(s,e,t,r){return G(this,void 0,void 0,function*(){return Se(s,"GET",e,t,r)})}function L(s,e,t,r,i){return G(this,void 0,void 0,function*(){return Se(s,"POST",e,r,i,t)})}function lr(s,e,t,r,i){return G(this,void 0,void 0,function*(){return Se(s,"PUT",e,r,i,t)})}function cr(s,e,t,r){return G(this,void 0,void 0,function*(){return Se(s,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:true}),r)})}function Xe(s,e,t,r,i){return G(this,void 0,void 0,function*(){return Se(s,"DELETE",e,r,i,t)})}var j=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})},Es={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},hr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:false},xe=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Ve(i);}uploadOrUpdate(e,t,r,i){return j(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},hr),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l)),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l))):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),i?.headers&&(a=Object.assign(Object.assign({},a),i.headers));let h=this._removeEmptyFolders(t),c=this._getFinalPath(h),u=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:h,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(x(n))return {data:null,error:n};throw n}})}upload(e,t,r){return j(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return j(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l,h=Object.assign({upsert:hr.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",h.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",h.cacheControl)):(l=r,c["cache-control"]=`max-age=${h.cacheControl}`,c["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(l){if(x(l))return {data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return j(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield L(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ce("No token returned by API");return {data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(x(r))return {data:null,error:r};throw r}})}update(e,t,r){return j(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return j(this,void 0,void 0,function*(){try{return {data:yield L(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(x(i))return {data:null,error:i};throw i}})}copy(e,t,r){return j(this,void 0,void 0,function*(){try{return {data:{path:(yield L(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(x(i))return {data:null,error:i};throw i}})}createSignedUrl(e,t,r){return j(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield L(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(x(i))return {data:null,error:i};throw i}})}createSignedUrls(e,t,r){return j(this,void 0,void 0,function*(){try{let i=yield L(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=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}${n}`):null})),error:null}}catch(i){if(x(i))return {data:null,error:i};throw i}})}download(e,t){return j(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return {data:yield (yield he(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(x(a))return {data:null,error:a};throw a}})}info(e){return j(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let r=yield he(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return {data:Ke(r),error:null}}catch(r){if(x(r))return {data:null,error:r};throw r}})}exists(e){return j(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield cr(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(x(r)&&r instanceof z){let i=r.originalError;if([400,404].includes(i?.status))return {data:false,error:r}}throw r}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===true?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return j(this,void 0,void 0,function*(){try{return {data:yield Xe(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(x(t))return {data:null,error:t};throw t}})}list(e,t,r){return j(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Es),t),{prefix:e||""});return {data:yield L(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(x(i))return {data:null,error:i};throw i}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return `${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var ur="2.7.1";var dr={"X-Client-Info":`storage-js/${ur}`};var ue=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})},Ee=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},dr),t),this.fetch=Ve(r);}listBuckets(){return ue(this,void 0,void 0,function*(){try{return {data:yield he(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(x(e))return {data:null,error:e};throw e}})}getBucket(e){return ue(this,void 0,void 0,function*(){try{return {data:yield he(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(x(t))return {data:null,error:t};throw t}})}createBucket(e,t={public:false}){return ue(this,void 0,void 0,function*(){try{return {data:yield L(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(x(r))return {data:null,error:r};throw r}})}updateBucket(e,t){return ue(this,void 0,void 0,function*(){try{return {data:yield lr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(x(r))return {data:null,error:r};throw r}})}emptyBucket(e){return ue(this,void 0,void 0,function*(){try{return {data:yield L(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(x(t))return {data:null,error:t};throw t}})}deleteBucket(e){return ue(this,void 0,void 0,function*(){try{return {data:yield Xe(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(x(t))return {data:null,error:t};throw t}})}};var Te=class extends Ee{constructor(e,t={},r){super(e,t,r);}from(e){return new xe(this.url,this.headers,e,this.fetch)}};var fr="2.50.0";var Ae="";typeof Deno<"u"?Ae="deno":typeof document<"u"?Ae="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ae="react-native":Ae="node";var Ts={"X-Client-Info":`supabase-js-${Ae}/${fr}`},pr={headers:Ts},gr={schema:"public"},_r={autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,flowType:"implicit"},vr={};j$1();var As=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})},Os=s=>{let e$1;return s?e$1=s:typeof fetch>"u"?e$1=e:e$1=fetch,(...t)=>e$1(...t)},js=()=>typeof Headers>"u"?f:Headers,mr=(s,e,t)=>{let r=Os(t),i=js();return (n,o)=>As(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:s,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",s),h.has("Authorization")||h.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};var Rs=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})};function wr(s){return s.endsWith("/")?s:s+"/"}function yr(s,e){var t,r;let{db:i,auth:n,realtime:o,global:a}=s,{db:l,auth:h,realtime:c,global:u}=e,d={db:Object.assign(Object.assign({},l),i),auth:Object.assign(Object.assign({},h),n),realtime:Object.assign(Object.assign({},c),o),global:Object.assign(Object.assign(Object.assign({},u),a),{headers:Object.assign(Object.assign({},(t=u?.headers)!==null&&t!==void 0?t:{}),(r=a?.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>Rs(this,void 0,void 0,function*(){return ""})};return s.accessToken?d.accessToken=s.accessToken:delete d.accessToken,d}var Ye="2.70.0";var K=30*1e3,Qe=3,Ze=Qe*K,br="http://localhost:9999",kr="supabase.auth.token";var Sr={"X-Client-Info":`gotrue-js/${Ye}`};var Oe="X-Supabase-Api-Version",At={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},xr=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Er=6e5;var je=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=true,this.name="AuthError",this.status=t,this.code=r;}};function g(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var et=class extends je{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r;}};function Tr(s){return g(s)&&s.name==="AuthApiError"}var de=class extends je{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t;}},D=class extends je{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r;}},P=class extends D{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0);}};function Ar(s){return g(s)&&s.name==="AuthSessionMissingError"}var V=class extends D{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0);}},X=class extends D{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0);}},Y=class extends D{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t;}toJSON(){return {name:this.name,message:this.message,status:this.status,details:this.details}}};function Or(s){return g(s)&&s.name==="AuthImplicitGrantRedirectError"}var Re=class extends D{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t;}toJSON(){return {name:this.name,message:this.message,status:this.status,details:this.details}}},fe=class extends D{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0);}};function tt(s){return g(s)&&s.name==="AuthRetryableFetchError"}var Ie=class extends D{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r;}};var B=class extends D{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt");}};var rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),jr=` 	
\r=`.split(""),Is=(()=>{let s=new Array(128);for(let e=0;e<s.length;e+=1)s[e]=-1;for(let e=0;e<jr.length;e+=1)s[jr[e].charCodeAt(0)]=-2;for(let e=0;e<rt.length;e+=1)s[rt[e].charCodeAt(0)]=e;return s})();function Rr(s,e,t){if(s!==null)for(e.queue=e.queue<<8|s,e.queuedBits+=8;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(rt[r]),e.queuedBits-=6;}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let r=e.queue>>e.queuedBits-6&63;t(rt[r]),e.queuedBits-=6;}}function Ir(s,e,t){let r=Is[s];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else {if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function Ot(s){let e=[],t=o=>{e.push(String.fromCodePoint(o));},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=o=>{$s(o,r,t);};for(let o=0;o<s.length;o+=1)Ir(s.charCodeAt(o),i,n);return e.join("")}function Ps(s,e){if(s<=127){e(s);return}else if(s<=2047){e(192|s>>6),e(128|s&63);return}else if(s<=65535){e(224|s>>12),e(128|s>>6&63),e(128|s&63);return}else if(s<=1114111){e(240|s>>18),e(128|s>>12&63),e(128|s>>6&63),e(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function Cs(s,e){for(let t=0;t<s.length;t+=1){let r=s.charCodeAt(t);if(r>55295&&r<=56319){let i=(r-55296)*1024&65535;r=(s.charCodeAt(t+1)-56320&65535|i)+65536,t+=1;}Ps(r,e);}}function $s(s,e,t){if(e.utf8seq===0){if(s<=127){t(s);return}for(let r=1;r<6;r+=1)if((s>>7-r&1)===0){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=s&31;else if(e.utf8seq===3)e.codepoint=s&15;else if(e.utf8seq===4)e.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1;}else if(e.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|s&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint);}}function Pr(s){let e=[],t={queue:0,queuedBits:0},r=i=>{e.push(i);};for(let i=0;i<s.length;i+=1)Ir(s.charCodeAt(i),t,r);return new Uint8Array(e)}function Cr(s){let e=[];return Cs(s,t=>e.push(t)),new Uint8Array(e)}function $r(s){let e=[],t={queue:0,queuedBits:0},r=i=>{e.push(i);};return s.forEach(i=>Rr(i,t,r)),Rr(null,t,r),e.join("")}function Ur(s){return Math.round(Date.now()/1e3)+s}function Lr(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return (s=="x"?e:e&3|8).toString(16)})}var C=()=>typeof window<"u"&&typeof document<"u",Q={tested:false,writable:false},F=()=>{if(!C())return  false;try{if(typeof globalThis.localStorage!="object")return !1}catch{return  false}if(Q.tested)return Q.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Q.tested=!0,Q.writable=!0;}catch{Q.tested=true,Q.writable=false;}return Q.writable};function Dr(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i;});}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r;}),e}var st=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>import('./browser-SUGEPLBN.js').then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Nr=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",jt=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t));},Ce=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},$e=async(s,e)=>{await s.removeItem(e);},Pe=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t;});}};Pe.promiseConstructor=Promise;function it(s){let e=s.split(".");if(e.length!==3)throw new B("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!xr.test(e[r]))throw new B("JWT not in base64url format");return {header:JSON.parse(Ot(e[0])),payload:JSON.parse(Ot(e[1])),signature:Pr(e[2]),raw:{header:e[0],payload:e[1]}}}async function qr(s){return await new Promise(e=>{setTimeout(()=>e(null),s);})}function Br(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})();})}function Us(s){return ("0"+s.toString(16)).substr(-2)}function Ls(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Us).join("")}async function Ds(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}async function Ns(s){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."),s;let t=await Ds(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Z(s,e,t=false){let r=Ls(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await jt(s,`${e}-code-verifier`,i);let n=await Ns(r);return [n,r===n?"plain":"s256"]}var qs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Mr(s){let e=s.headers.get(Oe);if(!e||!e.match(qs))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Fr(s){if(!s)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(s<=e)throw new Error("JWT has expired")}function Hr(s){switch(s){case "RS256":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case "ES256":return {name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ee(s){if(!Bs.test(s))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}var Ms=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},te=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Fs=[502,503,504];async function Jr(s){var e;if(!Nr(s))throw new fe(te(s),0);if(Fs.includes(s.status))throw new fe(te(s),s.status);let t;try{t=await s.json();}catch(n){throw new de(te(n),n)}let r,i=Mr(s);if(i&&i.getTime()>=At["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Ie(te(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new P}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",true))throw new Ie(te(t),s.status,t.weak_password.reasons);throw new et(te(t),s.status||500,r)}var Hs=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function m(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Oe]||(n[Oe]=At["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Js(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function Js(s,e,t,r,i,n){let o=Hs(e,r,i,n),a;try{a=await s(t,Object.assign({},o));}catch(l){throw console.error(l),new fe(te(l),0)}if(a.ok||await Jr(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await Jr(l);}}function N(s){var e;let t=null;Ws(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ur(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return {data:{session:t,user:r},error:null}}function Rt(s){let e=N(s);return !e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",true)&&(e.data.weak_password=s.weak_password),e}function q(s){var e;return {data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Wr(s){return {data:s,error:null}}function zr(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Ms(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},l=Object.assign({},o);return {data:{properties:a,user:l},error:null}}function Gr(s){return s}function Ws(s){return s.access_token&&s.refresh_token&&s.expires_in}var nt=["global","local","others"];var zs=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},re=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=st(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)};}async signOut(e,t=nt[0]){if(nt.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${nt.join(", ")}`);try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(g(r))return {data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:q})}catch(r){if(g(r))return {data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=zs(e,["options"]),i=Object.assign(Object.assign({},r),t);return "newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:zr,redirectTo:t?.redirectTo})}catch(t){if(g(t))return {data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:q})}catch(t){if(g(t))return {data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,l;try{let h={nextPage:null,lastPage:0,total:0},c=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Gr});if(c.error)throw c.error;let u=await c.json(),d=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(v=>{let w=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(v.split(";")[1].split("=")[1]);h[`${_}Page`]=w;}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(g(h))return {data:{users:[]},error:h};throw h}}async getUserById(e){ee(e);try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:q})}catch(t){if(g(t))return {data:{user:null},error:t};throw t}}async updateUserById(e,t){ee(e);try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:q})}catch(r){if(g(r))return {data:{user:null},error:r};throw r}}async deleteUser(e,t=false){ee(e);try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:q})}catch(r){if(g(r))return {data:{user:null},error:r};throw r}}async _listFactors(e){ee(e.userId);try{let{data:t,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return {data:t,error:r}}catch(t){if(g(t))return {data:null,error:t};throw t}}async _deleteFactor(e){ee(e.userId),ee(e.id);try{return {data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(g(t))return {data:null,error:t};throw t}}};var Kr={getItem:s=>F()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{F()&&globalThis.localStorage.setItem(s,e);},removeItem:s=>{F()&&globalThis.localStorage.removeItem(s);}};function It(s={}){return {getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t;},removeItem:e=>{delete s[e];}}}function Vr(){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);}}var se={debug:!!(globalThis&&F()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ue=class extends Error{constructor(e){super(e),this.isAcquireTimeout=true;}},ot=class extends Ue{};async function Pt(s,e,t){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),se.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s);},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:true}:{mode:"exclusive",signal:r.signal},async i=>{if(i){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{se.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name);}}else {if(e===0)throw se.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ot(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(se.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null,"  "));}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n);}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 t()}}))}Vr();var Gs={url:br,storageKey:kr,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:Sr,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false};async function Xr(s,e,t){return await t()}var ie=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=true,this.hasCustomAuthorizationHeader=false,this.suppressGetSessionWarning=false,this.lockAcquired=false,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&C()&&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.");let i=Object.assign(Object.assign({},Gs),e);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 re({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=st(i.fetch),this.lock=i.lock||Xr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:C()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Pt:this.lock=Xr,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:F()?this.storage=Kr:(this.memoryStorage={},this.storage=It(this.memoryStorage)):(this.memoryStorage={},this.storage=It(this.memoryStorage)),C()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey);}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n);}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,false);});}this.initialize();}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Ye}) ${new Date().toISOString()}`,...e),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(){var e;try{let t=Dr(window.location.href),r="none";if(this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce"),C()&&this.detectSessionInUrl&&r!=="none"){let{data:i,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),Or(n)){let l=(e=n.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return {error:n}}return await this._removeSession(),{error:n}}let{session:o,redirectType:a}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o);},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return g(t)?{error:t}:{error:new de("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end");}}async signInAnonymously(e){var t,r,i;try{let n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:N}),{data:o,error:a}=n;if(a||!o)return {data:{user:null,session:null},error:a};let l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(g(n))return {data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:c,password:u,options:d}=e,f=null,v=null;this.flowType==="pkce"&&([f,v]=await Z(this.storage,this.storageKey)),n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:c,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:v},xform:N});}else if("phone"in e){let{phone:c,password:u,options:d}=e;n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:N});}else throw new X("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return {data:{user:null,session:null},error:a};let l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(g(n))return {data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Rt});}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await m(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Rt});}else throw new X("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new V}:(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(t){if(g(t))return {data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;if(t==="solana")return await this.signInWithSolana(e);throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}async signInWithSolana(e){var t,r,i,n,o,a,l,h,c,u,d,f;let v,w;if("message"in e)v=e.message,w=e.signature;else {let{chain:_,wallet:k,statement:O,options:p}=e,y;if(C())if(typeof k=="object")y=k;else {let S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))y=S.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else {if(typeof k!="object"||!p?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=k;}let T=new URL((t=p?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in y&&y.signIn){let S=await y.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},p?.signInWithSolana),{version:"1",domain:T.host,uri:T.href}),O?{statement:O}:null)),R;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")R=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)R=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in R&&"signature"in R&&(typeof R.signedMessage=="string"||R.signedMessage instanceof Uint8Array)&&R.signature instanceof Uint8Array)v=typeof R.signedMessage=="string"?R.signedMessage:new TextDecoder().decode(R.signedMessage),w=R.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else {if(!("signMessage"in y)||typeof y.signMessage!="function"||!("publicKey"in y)||typeof y!="object"||!y.publicKey||!("toBase58"in y.publicKey)||typeof y.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");v=[`${T.host} wants you to sign in with your Solana account:`,y.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${T.href}`,`Issued At: ${(i=(r=p?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((n=p?.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${p.signInWithSolana.notBefore}`]:[],...!((o=p?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${p.signInWithSolana.expirationTime}`]:[],...!((a=p?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${p.signInWithSolana.chainId}`]:[],...!((l=p?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${p.signInWithSolana.nonce}`]:[],...!((h=p?.signInWithSolana)===null||h===void 0)&&h.requestId?[`Request ID: ${p.signInWithSolana.requestId}`]:[],...!((u=(c=p?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||u===void 0)&&u.length?["Resources",...p.signInWithSolana.resources.map(R=>`- ${R}`)]:[]].join(`
`);let S=await y.signMessage(new TextEncoder().encode(v),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");w=S;}}try{let{data:_,error:k}=await m(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:v,signature:$r(w)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:N});if(k)throw k;return !_||!_.session||!_.user?{data:{user:null,session:null},error:new V}:(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),{data:Object.assign({},_),error:k})}catch(_){if(g(_))return {data:{user:null,session:null},error:_};throw _}}async _exchangeCodeForSession(e){let t=await Ce(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/");try{let{data:n,error:o}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:N});if(await $e(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return !n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new V}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}catch(n){if(g(n))return {data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:N}),{data:l,error:h}=a;return h?{data:{user:null,session:null},error:h}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new V}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:h})}catch(t){if(g(t))return {data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:l}=e,h=null,c=null;this.flowType==="pkce"&&([h,c]=await Z(this.storage,this.storageKey));let{error:u}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:h,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return {data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:h,error:c}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return {data:{user:null,session:null,messageId:h?.message_id},error:c}}throw new X("You must provide either an email or phone number.")}catch(a){if(g(a))return {data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:N});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,h=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(i){if(g(i))return {data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Z(this.storage,this.storageKey)),await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Wr})}catch(n){if(g(n))return {data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new P;let{error:i}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return {data:{user:null,session:null},error:i}})}catch(e){if(g(e))return {data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await m(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return {data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await m(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return {data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new X("You must provide either an email or phone number and a type")}catch(t){if(g(t))return {data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i;}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r;}catch{}})()),await r;this.pendingInLock.length;){let 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(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end");}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ce(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return {data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()<Ze:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,h,c)=>(!o&&h==="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 may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,h,c))});}return {data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end");}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:q}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return !(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new P}:await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:q})})}catch(t){if(g(t))return Ar(t)&&(await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new P;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Z(this.storage,this.storageKey));let{data:h,error:c}=await m(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:q});if(c)throw c;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(g(r))return {data:{user:null},error:r};throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new P;let t=Date.now()/1e3,r=t,i=!0,n=null,{payload:o}=it(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return {data:{user:null,session:null},error:l};if(!a)return {data:{user:null,session:null},error:null};n=a;}else {let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n);}return {data:{user:n.user,session:n},error:null}}catch(t){if(g(t))return {data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0;}if(!e?.refresh_token)throw new P;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(g(t))return {data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!C())throw new Y("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Y(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case "implicit":if(this.flowType==="pkce")throw new Re("Not a valid PKCE flow url.");break;case "pkce":if(this.flowType==="implicit")throw new Y("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Re("No code detected.");let{data:O,error:p}=await this._exchangeCodeForSession(e.code);if(p)throw p;let y=new URL(window.location.href);return y.searchParams.delete("code"),window.history.replaceState(window.history.state,"",y.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:h}=e;if(!n||!a||!o||!h)throw new Y("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),d=c+u;l&&(d=parseInt(l));let f=d-c;f*1e3<=K&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let v=d-u;c-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,d,c):c-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,d,c);let{data:w,error:_}=await this._getUser(n);if(_)throw _;let k={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:e.type},error:null}}catch(r){if(g(r))return {data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(e){return !!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await Ce(this.storage,`${this.storageKey}-code-verifier`);return !!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return {error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Tr(a)&&(a.status===404||a.status===401||a.status===403)))return {error:a}}return e!=="others"&&(await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=Lr(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t);}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t);})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n);}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n);}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Z(this.storage,this.storageKey,true));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(g(n))return {data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return {data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(g(t))return {data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,l,h,c;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await m(this.fetch,"GET",f,{headers:this.headers,jwt:(c=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&c!==void 0?c:void 0})});if(i)throw i;return C()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(g(r))return {data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(g(t))return {data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Br(async i=>(i>0&&await qr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:N})),(i,n)=>{let o=200*Math.pow(2,i);return n&&tt(n)&&Date.now()+o-r<K})}catch(r){if(this._debug(t,"error",r),g(r))return {data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end");}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),C()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ce(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=((e=r.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<Ze;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${Ze}s`),i){if(this.autoRefreshToken&&r.refresh_token){let{error:n}=await this._callRefreshToken(r.refresh_token);n&&(console.error(n),tt(n)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",n),await this._removeSession()));}}else await this._notifyAllSubscribers("SIGNED_IN",r);}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end");}}async _callRefreshToken(e){var t,r;if(!e)throw new P;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Pe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new P;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),g(n)){let o={session:null,error:n};return tt(n)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw (r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end");}}async _notifyAllSubscribers(e,t,r=true){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t);}catch(l){n.push(l);}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end");}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=true,await jt(this.storage,this.storageKey,e);}async _removeSession(){this._debug("#_removeSession()"),await $e(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null);}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&C()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e);}catch(t){console.error("removing visibilitychange callback failed",t);}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),K);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick();},0);}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh();}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh();}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/K);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${K}ms, refresh threshold is ${Qe} ticks`),i<=Qe&&await this._callRefreshToken(r.refresh_token);})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t);}}finally{this._debug("#_autoRefreshTokenTick()","end");}});}catch(e){if(e.isAcquireTimeout||e instanceof Ue)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!C()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),false;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0);}catch(e){console.error("_handleVisibilityChange",e);}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh();}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh();}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await Z(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString());}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString());}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(g(t))return {data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return {data:null,error:o};let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:l,error:h}=await m(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return h?{data:null,error:h}:(e.factorType==="totp"&&(!((i=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(t){if(g(t))return {data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return {data:null,error:n};let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(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:a})})}catch(t){if(g(t))return {data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(g(t))return {data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return {data:null,error:t};let r=e?.factors||[],i=r.filter(o=>o.factor_type==="totp"&&o.status==="verified"),n=r.filter(o=>o.factor_type==="phone"&&o.status==="verified");return {data:{all:r,totp:i,phone:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return {data:null,error:n};if(!i)return {data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:o}=it(i.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let c=o.amr||[];return {data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(o=>o.kid===e);if(r||(r=this.jwks.keys.find(o=>o.kid===e),r&&this.jwks_cached_at+Er>Date.now()))return r;let{data:i,error:n}=await m(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(n)throw n;if(!i.keys||i.keys.length===0)throw new B("JWKS is empty");if(this.jwks=i,this.jwks_cached_at=Date.now(),r=i.keys.find(o=>o.kid===e),!r)throw new B("No matching signing key found in JWKS");return r}async getClaims(e,t={keys:[]}){try{let r=e;if(!r){let{data:f,error:v}=await this.getSession();if(v||!f.session)return {data:null,error:v};r=f.session.access_token;}let{header:i,payload:n,signature:o,raw:{header:a,payload:l}}=it(r);if(Fr(n.exp),!i.kid||i.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){let{error:f}=await this.getUser(r);if(f)throw f;return {data:{claims:n,header:i,signature:o},error:null}}let h=Hr(i.alg),c=await this.fetchJwk(i.kid,t),u=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,u,o,Cr(`${a}.${l}`)))throw new B("Invalid JWT signature");return {data:{claims:n,header:i,signature:o},error:null}}catch(r){if(g(r))return {data:null,error:r};throw r}}};ie.nextInstanceID=0;var Ks=ie,Ct=Ks;var at=class extends Ct{constructor(e){super(e);}};var Vs=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n);})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c));}catch(u){o(u);}}function l(c){try{h(r.throw(c));}catch(u){o(u);}}function h(c){c.done?n(c.value):i(c.value).then(a,l);}h((r=r.apply(s,[])).next());})},Le=class{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=wr(e),l=new URL(a);this.realtimeUrl=new URL("realtime/v1",l),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",l),this.storageUrl=new URL("storage/v1",l),this.functionsUrl=new URL("functions/v1",l);let h=`sb-${l.hostname.split(".")[0]}-auth-token`,c={db:gr,realtime:vr,auth:Object.assign(Object.assign({},_r),{storageKey:h}),global:pr},u=yr(r??{},c);this.storageKey=(i=u.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=u.global.headers)!==null&&n!==void 0?n:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=mr(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},u.realtime)),this.rest=new Yt(new URL("rest/v1",l).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),u.accessToken||this._listenForAuthEvents();}get functions(){return new ge(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Te(this.storageUrl.href,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Vs(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();let{data:r}=yield this.auth.getSession();return (t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,lock:a,debug:l},h,c){let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new at({url:this.authUrl.href,headers:Object.assign(Object.assign({},u),h),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,lock:a,debug:l,fetch:c,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new le(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token);})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?this.changedAccessToken=r:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0);}};var Yr=(s,e,t)=>new Le(s,e,t);var Xs="https://fvwjbphksvfqdzipqbek.supabase.co",Ys="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZ2d2picGhrc3ZmcWR6aXBxYmVrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDkyOTE1MDAsImV4cCI6MjA2NDg2NzUwMH0.7B9_GSUNmPIjVnvIWUQoZ_O2hQn8xVGKhnfVfbUxklY",Do=Yr(Xs,Ys);
export{Do as a};//# sourceMappingURL=chunk-JVZBWTXB.js.map
//# sourceMappingURL=chunk-JVZBWTXB.js.map