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