@tanay-wispr/webflow-package 6.6.18 → 6.6.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/signup.js CHANGED
@@ -1 +1 @@
1
- "use strict";(()=>{var Fr=Object.create;var tt=Object.defineProperty;var Hr=Object.getOwnPropertyDescriptor;var Br=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var Jr=(i,e)=>()=>(i&&(e=i(i=0)),e);var H=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Gr=(i,e)=>{for(var t in e)tt(i,t,{get:e[t],enumerable:!0})},ys=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Br(e))!zr.call(i,r)&&r!==t&&tt(i,r,{get:()=>e[r],enumerable:!(s=Hr(e,r))||s.enumerable});return i};var ws=(i,e,t)=>(t=i!=null?Fr(Wr(i)):{},ys(e||!i||!i.__esModule?tt(t,"default",{value:i,enumerable:!0}):t,i)),Kr=i=>ys(tt({},"__esModule",{value:!0}),i);var ee={};Gr(ee,{Headers:()=>Rt,Request:()=>Qr,Response:()=>Xr,default:()=>Pt,fetch:()=>Yr});var Vr,me,Yr,Pt,Rt,Qr,Xr,Q=Jr(()=>{"use strict";Vr=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},me=Vr(),Yr=me.fetch,Pt=me.fetch.bind(me),Rt=me.Headers,Qr=me.Request,Xr=me.Response});var Ts=H(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});var Ot=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ct.default=Ot});var Lt=H(Oe=>{"use strict";var xs=Oe&&Oe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Oe,"__esModule",{value:!0});var ei=xs((Q(),Kr(ee))),ti=xs(Ts()),It=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:typeof fetch>"u"?this.fetch=ei.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let R=await n.text();R===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=R:l=JSON.parse(R))}let w=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),b=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");w&&b&&b.length>1&&(u=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,p="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let w=await n.text();try{h=JSON.parse(w),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,p="OK")}catch{n.status===404&&w===""?(d=204,p="No Content"):h={message:w}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,p="OK"),h&&this.shouldThrowOnError)throw new ti.default(h)}return{error:h,data:l,count:u,status:d,statusText:p}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}};Oe.default=It});var $t=H(Ce=>{"use strict";var si=Ce&&Ce.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ce,"__esModule",{value:!0});var ri=si(Lt()),jt=class extends ri.default{select(e){let t=!1,s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:n=r}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!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:s=!1,buffers:r=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Ce.default=jt});var ot=H(Ie=>{"use strict";var ii=Ie&&Ie.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ie,"__esModule",{value:!0});var ni=ii($t()),Ut=class extends ni.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};Ie.default=Ut});var Nt=H(je=>{"use strict";var oi=je&&je.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(je,"__esModule",{value:!0});var Le=oi(ot()),Dt=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new Le.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new Le.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new Le.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new Le.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new Le.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};je.default=Dt});var As=H(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.version=void 0;at.version="0.0.0-automated"});var Ps=H(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.DEFAULT_HEADERS=void 0;var ai=As();ct.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ai.version}`}});var Os=H($e=>{"use strict";var Rs=$e&&$e.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty($e,"__esModule",{value:!0});var ci=Rs(Nt()),li=Rs(ot()),hi=Ps(),Mt=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},hi.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new ci.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new li.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};$e.default=Mt});var Us=H(I=>{"use strict";var Ue=I&&I.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(I,"__esModule",{value:!0});I.PostgrestBuilder=I.PostgrestTransformBuilder=I.PostgrestFilterBuilder=I.PostgrestQueryBuilder=I.PostgrestClient=void 0;var Cs=Ue(Os());I.PostgrestClient=Cs.default;var Is=Ue(Nt());I.PostgrestQueryBuilder=Is.default;var Ls=Ue(ot());I.PostgrestFilterBuilder=Ls.default;var js=Ue($t());I.PostgrestTransformBuilder=js.default;var $s=Ue(Lt());I.PostgrestBuilder=$s.default;I.default={PostgrestClient:Cs.default,PostgrestQueryBuilder:Is.default,PostgrestFilterBuilder:Ls.default,PostgrestTransformBuilder:js.default,PostgrestBuilder:$s.default}});var zs=H((Mn,Ws)=>{"use strict";Ws.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var C="https://api.wisprflow.ai",xt=class{static async signupUser(e){try{let t=`${C}/signup`,r=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=r&&r.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${C}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${C}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${C}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch(`${C}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${C}/user_status?email=${encodeURIComponent(e)}`)).json()}static async requestPasswordReset(e,t){let s=await fetch(`${C}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,captcha_token:t})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new Error(r.message||`Request failed with status ${s.status}`)}}static async signInWithEmail(e){let t=await fetch(`${C}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(s.error||s.message||`Request failed with status ${t.status}`);return s}static async getSubscriptionStatus(e){return await fetch(`${C}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${C}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let r=`${C}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`&currency=${s}`),await(await fetch(r,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${C}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch(`${C}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${C}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${C}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let r=new FormData;return r.append("screenshot",e),await fetch(`${C}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:r,signal:s})}};function vs(i){return i==="azure"?"Microsoft":i==="workos"?"SSO":i.charAt(0).toUpperCase()+i.slice(1)}var At=xt;var bs=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var ks=()=>{let i=window.location.hash.substring(1),e=new URLSearchParams(i);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var Ss=()=>{let{access_token:i,refresh_token:e}=ks(),t=i,s=e;if(!t||!s){let r=bs();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var Es=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Q(),ee)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Pe=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},st=class extends Pe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},rt=class extends Pe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},it=class extends Pe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},nt;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(nt||(nt={}));var Zr=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Re=class{constructor(e,{headers:t={},customFetch:s,region:r=nt.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Es(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Zr(this,void 0,void 0,function*(){try{let{headers:r,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:h}).catch(_=>{throw new st(_)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new rt(l);if(!l.ok)throw new it(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return d==="application/json"?p=yield l.json():d==="application/octet-stream"?p=yield l.blob():d==="text/event-stream"?p=l:d==="multipart/form-data"?p=yield l.formData():p=yield l.text(),{data:p,error:null}}catch(r){return{data:null,error:r}}})}};var Ds=ws(Us(),1),{PostgrestClient:Ns,PostgrestQueryBuilder:vn,PostgrestFilterBuilder:bn,PostgrestTransformBuilder:kn,PostgrestBuilder:Sn}=Ds.default;var Ms="2.10.2";var qs={"X-Client-Info":`realtime-js/${Ms}`},Fs="1.0.0",ht=1e4,Hs=1e3,te;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(te||(te={}));var L;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(L||(L={}));var j;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(j||(j={}));var lt;(function(i){i.websocket="websocket"})(lt||(lt={}));var X;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(X||(X={}));var De=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+r));o=o+r;let c=s.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var se=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var x;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(x||(x={}));var Ft=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=ui(o,i,e,r),n),{})},ui=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?Bs(n,o):qt(o)},Bs=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return gi(e,t)}switch(i){case x.bool:return di(e);case x.float4:case x.float8:case x.int2:case x.int4:case x.int8:case x.numeric:case x.oid:return fi(e);case x.json:case x.jsonb:return pi(e);case x.timestamp:return mi(e);case x.abstime:case x.date:case x.daterange:case x.int4range:case x.int8range:case x.money:case x.reltime:case x.text:case x.time:case x.timestamptz:case x.timetz:case x.tsrange:case x.tstzrange:return qt(e);default:return qt(e)}},qt=i=>i,di=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},fi=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},pi=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},gi=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Bs(e,a))}return i},mi=i=>typeof i=="string"?i.replace(" ","T"):i,ut=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var re=class{constructor(e,t,s={},r=ht){this.channel=e,this.event=t,this.payload=s,this.timeout=r,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 s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Ht;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Ht||(Ht={}));var _e=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,r,n,o),this.pendingDiffs.forEach(c=>{this.state=i.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=i.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(b=>b.presence_ref),p=u.map(b=>b.presence_ref),_=l.filter(b=>p.indexOf(b.presence_ref)<0),w=u.filter(b=>d.indexOf(b.presence_ref)<0);_.length>0&&(a[h]=_),w.length>0&&(c[h]=w)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},s,r)}static syncDiff(e,t,s,r){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(p=>p.presence_ref),d=l.filter(p=>u.indexOf(p.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,r(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Bt;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Bt||(Bt={}));var Wt;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Wt||(Wt={}));var zt;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(zt||(zt={}));var ye=class i{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=L.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,j.join,this.params,this.timeout),this.rejoinTimer=new se(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=L.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=L.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=L.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=L.errored,this.rejoinTimer.scheduleTimeout())}),this._on(j.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new _e(this),this.broadcastEndpointURL=ut(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,p=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let w=0;w<p;w++){let b=d[w],{filter:{event:R,schema:$,table:O,filter:m}}=b,E=l&&l[w];if(E&&E.event===R&&E.schema===$&&E.table===O&&E.filter===m)_.push(Object.assign(Object.assign({},b),{id:E.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=c.body)===null||r===void 0?void 0:r.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=L.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(j.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new re(this,j.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new re(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=j;if(s&&[a,c,h,l].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(p=>{var _,w,b;return((_=p.filter)===null||_===void 0?void 0:_.event)==="*"||((b=(w=p.filter)===null||w===void 0?void 0:w.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(p=>p.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var _,w,b,R,$,O;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let m=p.id,E=(_=p.filter)===null||_===void 0?void 0:_.event;return m&&((w=t.ids)===null||w===void 0?void 0:w.includes(m))&&(E==="*"||E?.toLocaleLowerCase()===((b=t.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{let m=($=(R=p?.filter)===null||R===void 0?void 0:R.event)===null||$===void 0?void 0:$.toLocaleLowerCase();return m==="*"||m===((O=t?.event)===null||O===void 0?void 0:O.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:w,table:b,commit_timestamp:R,type:$,errors:O}=_;d=Object.assign(Object.assign({},{schema:w,table:b,commit_timestamp:R,eventType:$,new:{},old:{},errors:O}),this._getPayloadRecords(_))}p.callback(d,s)})}_isClosed(){return this.state===L.closed}_isJoined(){return this.state===L.joined}_isJoining(){return this.state===L.joining}_isLeaving(){return this.state===L.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&i.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(j.close,{},e)}_onError(e){this._on(j.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=L.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Ft(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Ft(e.columns,e.old_record)),t}};var yi=()=>{},wi=typeof WebSocket<"u",we=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=qs,this.params={},this.timeout=ht,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=yi,this.conn=null,this.sendBuffer=[],this.serializer=new De,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(Q(),ee)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${lt.websocket}`,this.httpEndpoint=ut(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let r=(s=t?.params)===null||s===void 0?void 0:s.apikey;r&&(this.accessToken=r,this.apiKey=r),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new se(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(wi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Jt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ws(zs())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case te.connecting:return X.Connecting;case te.open:return X.Open;case te.closing:return X.Closing;default:return X.Closed}}isConnected(){return this.connectionState()===X.Open}channel(e,t={config:{}}){let s=new ye(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(j.access_token,{access_token:e})})}_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(s=>s.topic===e&&(s._isJoined()||s._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))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Fs}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||r===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(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(j.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Hs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Jt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=te.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var ve=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function P(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var dt=class extends ve{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Ne=class extends ve{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var vi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},ft=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Q(),ee)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Js=()=>vi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(Q(),ee))).Response:Response});var be=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Gt=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),bi=(i,e)=>be(void 0,void 0,void 0,function*(){let t=yield Js();i instanceof t?i.json().then(s=>{e(new dt(Gt(s),i.status||500))}).catch(s=>{e(new Ne(Gt(s),s))}):e(new Ne(Gt(i),i))}),ki=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};function pt(i,e,t,s,r,n){return be(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,ki(e,s,r,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>bi(c,a))})})}function Me(i,e,t,s){return be(this,void 0,void 0,function*(){return pt(i,"GET",e,t,s)})}function B(i,e,t,s,r){return be(this,void 0,void 0,function*(){return pt(i,"POST",e,s,r,t)})}function Gs(i,e,t,s,r){return be(this,void 0,void 0,function*(){return pt(i,"PUT",e,s,r,t)})}function gt(i,e,t,s,r){return be(this,void 0,void 0,function*(){return pt(i,"DELETE",e,s,r,t)})}var N=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Si={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ks={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},qe=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=ft(r)}uploadOrUpdate(e,t,s,r){return N(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Ks),r),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(P(n))return{data:null,error:n};throw n}})}upload(e,t,s){return N(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return N(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:Ks.upsert},r),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",h.cacheControl)):(c=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(P(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return N(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");let n=yield B(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ve("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(P(s))return{data:null,error:s};throw s}})}update(e,t,s){return N(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return N(this,void 0,void 0,function*(){try{return{data:yield B(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}copy(e,t,s){return N(this,void 0,void 0,function*(){try{return{data:{path:(yield B(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return N(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield B(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return N(this,void 0,void 0,function*(){try{let r=yield B(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}download(e,t){return N(this,void 0,void 0,function*(){let r=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Me(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(P(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),r=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&r.push(c);let h=r.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return N(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}list(e,t,s){return N(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},Si),t),{prefix:e||""});return{data:yield B(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(P(r))return{data:null,error:r};throw r}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Vs="2.6.0";var Ys={"X-Client-Info":`storage-js/${Vs}`};var ke=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Fe=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Ys),t),this.fetch=ft(s)}listBuckets(){return ke(this,void 0,void 0,function*(){try{return{data:yield Me(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(P(e))return{data:null,error:e};throw e}})}getBucket(e){return ke(this,void 0,void 0,function*(){try{return{data:yield Me(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ke(this,void 0,void 0,function*(){try{return{data:yield B(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(s){if(P(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return ke(this,void 0,void 0,function*(){try{return{data:yield Gs(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(P(s))return{data:null,error:s};throw s}})}emptyBucket(e){return ke(this,void 0,void 0,function*(){try{return{data:yield B(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ke(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}})}};var He=class extends Fe{constructor(e,t={},s){super(e,t,s)}from(e){return new qe(this.url,this.headers,e,this.fetch)}};var Qs="2.44.4";var Be="";typeof Deno<"u"?Be="deno":typeof document<"u"?Be="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Be="react-native":Be="node";var Ei={"X-Client-Info":`supabase-js-${Be}/${Qs}`},Xs={headers:Ei},Zs={schema:"public"},er={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},tr={};Q();var Ti=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},xi=i=>{let e;return i?e=i:typeof fetch>"u"?e=Pt:e=fetch,(...t)=>e(...t)},Ai=()=>typeof Headers>"u"?Rt:Headers,sr=(i,e,t)=>{let s=xi(t),r=Ai();return(n,o)=>Ti(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:i,h=new r(o?.headers);return h.has("apikey")||h.set("apikey",i),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function rr(i){return i.replace(/\/$/,"")}function ir(i,e){let{db:t,auth:s,realtime:r,global:n}=i,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),r),global:Object.assign(Object.assign({},h),n)}}var mt="2.64.4";var nr="http://localhost:9999",or="supabase.auth.token";var ar={"X-Client-Info":`gotrue-js/${mt}`},Kt=10;var We="X-Supabase-Api-Version",Vt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function cr(i){return Math.round(Date.now()/1e3)+i}function lr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}var M=()=>typeof document<"u",ie={tested:!1,writable:!1},Z=()=>{if(!M())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ie.tested)return ie.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),ie.tested=!0,ie.writable=!0}catch{ie.tested=!0,ie.writable=!1}return ie.writable};function _t(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}var yt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(Q(),ee)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},hr=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",Yt=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},Je=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},wt=async(i,e)=>{await i.removeItem(e)};function Pi(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,r,n,o,a,c,h,l=0;for(i=i.replace("-","+").replace("_","/");l<i.length;)o=e.indexOf(i.charAt(l++)),a=e.indexOf(i.charAt(l++)),c=e.indexOf(i.charAt(l++)),h=e.indexOf(i.charAt(l++)),s=o<<2|a>>4,r=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(s),c!=64&&r!=0&&(t=t+String.fromCharCode(r)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var ze=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ze.promiseConstructor=Promise;function Qt(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(Pi(s))}async function ur(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function dr(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function Ri(i){return("0"+i.toString(16)).substr(-2)}function Oi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,Ri).join("")}async function Ci(i){let t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}function Ii(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Li(i){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),i;let t=await Ci(i);return Ii(t)}async function ne(i,e,t=!1){let s=Oi(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await Yt(i,`${e}-code-verifier`,r);let n=await Li(s);return[n,s===n?"plain":"s256"]}var ji=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function fr(i){let e=i.headers.get(We);if(!e||!e.match(ji))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Ge=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function y(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var vt=class extends Ge{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function pr(i){return y(i)&&i.name==="AuthApiError"}var Se=class extends Ge{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},K=class extends Ge{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},W=class extends K{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ee=class extends K{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},oe=class extends K{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ae=class extends K{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}}},Ke=class extends K{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}}},Te=class extends K{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function bt(i){return y(i)&&i.name==="AuthRetryableFetchError"}var Ve=class extends K{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var $i=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},ce=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Ui=[502,503,504];async function gr(i){var e;if(!hr(i))throw new Te(ce(i),0);if(Ui.includes(i.status))throw new Te(ce(i),i.status);let t;try{t=await i.json()}catch(n){throw new Se(ce(n),n)}let s,r=fr(i);if(r&&r.getTime()>=Vt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new Ve(ce(t),i.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new Ve(ce(t),i.status,t.weak_password.reasons);throw new vt(ce(t),i.status||500,s)}var Di=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function S(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[We]||(n[We]=Vt["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Ni(i,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Ni(i,e,t,s,r,n){let o=Di(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(c){throw console.error(c),new Te(ce(c),0)}if(a.ok||await gr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await gr(c)}}function V(i){var e;let t=null;Mi(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=cr(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function Xt(i){let e=V(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function z(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function mr(i){return{data:i,error:null}}function _r(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=$i(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function yr(i){return i}function Mi(i){return i.access_token&&i.refresh_token&&i.expires_in}var qi=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},le=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=yt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(y(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:z})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=qi(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:_r,redirectTo:t?.redirectTo})}catch(t){if(y(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:z})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:yr});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(_=>{let w=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(_.split(";")[1].split("=")[1]);h[`${b}Page`]=w}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(y(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:z})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:z})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:z})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(y(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}};var wr={getItem:i=>Z()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{Z()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{Z()&&globalThis.localStorage.removeItem(i)}};function Zt(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function vr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var he={debug:!!(globalThis&&Z()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ye=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},kt=class extends Ye{};async function es(i,e,t){he.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),he.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){he.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{he.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw he.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new kt(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(he.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}vr();var Fi={url:nr,storageKey:or,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ar,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Qe=30*1e3,br=3;async function kr(i,e,t){return await t()}var ue=class i{constructor(e){var t,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=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&M()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let r=Object.assign(Object.assign({},Fi),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new le({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=yt(r.fetch),this.lock=r.lock||kr,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:M()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=es:this.lock=kr,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?r.storage?this.storage=r.storage:Z()?this.storage=wr:(this.memoryStorage={},this.storage=Zt(this.memoryStorage)):(this.memoryStorage={},this.storage=Zt(this.memoryStorage)),M()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${mt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=M()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:r,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",n),await this._saveSession(r),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return y(e)?{error:e}:{error:new Se("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:V}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(y(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,p=null,_=null;this.flowType==="pkce"&&([p,_]=await ne(this.storage,this.storageKey)),n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:p,code_challenge_method:_},xform:V})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:V})}else throw new oe("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(y(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Xt})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Xt})}else throw new oe("You must provide either an email or phone number and a password");let{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Ee}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Je(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:V});return await wt(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Ee}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:V}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Ee}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await ne(this.storage,this.storageKey));let{error:u}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new oe("You must provide either an email or phone number.")}catch(a){if(y(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:V});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(r){if(y(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await ne(this.storage,this.storageKey)),await S(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:mr})}catch(n){if(y(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new W;let{error:r}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(y(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:r,options:n}=e,{error:o}=await S(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:r,options:n}=e,{data:o,error:a}=await S(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new oe("You must provide either an email or phone number and a type")}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Je(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!o&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:z}):await this._useSession(async t=>{var s,r,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new W}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:z})})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new W;let o=r.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await ne(this.storage,this.storageKey));let{data:h,error:l}=await S(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:z});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Qt(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new W;let t=Date.now()/1e3,s=t,r=!0,n=null,o=Qt(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(y(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new W;let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(y(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!M())throw new ae("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ae("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ke("Not a valid PKCE flow url.");let t=_t(window.location.href);if(e){if(!t.code)throw new Ke("No code detected.");let{data:$,error:O}=await this._exchangeCodeForSession(t.code);if(O)throw O;let m=new URL(window.location.href);return m.searchParams.delete("code"),window.history.replaceState(window.history.state,"",m.toString()),{data:{session:$.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ae(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new ae("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let p=d-l;p*1e3<=Qe&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${u}s`);let _=d-u;l-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,l):l-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,l);let{data:w,error:b}=await this._getUser(n);if(b)throw b;let R={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:R,redirectType:t.type},error:null}}catch(t){if(y(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=_t(window.location.href);return!!(M()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=_t(window.location.href),t=await Je(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{error:n};let o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(pr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await wt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=lr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await ne(this.storage,this.storageKey,!0));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(y(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:r}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await S(this.fetch,"GET",p,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(r)throw r;return M()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(y(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await dr(async r=>(r>0&&await ur(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(r,n)=>{let o=200*Math.pow(2,r);return n&&bt(n)&&Date.now()+o-s<Qe})}catch(s){if(this._debug(t,"error",s),y(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),M()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await Je(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let r=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<r+Kt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Kt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),bt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new W;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new ze;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new W;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"error",n),y(n)){let o={session:null,error:n};return bt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Yt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await wt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&M()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Qe);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let r=Math.floor((s.expires_at*1e3-e)/Qe);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${Qe}ms, refresh threshold is ${br} ticks`),r<=br&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ye)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!M()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await ne(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await S(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((r=a?.totp)===null||r===void 0)&&r.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(y(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(y(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],r=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(r.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};ue.nextInstanceID=0;var Hi=ue,ts=Hi;var St=class extends ts{constructor(e){super(e)}};var Bi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Xe=class{constructor(e,t,s){var r,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=rr(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Zs,realtime:tr,auth:Object.assign(Object.assign({},er),{storageKey:c}),global:Xs},l=ir(s??{},h);this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=sr(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Ns(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Re(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new He(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}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 Bi(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new St({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new we(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Sr=(i,e,t)=>new Xe(i,e,t);var Y={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Wi=i=>{try{let e=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(i.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Et=i=>{let[e,t]=i.split(".");return!e||!t?null:Wi(t)},Er=i=>{let e=Et(i);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var zi="https://api.workos.com",Ji=60,xe=(i,e)=>typeof i[e]=="string"?i[e]:void 0,Tr=(i,e,t)=>{let s=Et(i);if(!s)return null;let r=xe(s,"urn:wispr:user_external_id")??xe(s,"sub"),n=t?.email??xe(s,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof s.exp=="number"?s.exp:void 0,c={id:r??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:i,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},Gi=async(i,e,t,s)=>{let r=t?.startsWith("https://")?t.replace(/\/$/,""):zi,n=await fetch(`${r}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:i,organization_id:s})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},xr=async(i,e)=>{let t=Et(i);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),r=typeof t.exp=="number"?t.exp:0,n=xe(t,"client_id");if(r-s<Ji&&n){let c=await Gi(e,n,xe(t,"iss"),xe(t,"org_id")),h=Tr(c.access_token,c.refresh_token,c.user);if(!h)throw new Error("WorkOS refresh returned an invalid access token");return h}if(r<=s)throw new Error("WorkOS session expired");let a=Tr(i,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Tt=class{constructor(){this.sessionData=null;this.supabase=Sr(Y.supaBaseUrl,Y.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||Y.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||Y.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||Y.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:r}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(r)throw r;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let r=new Date;r.setTime(r.getTime()+s*24*60*60*1e3);let n=`expires=${r.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{if(Er(t)==="workos"){this.sessionData=await xr(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(r){throw r}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,r]=t.split("=");return e[s]=r,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||Y.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,r,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:r||Y.redirectUri,data:{full_name:s},captchaToken:n}});if(o)throw o;console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s){try{let{data:r,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:s}});if(n)throw n;if(!r.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:r.session.access_token,refreshToken:r.session.refresh_token,fullName:r.session.user.user_metadata?.full_name||void 0}}catch(r){throw console.error("Error signing in with password:",r),r}}async resendVerificationEmail(e,t,s){try{let{error:r}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||Y.redirectUri,captchaToken:s}});if(r)throw r;console.log("Verification email resent to:",e)}catch(r){throw console.error("Error resending verification email:",r),r}}async getUser(){let{data:e,error:t}=await this.supabase.auth.getUser();if(t)throw t;return e.user}async getSession(){let{data:e,error:t}=await this.supabase.auth.getSession();if(t)throw t;return e.session}};var J=null;function ss(i,e=30,t){J&&(clearInterval(J),J=null);let s=e;i.style.pointerEvents="none",i.textContent=`Resend (${s}s)`,J=setInterval(()=>{s=s-1,i.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(i.style.pointerEvents="auto",J&&(clearInterval(J),J=null),t&&t())},1e3)}function Ar(){J&&(clearInterval(J),J=null)}var Pr=/^[\p{L}\p{M}\s\-'.]+$/u;function Ki(i,e){let t=i.trim();return t?/\d/.test(t)?"Your name can't include numbers":Pr.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function rs(i,e){let t=i.trim();return t?/\d/.test(t)?"Your name can't include numbers":Pr.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function Rr(i,e,t){let s="full-name-match-error",r=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let h=document.getElementById(s);h||(h=document.createElement("div"),h.id=s,h.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",h)),h.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=Ki(e.value,i.value);c?r(c):n()},a=()=>{let c=rs(e.value,i.value);c?r(c):n()};i.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var is=(i,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:i,retry_attempt:10-t}),window.posthog.capture(i,e)):t>0&&setTimeout(()=>is(i,e,t-1),200)};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=localStorage.getItem("checkout_debug");if(i){try{let f=JSON.parse(i);is("checkout_debug",{...f,reported_from:"get_started",ms_since_error:Date.now()-(f.timestamp??Date.now())})}catch{}localStorage.removeItem("checkout_debug")}let e=!1,t=setTimeout(()=>{e||(document.body.style.visibility="visible")},4e3),s=new Tt,{accessToken:r,refreshToken:n}=Ss(),o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),h=document.querySelector("#full-name"),l=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),d=document.querySelector("#microsoft-login"),p;(T=>(T.EMAIL_INPUT="email_input",T.LOGIN="login",T.SIGNUP="signup",T.OAUTH_USER="oauth_user",T.UNVERIFIED_EMAIL="unverified_email"))(p||(p={}));let _="email_input",w=document.querySelector("[email-element]"),b=document.querySelector("[different-provider]"),R=document.querySelector("[different-provider-name]"),$=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),m=document.querySelector("[email-signup-error]"),E=document.querySelector("[error-message]"),ns=document.querySelector("[verification-email]"),Ae=document.querySelector("[email-signup-retry]"),os=document.querySelector("[email-signup-reset]"),de=document.querySelector("[scim-div]"),as=document.querySelector("[scim-reset]"),U=document.querySelector("[forgot-password]"),Ze=document.querySelector("[forgot-password-success]"),cs=document.querySelector("[forgot-password-email]"),fe=document.querySelector("[unverified-email]"),ls=document.querySelector("[unverified-email-address]"),q=document.querySelector("[resend-verification-email]"),hs=document.querySelector("[unverified-email-reset]"),Or=localStorage.getItem("email"),us=localStorage.getItem("last_authed_provider");us&&{google:l,apple:u,microsoft:d,sso:document.querySelector("#sso-login"),email:a}[us]?.classList.add("last-used");let pe=new URLSearchParams(window.location.search),ds=pe.get("referral"),fs=pe.get("plan"),ps=pe.get("utm_source"),Cr=pe.get("redirect"),gs=pe.get("team_invite_code"),Vi=pe.get("code"),Ir=Cr==="android-waitlist"?"/android-waitlist":"/downloads",F=`${window.location.origin}${Ir}`,ge=new URLSearchParams;ds&&ge.append("referral",ds),fs&&ge.append("plan",fs),ps&&ge.append("utm_source",ps),gs&&ge.append("team_invite_code",gs),ge.toString()&&(F+=`?${ge.toString()}`);let Lr=()=>{try{let f=document.cookie.split("; ");for(let g of f){let v=g.indexOf("=");if(v===-1||g.slice(0,v)!=="wispr_auth")continue;let A=g.slice(v+1),T=decodeURIComponent(A);return JSON.parse(T)}return null}catch{return null}};if(r&&n)try{s.setCookies(r,n);let f=s.checkAndSetSession(),g=new Promise((k,A)=>setTimeout(()=>A(new Error("Session timeout")),3e3));await Promise.race([f,g]),s.sessionData&&s.setCookies(s.sessionData.access_token,s.sessionData.refresh_token);let v=s.sessionData?.user.email;localStorage.setItem("email",v),e=!0,clearTimeout(t),window.location.href=F}catch(f){console.error("Error during session setup:",f),document.body.style.visibility="visible"}else{let f=Lr();if(f?.access_token&&f?.refresh_token)try{s.setCookies(f.access_token,f.refresh_token);let g=s.checkAndSetSession(),v=new Promise((T,D)=>setTimeout(()=>D(new Error("Session timeout")),3e3));await Promise.race([g,v]),s.sessionData&&s.setCookies(s.sessionData.access_token,s.sessionData.refresh_token);let k=s.sessionData?.user.email,A=s.sessionData?.user.app_metadata.provider||"typing_test";localStorage.setItem("email",k),localStorage.setItem("signin_provider",A),e=!0,clearTimeout(t),window.location.href=F}catch(g){console.error("Error authenticating from typing test session:",g),f.email&&(a.value=f.email),document.body.style.visibility="visible"}else f?.email?(a.value=f.email,document.body.style.visibility="visible"):(Or&&localStorage.removeItem("email"),document.body.style.visibility="visible")}l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await s.signInWithGoogle(F)}catch(f){console.error("Error during sign-in:",f)}}),u.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await s.signInWithApple(F)}catch(f){console.error("Error during sign-in:",f)}}),d.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await s.signInWithMicrosoft(F)}catch(f){console.error("Error during sign-in:",f)}});let et=()=>{b&&(b.style.display="none"),O&&(O.style.display="none"),m&&(m.style.display="none"),fe&&(fe.style.display="none"),de&&(de.style.display="none"),U&&(U.style.display="none"),Ze&&(Ze.style.display="none");let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="block"),w&&(w.style.display="flex"),a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled"),c.value="",c.style.display="none",c.removeAttribute("required"),h.value="",h.style.display="none",h.removeAttribute("required");let g=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");g&&(g.style.display="none"),v&&(v.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),_="email_input",a.focus()},jr=()=>{a.setAttribute("readonly","true"),a.classList.add("disabled"),c.style.display="block",c.setAttribute("required","true"),c.focus(),h.style.display="none",h.removeAttribute("required");let f=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),g&&(g.style.display="block"),U&&(U.style.display="block",U.onclick=async()=>{let v=a.value,k=U.textContent||"";try{let{hcaptcha:A}=window;if(!A)throw new Error("Verification system not loaded. Please refresh the page.");U.style.pointerEvents="none",U.textContent="Sending...";let{response:T}=await A.execute({async:!0});if(!T)throw new Error("Verification cancelled");await At.requestPasswordReset(v,T),A.reset(),w&&(w.style.display="none"),U&&(U.style.display="none"),Ze&&(Ze.style.display="block"),cs&&(cs.textContent=v)}catch(A){console.error("\u274C Error sending password reset email:",A),U.textContent=k,U.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),m&&(m.style.display="block",E&&(E.textContent=A instanceof Error?A.message:"Failed to send reset email"))}}),_="login",console.log("\u2705 Existing user detected - showing login form")},ms=()=>{a.setAttribute("readonly","true"),a.classList.add("disabled"),c.style.display="block",c.setAttribute("required","true"),h.style.display="block",h.setAttribute("required","true"),c.focus();let f=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),g&&(g.style.display="block"),_="signup",console.log("\u2705 New user detected - showing signup form")},$r=()=>{let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="none"),de&&(de.style.display="block"),as&&(as.onclick=()=>{de&&(de.style.display="none"),f&&(f.style.display="block"),et()})},_s=f=>{let g=vs(f);w&&(w.style.display="none"),b&&(b.style.display="block"),R&&(R.textContent=g),$&&($.onclick=()=>{b&&(b.style.display="none"),et()}),_="oauth_user"},Ur=f=>{w&&(w.style.display="none"),fe&&(fe.style.display="block"),ls&&(ls.textContent=f),q&&(q.onclick=async()=>{let g=q.textContent||"";try{let v=window.hcaptcha;if(!v)throw new Error("Verification system not loaded. Please refresh the page.");q.textContent="Verifying...",q.style.pointerEvents="none";let{response:k}=await v.execute({async:!0});if(!k)throw new Error("Verification cancelled");q.textContent="Sending...",await s.resendVerificationEmail(f,F,k),q.textContent="Verification email resent! \u2705",q.style.textDecoration="none",console.log("\u2705 Verification email resent to:",f),m&&(m.style.display="none"),v.reset()}catch(v){if(console.error("\u274C Error resending verification email:",v),q.textContent=g,q.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),m&&(m.style.display="block",E)){let k=v instanceof Error?v.message:"Failed to resend verification email";E.textContent=k}}}),hs&&(hs.onclick=()=>{fe&&(fe.style.display="none"),et()}),_="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},Dr=async(f,g)=>{let v=g.value;g.classList.add("loading"),g.value="";try{let k=await At.checkUserStatus(f);console.log("User status check:",k),g.classList.remove("loading"),g.value=v,!k.exists&&k.scim_managed?$r():k.enforce_sso?_s("workos"):k.exists&&k.provider&&k.provider!=="email"?_s(k.provider):k.exists&&k.provider==="email"&&!k.verified?Ur(f):k.exists&&k.provider==="email"?jr():ms()}catch(k){console.error("\u274C Error checking user status:",k),g.classList.remove("loading"),g.value=v,ms()}},Nr=async(f,g,v,k)=>{if(!g||g.length<8){m&&(m.style.display="block",E&&(E.textContent="Password must be at least 8 characters"));return}let A=window.hcaptcha?.getResponse()||"";if(!A){m&&(m.style.display="block",E&&(E.textContent="Please complete the verification"));return}v.classList.add("loading"),v.value="";try{console.log("\u2705 Attempting login for:",f);let{accessToken:T,refreshToken:D}=await s.signInWithPassword(f,g,A);s.setCookies(T,D),localStorage.setItem("email",f),e=!0,clearTimeout(t),window.location.href=F}catch(T){if(console.error("\u274C Login error:",T),window.hcaptcha&&window.hcaptcha.reset(),v.classList.remove("loading"),v.value=k,m&&(m.style.display="block",E)){let D=T instanceof Error?T.message:"Invalid login credentials";E.textContent=D}}},Mr=async(f,g,v,k,A)=>{if(!g||g.length<8){m&&(m.style.display="block",E&&(E.textContent="Password must be at least 8 characters"));return}if(!v||v.trim().length<2){m&&(m.style.display="block",E&&(E.textContent="Please enter your full name"));return}let T=rs(v,g);if(T){m&&(m.style.display="block",E&&(E.textContent=T));return}let D=window.hcaptcha?.getResponse()||"";if(!D){m&&(m.style.display="block",E&&(E.textContent="Please complete the verification"));return}k.classList.add("loading"),k.value="";try{console.log("\u2705 Creating new account for:",f),await s.signUpWithPassword(f,g,v,F,D),window.hcaptcha&&window.hcaptcha.reset(),k.classList.remove("loading"),k.value=A,w&&(w.style.display="none"),m&&(m.style.display="none"),O&&(O.style.display="block"),ns&&(ns.textContent=f),Ae&&(ss(Ae,30),Ae.onclick=async()=>{if(Ae.style.pointerEvents!=="none")try{let G=window.hcaptcha?.getResponse()||"";await s.signUpWithPassword(f,g,v,F,G),window.hcaptcha&&window.hcaptcha.reset(),ss(Ae,30),console.log("\u2705 Verification email resent to:",f)}catch(G){console.error("\u274C Error resending verification email:",G)}}),os&&(os.onclick=()=>{O&&(O.style.display="none"),Ar(),et()})}catch(G){if(console.error("\u274C Signup error:",G),k.classList.remove("loading"),k.value=A,m&&(m.style.display="block",E)){let qr=G instanceof Error?G.message:"Signup failed";E.textContent=qr}}};Rr(c,h,o.querySelector('[type="submit"]')),o.addEventListener("submit",async f=>{f.stopPropagation(),f.preventDefault();let g=a.value,v=c?.value||"",k=h?.value||"";if(!g||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g)){console.error("\u274C Email invalid"),m&&(m.style.display="block",E&&(E.textContent="Please enter a valid email address"));return}m&&(m.style.display="none"),E&&(E.textContent="");let T=o.querySelector('[type="submit"]'),D=T?.value||"";localStorage.setItem("signin_provider","email");try{_==="email_input"?await Dr(g,T):_==="login"?await Nr(g,v,T,D):_==="signup"&&await Mr(g,v,k,T,D)}catch(G){console.error("\u274C Signup error:",G),T&&(T.classList.remove("loading"),T.value=D),m&&(m.style.display="block")}})});})();
1
+ "use strict";(()=>{var Wr=Object.create;var it=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var Gr=Object.getOwnPropertyNames;var Jr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var Kr=(r,e)=>()=>(r&&(e=r(r=0)),e);var H=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Vr=(r,e)=>{for(var t in e)it(r,t,{get:e[t],enumerable:!0})},ks=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Gr(e))!zr.call(r,i)&&i!==t&&it(r,i,{get:()=>e[i],enumerable:!(s=Br(e,i))||s.enumerable});return r};var Ss=(r,e,t)=>(t=r!=null?Wr(Jr(r)):{},ks(e||!r||!r.__esModule?it(t,"default",{value:r,enumerable:!0}):t,r)),Yr=r=>ks(it({},"__esModule",{value:!0}),r);var te={};Vr(te,{Headers:()=>jt,Request:()=>Zr,Response:()=>ei,default:()=>It,fetch:()=>Xr});var Qr,ye,Xr,It,jt,Zr,ei,X=Kr(()=>{"use strict";Qr=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ye=Qr(),Xr=ye.fetch,It=ye.fetch.bind(ye),jt=ye.Headers,Zr=ye.Request,ei=ye.Response});var Ps=H(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});var $t=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ut.default=$t});var Nt=H(Le=>{"use strict";var Rs=Le&&Le.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Le,"__esModule",{value:!0});var si=Rs((X(),Yr(te))),ri=Rs(Ps()),Dt=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:typeof fetch>"u"?this.fetch=si.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let u=null,l=null,h=null,d=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let C=await n.text();C===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=C:l=JSON.parse(C))}let w=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),v=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");w&&v&&v.length>1&&(h=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,h=null,d=406,p="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let w=await n.text();try{u=JSON.parse(w),Array.isArray(u)&&n.status===404&&(l=[],u=null,d=200,p="OK")}catch{n.status===404&&w===""?(d=204,p="No Content"):u={message:w}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,d=200,p="OK"),u&&this.shouldThrowOnError)throw new ri.default(u)}return{error:u,data:l,count:h,status:d,statusText:p}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};Le.default=Dt});var qt=H(Ie=>{"use strict";var ii=Ie&&Ie.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ie,"__esModule",{value:!0});var ni=ii(Nt()),Mt=class extends ni.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!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:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Ie.default=Mt});var lt=H(je=>{"use strict";var oi=je&&je.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(je,"__esModule",{value:!0});var ai=oi(qt()),Ft=class extends ai.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};je.default=Ft});var Wt=H(Ue=>{"use strict";var ci=Ue&&Ue.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ue,"__esModule",{value:!0});var $e=ci(lt()),Ht=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new $e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new $e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new $e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new $e.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new $e.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ue.default=Ht});var Cs=H(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.version=void 0;ut.version="0.0.0-automated"});var Os=H(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.DEFAULT_HEADERS=void 0;var li=Cs();ht.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${li.version}`}});var Is=H(De=>{"use strict";var Ls=De&&De.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(De,"__esModule",{value:!0});var ui=Ls(Wt()),hi=Ls(lt()),di=Os(),Bt=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},di.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ui.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,h])=>h!==void 0).map(([l,h])=>[l,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([l,h])=>{a.searchParams.append(l,h)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new hi.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};De.default=Bt});var Ms=H(L=>{"use strict";var Ne=L&&L.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(L,"__esModule",{value:!0});L.PostgrestBuilder=L.PostgrestTransformBuilder=L.PostgrestFilterBuilder=L.PostgrestQueryBuilder=L.PostgrestClient=void 0;var js=Ne(Is());L.PostgrestClient=js.default;var $s=Ne(Wt());L.PostgrestQueryBuilder=$s.default;var Us=Ne(lt());L.PostgrestFilterBuilder=Us.default;var Ds=Ne(qt());L.PostgrestTransformBuilder=Ds.default;var Ns=Ne(Nt());L.PostgrestBuilder=Ns.default;L.default={PostgrestClient:js.default,PostgrestQueryBuilder:$s.default,PostgrestFilterBuilder:Us.default,PostgrestTransformBuilder:Ds.default,PostgrestBuilder:Ns.default}});var Ks=H((Bn,zs)=>{"use strict";zs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var P="https://api.wisprflow.ai";function Re(r,e){return typeof r.message=="string"&&r.message||typeof r.error=="string"&&r.error||typeof r.detail=="string"&&r.detail||`Request failed with status ${e}`}var Ot=class{static async signupUser(e){try{let t=`${P}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${P}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${P}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${P}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch(`${P}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${P}/user_status?email=${encodeURIComponent(e)}`)).json()}static async requestPasswordReset(e,t){let s=await fetch(`${P}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,captcha_token:t})});if(!s.ok){let i=await s.json().catch(()=>({}));throw new Error(Re(i,s.status))}}static async signUpWithCaptcha(e){let t=await fetch(`${P}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(Re(s,t.status));return s}static async signInWithCaptcha(e){let t=await fetch(`${P}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(Re(s,t.status));return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${P}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(Re(s,t.status))}}static async signInWithEmail(e){let t=await fetch(`${P}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(Re(s,t.status));return s}static async getSubscriptionStatus(e){return await fetch(`${P}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${P}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let i=`${P}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(i+=`&currency=${s}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${P}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch(`${P}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${P}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${P}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let i=new FormData;return i.append("screenshot",e),await fetch(`${P}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function Lt(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var Q=Ot;var Es=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Ts=()=>{let r=window.location.hash.substring(1),e=new URLSearchParams(r);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var xs=()=>{let{access_token:r,refresh_token:e}=Ts(),t=r,s=e;if(!t||!s){let i=Es();t=i.access_token,s=i.refresh_token}return{accessToken:t,refreshToken:s}};var As=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(X(),te)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Ce=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},nt=class extends Ce{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ot=class extends Ce{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},at=class extends Ce{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ct;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(ct||(ct={}));var ti=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Oe=class{constructor(e,{headers:t={},customFetch:s,region:i=ct.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=As(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return ti(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let u;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(y=>{throw new nt(y)}),h=l.headers.get("x-relay-error");if(h&&h==="true")throw new ot(l);if(!l.ok)throw new at(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return d==="application/json"?p=yield l.json():d==="application/octet-stream"?p=yield l.blob():d==="text/event-stream"?p=l:d==="multipart/form-data"?p=yield l.formData():p=yield l.text(),{data:p,error:null}}catch(i){return{data:null,error:i}}})}};var qs=Ss(Ms(),1),{PostgrestClient:Fs,PostgrestQueryBuilder:Tn,PostgrestFilterBuilder:xn,PostgrestTransformBuilder:An,PostgrestBuilder:Pn}=qs.default;var Hs="2.10.2";var Ws={"X-Client-Info":`realtime-js/${Hs}`},Bs="1.0.0",ft=1e4,Gs=1e3,se;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(se||(se={}));var I;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(I||(I={}));var j;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(j||(j={}));var dt;(function(r){r.websocket="websocket"})(dt||(dt={}));var Z;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(Z||(Z={}));var Me=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var re=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var x;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(x||(x={}));var Jt=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=fi(o,r,e,i),n),{})},fi=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?Js(n,o):Gt(o)},Js=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return yi(e,t)}switch(r){case x.bool:return pi(e);case x.float4:case x.float8:case x.int2:case x.int4:case x.int8:case x.numeric:case x.oid:return mi(e);case x.json:case x.jsonb:return gi(e);case x.timestamp:return _i(e);case x.abstime:case x.date:case x.daterange:case x.int4range:case x.int8range:case x.money:case x.reltime:case x.text:case x.time:case x.timestamptz:case x.timetz:case x.tsrange:case x.tstzrange:return Gt(e);default:return Gt(e)}},Gt=r=>r,pi=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},mi=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},gi=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},yi=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n,o=r.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Js(e,a))}return r},_i=r=>typeof r=="string"?r.replace(" ","T"):r,pt=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ie=class{constructor(e,t,s={},i=ft){this.channel=e,this.event=t,this.payload=s,this.timeout=i,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 s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var zt;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(zt||(zt={}));var _e=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let h=n[u];if(h){let d=l.map(v=>v.presence_ref),p=h.map(v=>v.presence_ref),y=l.filter(v=>p.indexOf(v.presence_ref)<0),w=h.filter(v=>d.indexOf(v.presence_ref)<0);y.length>0&&(a[u]=y),w.length>0&&(c[u]=w)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let h=e[a].map(p=>p.presence_ref),d=l.filter(p=>h.indexOf(p.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(h=>h.presence_ref);u=u.filter(h=>l.indexOf(h.presence_ref)<0),e[a]=u,i(a,u,c),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Kt;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(Kt||(Kt={}));var Vt;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(Vt||(Vt={}));var Yt;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Yt||(Yt={}));var we=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=I.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 ie(this,j.join,this.params,this.timeout),this.rejoinTimer=new re(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=I.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=I.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this._on(j.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new _e(this),this.broadcastEndpointURL=pt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var h;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,p=(h=d?.length)!==null&&h!==void 0?h:0,y=[];for(let w=0;w<p;w++){let v=d[w],{filter:{event:C,schema:$,table:O,filter:g}}=v,E=l&&l[w];if(E&&E.event===C&&E.schema===$&&E.table===O&&E.filter===g)y.push(Object.assign(Object.assign({},v),{id:E.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=I.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(j.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new ie(this,j.leave,{},e);i.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let i=new AbortController,n=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new ie(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:u,join:l}=j;if(s&&[a,c,u,l].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(p=>{var y,w,v;return((y=p.filter)===null||y===void 0?void 0:y.event)==="*"||((v=(w=p.filter)===null||w===void 0?void 0:w.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===o}).map(p=>p.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var y,w,v,C,$,O;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let g=p.id,E=(y=p.filter)===null||y===void 0?void 0:y.event;return g&&((w=t.ids)===null||w===void 0?void 0:w.includes(g))&&(E==="*"||E?.toLocaleLowerCase()===((v=t.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{let g=($=(C=p?.filter)===null||C===void 0?void 0:C.event)===null||$===void 0?void 0:$.toLocaleLowerCase();return g==="*"||g===((O=t?.event)===null||O===void 0?void 0:O.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof d=="object"&&"ids"in d){let y=d.data,{schema:w,table:v,commit_timestamp:C,type:$,errors:O}=y;d=Object.assign(Object.assign({},{schema:w,table:v,commit_timestamp:C,eventType:$,new:{},old:{},errors:O}),this._getPayloadRecords(y))}p.callback(d,s)})}_isClosed(){return this.state===I.closed}_isJoined(){return this.state===I.joined}_isJoining(){return this.state===I.joining}_isLeaving(){return this.state===I.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(j.close,{},e)}_onError(e){this._on(j.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=I.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Jt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Jt(e.columns,e.old_record)),t}};var vi=()=>{},bi=typeof WebSocket<"u",ve=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ws,this.params={},this.timeout=ft,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=vi,this.conn=null,this.sendBuffer=[],this.serializer=new Me,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(X(),te)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${dt.websocket}`,this.httpEndpoint=pt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(s=t?.params)===null||s===void 0?void 0:s.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new re(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(bi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Qt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ss(Ks())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case se.connecting:return Z.Connecting;case se.open:return Z.Open;case se.closing:return Z.Closing;default:return Z.Closed}}isConnected(){return this.connectionState()===Z.Open}channel(e,t={config:{}}){let s=new we(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(j.access_token,{access_token:e})})}_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(s=>s.topic===e&&(s._isJoined()||s._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))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Bs}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(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(j.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Gs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Qt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=se.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var be=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function R(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var mt=class extends be{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},qe=class extends be{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var ki=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},gt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(X(),te)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Vs=()=>ki(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(X(),te))).Response:Response});var ke=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Xt=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Si=(r,e)=>ke(void 0,void 0,void 0,function*(){let t=yield Vs();r instanceof t?r.json().then(s=>{e(new mt(Xt(s),r.status||500))}).catch(s=>{e(new qe(Xt(s),s))}):e(new qe(Xt(r),r))}),Ei=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};function yt(r,e,t,s,i,n){return ke(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,Ei(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Si(c,a))})})}function Fe(r,e,t,s){return ke(this,void 0,void 0,function*(){return yt(r,"GET",e,t,s)})}function W(r,e,t,s,i){return ke(this,void 0,void 0,function*(){return yt(r,"POST",e,s,i,t)})}function Ys(r,e,t,s,i){return ke(this,void 0,void 0,function*(){return yt(r,"PUT",e,s,i,t)})}function _t(r,e,t,s,i){return ke(this,void 0,void 0,function*(){return yt(r,"DELETE",e,s,i,t)})}var N=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Ti={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Qs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},He=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=gt(i)}uploadOrUpdate(e,t,s,i){return N(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Qs),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),h=yield l.json();return l.ok?{data:{path:c,id:h.Id,fullPath:h.Key},error:null}:{data:null,error:h}}catch(n){if(R(n))return{data:null,error:n};throw n}})}upload(e,t,s){return N(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return N(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,u=Object.assign({upsert:Qs.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",u.cacheControl)):(c=s,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let h=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield h.json();return h.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(R(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return N(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield W(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new be("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(R(s))return{data:null,error:s};throw s}})}update(e,t,s){return N(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return N(this,void 0,void 0,function*(){try{return{data:yield W(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(R(i))return{data:null,error:i};throw i}})}copy(e,t,s){return N(this,void 0,void 0,function*(){try{return{data:{path:(yield W(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(R(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return N(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield W(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(R(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return N(this,void 0,void 0,function*(){try{let i=yield W(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(R(i))return{data:null,error:i};throw i}})}download(e,t){return N(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Fe(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(R(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${u}`)}}}remove(e){return N(this,void 0,void 0,function*(){try{return{data:yield _t(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(R(t))return{data:null,error:t};throw t}})}list(e,t,s){return N(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Ti),t),{prefix:e||""});return{data:yield W(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(R(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Xs="2.6.0";var Zs={"X-Client-Info":`storage-js/${Xs}`};var Se=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},We=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Zs),t),this.fetch=gt(s)}listBuckets(){return Se(this,void 0,void 0,function*(){try{return{data:yield Fe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(R(e))return{data:null,error:e};throw e}})}getBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield Fe(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(R(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Se(this,void 0,void 0,function*(){try{return{data:yield W(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(s){if(R(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Se(this,void 0,void 0,function*(){try{return{data:yield Ys(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(R(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield W(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(R(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Se(this,void 0,void 0,function*(){try{return{data:yield _t(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(R(t))return{data:null,error:t};throw t}})}};var Be=class extends We{constructor(e,t={},s){super(e,t,s)}from(e){return new He(this.url,this.headers,e,this.fetch)}};var er="2.44.4";var Ge="";typeof Deno<"u"?Ge="deno":typeof document<"u"?Ge="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ge="react-native":Ge="node";var xi={"X-Client-Info":`supabase-js-${Ge}/${er}`},tr={headers:xi},sr={schema:"public"},rr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ir={};X();var Ai=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Pi=r=>{let e;return r?e=r:typeof fetch>"u"?e=It:e=fetch,(...t)=>e(...t)},Ri=()=>typeof Headers>"u"?jt:Headers,nr=(r,e,t)=>{let s=Pi(t),i=Ri();return(n,o)=>Ai(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",r),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:u}))})};function or(r){return r.replace(/\/$/,"")}function ar(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var wt="2.64.4";var cr="http://localhost:9999",lr="supabase.auth.token";var ur={"X-Client-Info":`gotrue-js/${wt}`},Zt=10;var Je="X-Supabase-Api-Version",es={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function hr(r){return Math.round(Date.now()/1e3)+r}function dr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var M=()=>typeof document<"u",ne={tested:!1,writable:!1},ee=()=>{if(!M())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ne.tested)return ne.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),ne.tested=!0,ne.writable=!0}catch{ne.tested=!0,ne.writable=!1}return ne.writable};function vt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var bt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(X(),te)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},fr=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",ts=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Ke=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},kt=async(r,e)=>{await r.removeItem(e)};function Ci(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,u,l=0;for(r=r.replace("-","+").replace("_","/");l<r.length;)o=e.indexOf(r.charAt(l++)),a=e.indexOf(r.charAt(l++)),c=e.indexOf(r.charAt(l++)),u=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var ze=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ze.promiseConstructor=Promise;function ss(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(Ci(s))}async function pr(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function mr(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await r(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Oi(r){return("0"+r.toString(16)).substr(-2)}function Li(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,Oi).join("")}async function Ii(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function ji(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function $i(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await Ii(r);return ji(t)}async function oe(r,e,t=!1){let s=Li(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await ts(r,`${e}-code-verifier`,i);let n=await $i(s);return[n,s===n?"plain":"s256"]}var Ui=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function gr(r){let e=r.headers.get(Je);if(!e||!e.match(Ui))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Ve=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function _(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var St=class extends Ve{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function yr(r){return _(r)&&r.name==="AuthApiError"}var Ee=class extends Ve{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},K=class extends Ve{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},B=class extends K{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Te=class extends K{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ae=class extends K{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ce=class extends K{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}}},Ye=class extends K{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}}},xe=class extends K{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Et(r){return _(r)&&r.name==="AuthRetryableFetchError"}var Qe=class extends K{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Di=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},le=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Ni=[502,503,504];async function _r(r){var e;if(!fr(r))throw new xe(le(r),0);if(Ni.includes(r.status))throw new xe(le(r),r.status);let t;try{t=await r.json()}catch(n){throw new Ee(le(n),n)}let s,i=gr(r);if(i&&i.getTime()>=es["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new Qe(le(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new Qe(le(t),r.status,t.weak_password.reasons);throw new St(le(t),r.status||500,s)}var Mi=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function S(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[Je]||(n[Je]=es["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await qi(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function qi(r,e,t,s,i,n){let o=Mi(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new xe(le(c),0)}if(a.ok||await _r(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await _r(c)}}function V(r){var e;let t=null;Fi(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=hr(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function rs(r){let e=V(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function G(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function wr(r){return{data:r,error:null}}function vr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Di(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function br(r){return r}function Fi(r){return r.access_token&&r.refresh_token&&r.expires_in}var Hi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},ue=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=bt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(_(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:G})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Hi(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:vr,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:G})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:br});if(l.error)throw l.error;let h=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(y=>{let w=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(y.split(";")[1].split("=")[1]);u[`${v}Page`]=w}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(_(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:G})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:G})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:G})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var kr={getItem:r=>ee()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ee()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ee()&&globalThis.localStorage.removeItem(r)}};function is(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Sr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var he={debug:!!(globalThis&&ee()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Xe=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Tt=class extends Xe{};async function ns(r,e,t){he.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),he.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){he.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{he.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw he.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Tt(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(he.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Sr();var Wi={url:cr,storageKey:lr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ur,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ze=30*1e3,Er=3;async function Tr(r,e,t){return await t()}var de=class r{constructor(e){var t,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&&M()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},Wi),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new ue({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=bt(i.fetch),this.lock=i.lock||Tr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:M()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=ns:this.lock=Tr,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:ee()?this.storage=kr:(this.memoryStorage={},this.storage=is(this.memoryStorage)):(this.memoryStorage={},this.storage=is(this.memoryStorage)),M()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${wt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=M()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return _(e)?{error:e}:{error:new Ee("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:V}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:l,password:h,options:d}=e,p=null,y=null;this.flowType==="pkce"&&([p,y]=await oe(this.storage,this.storageKey)),n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:h,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:p,code_challenge_method:y},xform:V})}else if("phone"in e){let{phone:l,password:h,options:d}=e;n=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:h,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:V})}else throw new ae("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:rs})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:rs})}else throw new ae("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Te}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ke(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:V});return await kt(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new Te}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:i,access_token:n,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:V}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Te}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await oe(this.storage,this.storageKey));let{error:h}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:u?.message_id},error:l}}throw new ae("You must provide either an email or phone number.")}catch(a){if(_(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:V});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(_(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await oe(this.storage,this.storageKey)),await S(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:wr})}catch(n){if(_(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new B;let{error:i}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(_(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await S(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:i,options:n}=e,{data:o,error:a}=await S(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new ae("You must provide either an email or phone number and a type")}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ke(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,u,l)=>(!o&&u==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,u,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:G}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new B}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:G})})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new B;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await oe(this.storage,this.storageKey));let{data:u,error:l}=await S(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:G});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return ss(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new B;let t=Date.now()/1e3,s=t,i=!0,n=null,o=ss(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new B;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!M())throw new ce("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ce("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ye("Not a valid PKCE flow url.");let t=vt(window.location.href);if(e){if(!t.code)throw new Ye("No code detected.");let{data:$,error:O}=await this._exchangeCodeForSession(t.code);if(O)throw O;let g=new URL(window.location.href);return g.searchParams.delete("code"),window.history.replaceState(window.history.state,"",g.toString()),{data:{session:$.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ce(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:u}=t;if(!n||!a||!o||!u)throw new ce("No session defined in URL");let l=Math.round(Date.now()/1e3),h=parseInt(a),d=l+h;c&&(d=parseInt(c));let p=d-l;p*1e3<=Ze&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);let y=d-h;l-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,d,l):l-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,d,l);let{data:w,error:v}=await this._getUser(n);if(v)throw v;let C={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:u,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:C,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=vt(window.location.href);return!!(M()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=vt(window.location.href),t=await Ke(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{error:n};let o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(yr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await kt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=dr(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,i=null;this.flowType==="pkce"&&([s,i]=await oe(this.storage,this.storageKey,!0));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,u,l;let{data:h,error:d}=n;if(d)throw d;let p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await S(this.fetch,"GET",p,{headers:this.headers,jwt:(l=(u=h.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return M()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(_(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await mr(async i=>(i>0&&await pr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Et(n)&&Date.now()+o-s<Ze})}catch(s){if(this._debug(t,"error",s),_(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),M()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await Ke(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<i+Zt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Zt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Et(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new B;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ze;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new B;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),_(n)){let o={session:null,error:n};return Et(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await ts(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await kt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&M()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Ze);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((s.expires_at*1e3-e)/Ze);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ze}ms, refresh threshold is ${Er} ticks`),i<=Er&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Xe)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!M()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await oe(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await S(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};de.nextInstanceID=0;var Bi=de,os=Bi;var xt=class extends os{constructor(e){super(e)}};var Gi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(h){o(h)}}function c(l){try{u(s.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},et=class{constructor(e,t,s){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=or(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,u={db:sr,realtime:ir,auth:Object.assign(Object.assign({},rr),{storageKey:c}),global:tr},l=ar(s??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=nr(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Fs(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Oe(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Be(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}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 Gi(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,storageKey:n,flowType:o,debug:a},c,u){var l;let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new xt({url:this.authUrl,headers:Object.assign(Object.assign({},h),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new ve(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var xr=(r,e,t)=>new et(r,e,t);var Y={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Ji=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},At=r=>{let[e,t]=r.split(".");return!e||!t?null:Ji(t)},Ar=r=>{let e=At(r);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var zi="https://api.workos.com",Ki=60,Ae=(r,e)=>typeof r[e]=="string"?r[e]:void 0,Pr=(r,e,t)=>{let s=At(r);if(!s)return null;let i=Ae(s,"urn:wispr:user_external_id")??Ae(s,"sub"),n=t?.email??Ae(s,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof s.exp=="number"?s.exp:void 0,c={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},Vi=async(r,e,t,s)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):zi,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:r,organization_id:s})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},Rr=async(r,e)=>{let t=At(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=Ae(t,"client_id");if(i-s<Ki&&n){let c=await Vi(e,n,Ae(t,"iss"),Ae(t,"org_id")),u=Pr(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=s)throw new Error("WorkOS session expired");let a=Pr(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var tt=class{constructor(){this.sessionData=null;this.supabase=xr(Y.supaBaseUrl,Y.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||Y.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||Y.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||Y.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let i=new Date;i.setTime(i.getTime()+s*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{if(Ar(t)==="workos"){this.sessionData=await Rr(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,i]=t.split("=");return e[s]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||Y.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,i,n){try{if(!n)throw new Error("Please complete the verification");await Q.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:n,redirect_url:i||Y.redirectUri}),console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await Q.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:i?.provision??!1,workos_capable:i?.workosCapable});if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in successful for:",e),{accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,s){try{if(!s)throw new Error("Please complete the verification");await Q.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||Y.redirectUri}),console.log("Verification email resent to:",e)}catch(i){throw console.error("Error resending verification email:",i),i}}async getUser(){let{data:e,error:t}=await this.supabase.auth.getUser();if(t)throw t;return e.user}async getSession(){let{data:e,error:t}=await this.supabase.auth.getSession();if(t)throw t;return e.session}};var J=null;function Pt(r,e=30,t){J&&(clearInterval(J),J=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,J=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",J&&(clearInterval(J),J=null),t&&t())},1e3)}function as(){J&&(clearInterval(J),J=null)}var Cr=/^[\p{L}\p{M}\s\-'.]+$/u;function Yi(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Cr.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Rt(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Cr.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function cs(r,e,t){let s="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let u=document.getElementById(s);u||(u=document.createElement("div"),u.id=s,u.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",u)),u.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=Yi(e.value,r.value);c?i(c):n()},a=()=>{let c=Rt(e.value,r.value);c?i(c):n()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var Ct=(r,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:r,retry_attempt:10-t}),window.posthog.capture(r,e)):t>0&&setTimeout(()=>Ct(r,e,t-1),200)};var Qi="wisprjam.com",Xi="wispr.ai",Zi=r=>r.trim().toLowerCase().split("@")[1]??"",Or=r=>{let e=Zi(r);return e===Qi||e===Xi};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=localStorage.getItem("checkout_debug");if(r){try{let f=JSON.parse(r);Ct("checkout_debug",{...f,reported_from:"get_started",ms_since_error:Date.now()-(f.timestamp??Date.now())})}catch{}localStorage.removeItem("checkout_debug")}let e=!1,t=setTimeout(()=>{e||(document.body.style.visibility="visible")},4e3),s=new tt,{accessToken:i,refreshToken:n}=xs(),o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),u=document.querySelector("#full-name"),l=document.querySelector("#google-login"),h=document.querySelector("#apple-login"),d=document.querySelector("#microsoft-login"),p;(T=>(T.EMAIL_INPUT="email_input",T.LOGIN="login",T.SIGNUP="signup",T.OAUTH_USER="oauth_user",T.UNVERIFIED_EMAIL="unverified_email"))(p||(p={}));let y="email_input",w=document.querySelector("[email-element]"),v=document.querySelector("[different-provider]"),C=document.querySelector("[different-provider-name]"),$=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),g=document.querySelector("[email-signup-error]"),E=document.querySelector("[error-message]"),ls=document.querySelector("[verification-email]"),Pe=document.querySelector("[email-signup-retry]"),us=document.querySelector("[email-signup-reset]"),fe=document.querySelector("[scim-div]"),hs=document.querySelector("[scim-reset]"),U=document.querySelector("[forgot-password]"),st=document.querySelector("[forgot-password-success]"),ds=document.querySelector("[forgot-password-email]"),pe=document.querySelector("[unverified-email]"),fs=document.querySelector("[unverified-email-address]"),q=document.querySelector("[resend-verification-email]"),ps=document.querySelector("[unverified-email-reset]"),Lr=localStorage.getItem("email"),ms=localStorage.getItem("last_authed_provider");ms&&{google:l,apple:h,microsoft:d,sso:document.querySelector("#sso-login"),email:a}[ms]?.classList.add("last-used");let me=new URLSearchParams(window.location.search),gs=me.get("referral"),ys=me.get("plan"),_s=me.get("utm_source"),Ir=me.get("redirect"),ws=me.get("team_invite_code"),en=me.get("code"),jr=Ir==="android-waitlist"?"/android-waitlist":"/downloads",F=`${window.location.origin}${jr}`,ge=new URLSearchParams;gs&&ge.append("referral",gs),ys&&ge.append("plan",ys),_s&&ge.append("utm_source",_s),ws&&ge.append("team_invite_code",ws),ge.toString()&&(F+=`?${ge.toString()}`);let $r=()=>{try{let f=document.cookie.split("; ");for(let m of f){let b=m.indexOf("=");if(b===-1||m.slice(0,b)!=="wispr_auth")continue;let A=m.slice(b+1),T=decodeURIComponent(A);return JSON.parse(T)}return null}catch{return null}};if(i&&n)try{s.setCookies(i,n);let f=s.checkAndSetSession(),m=new Promise((k,A)=>setTimeout(()=>A(new Error("Session timeout")),3e3));await Promise.race([f,m]),s.sessionData&&s.setCookies(s.sessionData.access_token,s.sessionData.refresh_token);let b=s.sessionData?.user.email;localStorage.setItem("email",b),e=!0,clearTimeout(t),window.location.href=F}catch(f){console.error("Error during session setup:",f),document.body.style.visibility="visible"}else{let f=$r();if(f?.access_token&&f?.refresh_token)try{s.setCookies(f.access_token,f.refresh_token);let m=s.checkAndSetSession(),b=new Promise((T,D)=>setTimeout(()=>D(new Error("Session timeout")),3e3));await Promise.race([m,b]),s.sessionData&&s.setCookies(s.sessionData.access_token,s.sessionData.refresh_token);let k=s.sessionData?.user.email,A=s.sessionData?.user.app_metadata.provider||"typing_test";localStorage.setItem("email",k),localStorage.setItem("signin_provider",A),e=!0,clearTimeout(t),window.location.href=F}catch(m){console.error("Error authenticating from typing test session:",m),f.email&&(a.value=f.email),document.body.style.visibility="visible"}else f?.email?(a.value=f.email,document.body.style.visibility="visible"):(Lr&&localStorage.removeItem("email"),document.body.style.visibility="visible")}l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await s.signInWithGoogle(F)}catch(f){console.error("Error during sign-in:",f)}}),h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await s.signInWithApple(F)}catch(f){console.error("Error during sign-in:",f)}}),d.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await s.signInWithMicrosoft(F)}catch(f){console.error("Error during sign-in:",f)}});let rt=()=>{v&&(v.style.display="none"),O&&(O.style.display="none"),g&&(g.style.display="none"),pe&&(pe.style.display="none"),fe&&(fe.style.display="none"),U&&(U.style.display="none"),st&&(st.style.display="none");let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="block"),w&&(w.style.display="flex"),a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled"),c.value="",c.style.display="none",c.removeAttribute("required"),u.value="",u.style.display="none",u.removeAttribute("required");let m=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");m&&(m.style.display="none"),b&&(b.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),y="email_input",a.focus()},Ur=()=>{a.setAttribute("readonly","true"),a.classList.add("disabled"),c.style.display="block",c.setAttribute("required","true"),c.focus(),u.style.display="none",u.removeAttribute("required");let f=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),m&&(m.style.display="block"),U&&(U.style.display="block",U.onclick=async()=>{let b=a.value,k=U.textContent||"";try{let{hcaptcha:A}=window;if(!A)throw new Error("Verification system not loaded. Please refresh the page.");U.style.pointerEvents="none",U.textContent="Sending...";let{response:T}=await A.execute({async:!0});if(!T)throw new Error("Verification cancelled");await Q.requestPasswordReset(b,T),A.reset(),w&&(w.style.display="none"),U&&(U.style.display="none"),st&&(st.style.display="block"),ds&&(ds.textContent=b)}catch(A){console.error("\u274C Error sending password reset email:",A),U.textContent=k,U.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),g&&(g.style.display="block",E&&(E.textContent=A instanceof Error?A.message:"Failed to send reset email"))}}),y="login",console.log("\u2705 Existing user detected - showing login form")},vs=()=>{a.setAttribute("readonly","true"),a.classList.add("disabled"),c.style.display="block",c.setAttribute("required","true"),u.style.display="block",u.setAttribute("required","true"),c.focus();let f=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");f&&(f.style.display="block"),m&&(m.style.display="block"),y="signup",console.log("\u2705 New user detected - showing signup form")},Dr=()=>{let f=document.querySelector(".gs-hero_form-block");f&&(f.style.display="none"),fe&&(fe.style.display="block"),hs&&(hs.onclick=()=>{fe&&(fe.style.display="none"),f&&(f.style.display="block"),rt()})},bs=f=>{let m=Lt(f);w&&(w.style.display="none"),v&&(v.style.display="block"),C&&(C.textContent=m),$&&($.onclick=()=>{v&&(v.style.display="none"),rt()}),y="oauth_user"},Nr=f=>{w&&(w.style.display="none"),pe&&(pe.style.display="block"),fs&&(fs.textContent=f),q&&(q.onclick=async()=>{let m=q.textContent||"";try{let b=window.hcaptcha;if(!b)throw new Error("Verification system not loaded. Please refresh the page.");q.textContent="Verifying...",q.style.pointerEvents="none";let{response:k}=await b.execute({async:!0});if(!k)throw new Error("Verification cancelled");q.textContent="Sending...",await s.resendVerificationEmail(f,F,k),q.textContent="Verification email resent! \u2705",q.style.textDecoration="none",console.log("\u2705 Verification email resent to:",f),g&&(g.style.display="none"),b.reset()}catch(b){if(console.error("\u274C Error resending verification email:",b),q.textContent=m,q.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),g&&(g.style.display="block",E)){let k=b instanceof Error?b.message:"Failed to resend verification email";E.textContent=k}}}),ps&&(ps.onclick=()=>{pe&&(pe.style.display="none"),rt()}),y="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},Mr=async(f,m)=>{let b=m.value;m.classList.add("loading"),m.value="";try{let k=await Q.checkUserStatus(f);console.log("User status check:",k),m.classList.remove("loading"),m.value=b,!k.exists&&k.scim_managed?Dr():k.enforce_sso?bs("workos"):k.exists&&k.provider&&k.provider!=="email"?bs(k.provider):k.exists&&k.provider==="email"&&!k.verified?Nr(f):k.exists&&k.provider==="email"?Ur():vs()}catch(k){console.error("\u274C Error checking user status:",k),m.classList.remove("loading"),m.value=b,vs()}},qr=async(f,m,b,k)=>{if(!m||m.length<8){g&&(g.style.display="block",E&&(E.textContent="Password must be at least 8 characters"));return}let A=window.hcaptcha?.getResponse()||"";if(!A){g&&(g.style.display="block",E&&(E.textContent="Please complete the verification"));return}b.classList.add("loading"),b.value="";try{console.log("\u2705 Attempting login for:",f);let{accessToken:T,refreshToken:D}=await s.signInWithPassword(f,m,A,{workosCapable:Or(f),provision:!1});s.setCookies(T,D),localStorage.setItem("email",f),e=!0,clearTimeout(t),window.location.href=F}catch(T){if(console.error("\u274C Login error:",T),window.hcaptcha&&window.hcaptcha.reset(),b.classList.remove("loading"),b.value=k,g&&(g.style.display="block",E)){let D=T instanceof Error?T.message:"Invalid login credentials";E.textContent=D}}},Fr=async(f,m,b,k,A)=>{if(!m||m.length<8){g&&(g.style.display="block",E&&(E.textContent="Password must be at least 8 characters"));return}if(!b||b.trim().length<2){g&&(g.style.display="block",E&&(E.textContent="Please enter your full name"));return}let T=Rt(b,m);if(T){g&&(g.style.display="block",E&&(E.textContent=T));return}let D=window.hcaptcha?.getResponse()||"";if(!D){g&&(g.style.display="block",E&&(E.textContent="Please complete the verification"));return}k.classList.add("loading"),k.value="";try{console.log("\u2705 Creating new account for:",f),await s.signUpWithPassword(f,m,b,F,D),window.hcaptcha&&window.hcaptcha.reset(),k.classList.remove("loading"),k.value=A,w&&(w.style.display="none"),g&&(g.style.display="none"),O&&(O.style.display="block"),ls&&(ls.textContent=f),Pe&&(Pt(Pe,30),Pe.onclick=async()=>{if(Pe.style.pointerEvents!=="none")try{let z=window.hcaptcha?.getResponse()||"";await s.resendVerificationEmail(f,F,z),window.hcaptcha&&window.hcaptcha.reset(),Pt(Pe,30),console.log("\u2705 Verification email resent to:",f)}catch(z){console.error("\u274C Error resending verification email:",z)}}),us&&(us.onclick=()=>{O&&(O.style.display="none"),as(),rt()})}catch(z){if(console.error("\u274C Signup error:",z),k.classList.remove("loading"),k.value=A,g&&(g.style.display="block",E)){let Hr=z instanceof Error?z.message:"Signup failed";E.textContent=Hr}}};cs(c,u,o.querySelector('[type="submit"]')),o.addEventListener("submit",async f=>{f.stopPropagation(),f.preventDefault();let m=a.value,b=c?.value||"",k=u?.value||"";if(!m||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m)){console.error("\u274C Email invalid"),g&&(g.style.display="block",E&&(E.textContent="Please enter a valid email address"));return}g&&(g.style.display="none"),E&&(E.textContent="");let T=o.querySelector('[type="submit"]'),D=T?.value||"";localStorage.setItem("signin_provider","email");try{y==="email_input"?await Mr(m,T):y==="login"?await qr(m,b,T,D):y==="signup"&&await Fr(m,b,k,T,D)}catch(z){console.error("\u274C Signup error:",z),T&&(T.classList.remove("loading"),T.value=D),g&&(g.style.display="block")}})});})();