@tanay-wispr/webflow-package 6.4.22 → 6.4.23
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 +1 -1
- package/package.json +1 -1
package/dist/signup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var bs=Object.create;var Ve=Object.defineProperty;var ks=Object.getOwnPropertyDescriptor;var Ss=Object.getOwnPropertyNames;var Es=Object.getPrototypeOf,Ts=Object.prototype.hasOwnProperty;var xs=(i,e)=>()=>(i&&(e=i(i=0)),e);var M=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),As=(i,e)=>{for(var t in e)Ve(i,t,{get:e[t],enumerable:!0})},ir=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ss(e))!Ts.call(i,s)&&s!==t&&Ve(i,s,{get:()=>e[s],enumerable:!(r=ks(e,s))||r.enumerable});return i};var nr=(i,e,t)=>(t=i!=null?bs(Es(i)):{},ir(e||!i||!i.__esModule?Ve(t,"default",{value:i,enumerable:!0}):t,i)),Ps=i=>ir(Ve({},"__esModule",{value:!0}),i);var X={};As(X,{Headers:()=>St,Request:()=>Cs,Response:()=>Is,default:()=>kt,fetch:()=>Rs});var Os,ue,Rs,kt,St,Cs,Is,V=xs(()=>{"use strict";Os=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")},ue=Os(),Rs=ue.fetch,kt=ue.fetch.bind(ue),St=ue.Headers,Cs=ue.Request,Is=ue.Response});var dr=M(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});var Et=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Tt.default=Et});var At=M(xe=>{"use strict";var fr=xe&&xe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(xe,"__esModule",{value:!0});var $s=fr((V(),Ps(X))),Ls=fr(dr()),xt=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=$s.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 r=this.fetch,s=r(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,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let P=await n.text();P===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=P:l=JSON.parse(P))}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,f="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,f="OK")}catch{n.status===404&&w===""?(d=204,f="No Content"):h={message:w}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new Ls.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(s=s.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:""}})),s.then(e,t)}};xe.default=xt});var Ot=M(Ae=>{"use strict";var Us=Ae&&Ae.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ae,"__esModule",{value:!0});var Ds=Us(At()),Pt=class extends Ds.default{select(e){let t=!1,r=(e??"*").split("").map(s=>/\s/.test(s)&&!t?"":(s==='"'&&(t=!t),s)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let n=typeof s>"u"?"offset":`${s}.offset`,o=typeof s>"u"?"limit":`${s}.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:r=!1,buffers:s=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"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}};Ae.default=Pt});var et=M(Pe=>{"use strict";var Ns=Pe&&Pe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Pe,"__esModule",{value:!0});var Ms=Ns(Ot()),Rt=class extends Ms.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(s=>typeof s=="string"&&new RegExp("[,()]").test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};Pe.default=Rt});var It=M(Re=>{"use strict";var qs=Re&&Re.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Re,"__esModule",{value:!0});var Oe=qs(et()),Ct=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=t,this.schema=r,this.fetch=s}select(e,{head:t=!1,count:r}={}){let s=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),r&&(this.headers.Prefer=`count=${r}`),new Oe.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let s="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,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 Oe.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),s&&a.push(`count=${s}`),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 Oe.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",s=[];return this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),this.headers.Prefer=s.join(","),new Oe.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new Oe.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Re.default=Ct});var pr=M(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.version=void 0;tt.version="0.0.0-automated"});var gr=M(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.DEFAULT_HEADERS=void 0;var Fs=pr();rt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Fs.version}`}});var _r=M(Ce=>{"use strict";var mr=Ce&&Ce.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ce,"__esModule",{value:!0});var Hs=mr(It()),Bs=mr(et()),zs=gr(),jt=class i{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},zs.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new Hs.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;r||s?(o=r?"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 Bs.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Ce.default=jt});var Sr=M(C=>{"use strict";var Ie=C&&C.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(C,"__esModule",{value:!0});C.PostgrestBuilder=C.PostgrestTransformBuilder=C.PostgrestFilterBuilder=C.PostgrestQueryBuilder=C.PostgrestClient=void 0;var yr=Ie(_r());C.PostgrestClient=yr.default;var vr=Ie(It());C.PostgrestQueryBuilder=vr.default;var wr=Ie(et());C.PostgrestFilterBuilder=wr.default;var br=Ie(Ot());C.PostgrestTransformBuilder=br.default;var kr=Ie(At());C.PostgrestBuilder=kr.default;C.default={PostgrestClient:yr.default,PostgrestQueryBuilder:vr.default,PostgrestFilterBuilder:wr.default,PostgrestTransformBuilder:br.default,PostgrestBuilder:kr.default}});var Ir=M((pn,Cr)=>{"use strict";Cr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var j="https://api.wisprflow.ai",bt=class{static async signupUser(e){try{let t=`${j}/signup`,s=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=s&&s.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(`${j}/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(`${j}/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(`${j}/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(`${j}/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(`${j}/user_status?email=${encodeURIComponent(e)}`)).json()}static async getSubscriptionStatus(e){return await fetch(`${j}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${j}/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,r){let s=`${j}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(s+=`¤cy=${r}`),await(await fetch(s,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${j}/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(`${j}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${j}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${j}/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,r){let s=new FormData;return s.append("screenshot",e),await fetch(`${j}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:s,signal:r})}};function or(i){return i==="azure"?"Microsoft":i.charAt(0).toUpperCase()+i.slice(1)}var ar=bt;var cr=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,r]=e.split("=");return i[t]=r,i},{});var lr=()=>{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 hr=()=>{let{access_token:i,refresh_token:e}=lr(),t=i,r=e;if(!t||!r){let s=cr();t=s.access_token,r=s.refresh_token}return{accessToken:t,refreshToken:r}};var ur=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),X)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var Ee=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Ye=class extends Ee{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Qe=class extends Ee{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Xe=class extends Ee{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ze;(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"})(Ze||(Ze={}));var js=function(i,e,t,r){function s(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(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((r=r.apply(i,e||[])).next())})},Te=class{constructor(e,{headers:t={},customFetch:r,region:s=Ze.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=ur(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return js(this,void 0,void 0,function*(){try{let{headers:s,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&(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),s),body:h}).catch(g=>{throw new Ye(g)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new Qe(l);if(!l.ok)throw new Xe(l);let d=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(s){return{data:null,error:s}}})}};var Er=nr(Sr(),1),{PostgrestClient:Tr,PostgrestQueryBuilder:Ki,PostgrestFilterBuilder:Vi,PostgrestTransformBuilder:Yi,PostgrestBuilder:Qi}=Er.default;var xr="2.10.2";var Ar={"X-Client-Info":`realtime-js/${xr}`},Pr="1.0.0",it=1e4,Or=1e3,Z;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(Z||(Z={}));var $;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})($||($={}));var L;(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"})(L||(L={}));var st;(function(i){i.websocket="websocket"})(st||(st={}));var Y;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(Y||(Y={}));var je=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+s));o=o+s;let c=r.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var ee=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 E;(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"})(E||(E={}));var Lt=(i,e,t={})=>{var r;let s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Gs(o,i,e,s),n),{})},Gs=(i,e,t,r)=>{let s=e.find(a=>a.name===i),n=s?.type,o=t[i];return n&&!r.includes(n)?Rr(n,o):$t(o)},Rr=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return Vs(e,t)}switch(i){case E.bool:return Js(e);case E.float4:case E.float8:case E.int2:case E.int4:case E.int8:case E.numeric:case E.oid:return Ws(e);case E.json:case E.jsonb:return Ks(e);case E.timestamp:return Ys(e);case E.abstime:case E.date:case E.daterange:case E.int4range:case E.int8range:case E.money:case E.reltime:case E.text:case E.time:case E.timestamptz:case E.timetz:case E.tsrange:case E.tstzrange:return $t(e);default:return $t(e)}},$t=i=>i,Js=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Ws=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Ks=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Vs=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,r=i[t];if(i[0]==="{"&&r==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Rr(e,a))}return i},Ys=i=>typeof i=="string"?i.replace(" ","T"):i,nt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var te=class{constructor(e,t,r={},s=it){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Ut;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Ut||(Ut={}));var de=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,s,n,o),this.pendingDiffs.forEach(c=>{this.state=i.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=i.syncDiff(this.state,s,n,o),a())}),this.onJoin((s,n,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:n,newPresences:o})}),this.onLeave((s,n,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){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),f=u.map(b=>b.presence_ref),g=l.filter(b=>f.indexOf(b.presence_ref)<0),w=u.filter(b=>d.indexOf(b.presence_ref)<0);g.length>0&&(a[h]=g),w.length>0&&(c[h]=w)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},r,s)}static syncDiff(e,t,r,s){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),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(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}r(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,s(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let s=e[r];return"metas"in s?t[r]=s.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Dt;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Dt||(Dt={}));var Nt;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Nt||(Nt={}));var Mt;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(Mt||(Mt={}));var fe=class i{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=$.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new te(this,L.join,this.params,this.timeout),this.rejoinTimer=new ee(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=$.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=$.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=$.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=$.errored,this.rejoinTimer.scheduleTimeout())}),this._on(L.reply,{},(s,n)=>{this._trigger(this._replyEventName(n),s)}),this.presence=new de(this),this.broadcastEndpointURL=nt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,s;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:(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&s!==void 0?s:[],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,f=(u=d?.length)!==null&&u!==void 0?u:0,g=[];for(let w=0;w<f;w++){let b=d[w],{filter:{event:P,schema:O,table:m,filter:k}}=b,I=l&&l[w];if(I&&I.event===P&&I.schema===O&&I.table===m&&I.filter===k)g.push(Object.assign(Object.assign({},b),{id:I.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=g,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,r){return this._on(e,t,r)}async send(e,t={}){var r,s;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,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.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=$.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(L.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let s=new te(this,L.leave,{},e);s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new te(this,e,t,r);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=L;if(r&&[a,c,h,l].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var g,w,b;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((b=(w=f.filter)===null||w===void 0?void 0:w.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var g,w,b,P,O,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let k=f.id,I=(g=f.filter)===null||g===void 0?void 0:g.event;return k&&((w=t.ids)===null||w===void 0?void 0:w.includes(k))&&(I==="*"||I?.toLocaleLowerCase()===((b=t.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{let k=(O=(P=f?.filter)===null||P===void 0?void 0:P.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return k==="*"||k===((m=t?.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let g=d.data,{schema:w,table:b,commit_timestamp:P,type:O,errors:m}=g;d=Object.assign(Object.assign({},{schema:w,table:b,commit_timestamp:P,eventType:O,new:{},old:{},errors:m}),this._getPayloadRecords(g))}f.callback(d,r)})}_isClosed(){return this.state===$.closed}_isJoined(){return this.state===$.joined}_isJoining(){return this.state===$.joining}_isLeaving(){return this.state===$.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(s=>{var n;return!(((n=s.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&i.isEqual(s.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(L.close,{},e)}_onError(e){this._on(L.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=$.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Lt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Lt(e.columns,e.old_record)),t}};var Xs=()=>{},Zs=typeof WebSocket<"u",pe=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ar,this.params={},this.timeout=it,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Xs,this.conn=null,this.sendBuffer=[],this.serializer=new je,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(V(),X)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${st.websocket}`,this.httpEndpoint=nt(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 s=(r=t?.params)===null||r===void 0?void 0:r.apikey;s&&(this.accessToken=s,this.apiKey=s),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 ee(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(Zs){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new qt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>nr(Ir())).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,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Z.connecting:return Y.Connecting;case Z.open:return Y.Open;case Z.closing:return Y.Closing;default:return Y.Closed}}isConnected(){return this.connectionState()===Y.Open}channel(e,t={config:{}}){let r=new fe(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:s,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${r} (${n})`,s),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(L.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(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._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:Pr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:s,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||s===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${s} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(s,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(L.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_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(Or,"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,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Z.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var ge=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function A(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var ot=class extends ge{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},$e=class extends ge{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var ei=function(i,e,t,r){function s(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(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((r=r.apply(i,e||[])).next())})},at=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),X)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},jr=()=>ei(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(V(),X))).Response:Response});var me=function(i,e,t,r){function s(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(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((r=r.apply(i,e||[])).next())})},Ft=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),ti=(i,e)=>me(void 0,void 0,void 0,function*(){let t=yield jr();i instanceof t?i.json().then(r=>{e(new ot(Ft(r),i.status||500))}).catch(r=>{e(new $e(Ft(r),r))}):e(new $e(Ft(i),i))}),ri=(i,e,t,r)=>{let s={method:i,headers:e?.headers||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};function ct(i,e,t,r,s,n){return me(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,ri(e,r,s,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>ti(c,a))})})}function Le(i,e,t,r){return me(this,void 0,void 0,function*(){return ct(i,"GET",e,t,r)})}function q(i,e,t,r,s){return me(this,void 0,void 0,function*(){return ct(i,"POST",e,r,s,t)})}function $r(i,e,t,r,s){return me(this,void 0,void 0,function*(){return ct(i,"PUT",e,r,s,t)})}function lt(i,e,t,r,s){return me(this,void 0,void 0,function*(){return ct(i,"DELETE",e,r,s,t)})}var U=function(i,e,t,r){function s(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(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((r=r.apply(i,e||[])).next())})},si={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Lr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ue=class{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=at(s)}uploadOrUpdate(e,t,r,s){return U(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Lr),s),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,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(A(n))return{data:null,error:n};throw n}})}upload(e,t,r){return U(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return U(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:Lr.upsert},s),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",h.cacheControl)):(c=r,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(A(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return U(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),s=Object.assign({},this.headers);t?.upsert&&(s["x-upsert"]="true");let n=yield q(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ge("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}update(e,t,r){return U(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return U(this,void 0,void 0,function*(){try{return{data:yield q(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}copy(e,t,r){return U(this,void 0,void 0,function*(){try{return{data:{path:(yield q(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,r){return U(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=yield q(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return U(this,void 0,void 0,function*(){try{let s=yield q(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}download(e,t){return U(this,void 0,void 0,function*(){let s=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 Le(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(A(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&s.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&s.push(c);let h=s.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return U(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}list(e,t,r){return U(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},si),t),{prefix:e||""});return{data:yield q(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Ur="2.6.0";var Dr={"X-Client-Info":`storage-js/${Ur}`};var _e=function(i,e,t,r){function s(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(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((r=r.apply(i,e||[])).next())})},De=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Dr),t),this.fetch=at(r)}listBuckets(){return _e(this,void 0,void 0,function*(){try{return{data:yield Le(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(A(e))return{data:null,error:e};throw e}})}getBucket(e){return _e(this,void 0,void 0,function*(){try{return{data:yield Le(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return _e(this,void 0,void 0,function*(){try{return{data:yield q(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return _e(this,void 0,void 0,function*(){try{return{data:yield $r(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}emptyBucket(e){return _e(this,void 0,void 0,function*(){try{return{data:yield q(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}deleteBucket(e){return _e(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}};var Ne=class extends De{constructor(e,t={},r){super(e,t,r)}from(e){return new Ue(this.url,this.headers,e,this.fetch)}};var Nr="2.44.4";var Me="";typeof Deno<"u"?Me="deno":typeof document<"u"?Me="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Me="react-native":Me="node";var ii={"X-Client-Info":`supabase-js-${Me}/${Nr}`},Mr={headers:ii},qr={schema:"public"},Fr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Hr={};V();var ni=function(i,e,t,r){function s(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(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((r=r.apply(i,e||[])).next())})},oi=i=>{let e;return i?e=i:typeof fetch>"u"?e=kt:e=fetch,(...t)=>e(...t)},ai=()=>typeof Headers>"u"?St:Headers,Br=(i,e,t)=>{let r=oi(t),s=ai();return(n,o)=>ni(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:i,h=new s(o?.headers);return h.has("apikey")||h.set("apikey",i),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};function zr(i){return i.replace(/\/$/,"")}function Gr(i,e){let{db:t,auth:r,realtime:s,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),r),realtime:Object.assign(Object.assign({},c),s),global:Object.assign(Object.assign({},h),n)}}var ht="2.64.4";var Jr="http://localhost:9999",Wr="supabase.auth.token";var Kr={"X-Client-Info":`gotrue-js/${ht}`},Ht=10;var qe="X-Supabase-Api-Version",Bt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Vr(i){return Math.round(Date.now()/1e3)+i}function Yr(){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 D=()=>typeof document<"u",re={tested:!1,writable:!1},Q=()=>{if(!D())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(re.tested)return re.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),re.tested=!0,re.writable=!0}catch{re.tested=!0,re.writable=!1}return re.writable};function ut(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,n)=>{e[n]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var dt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),X)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Qr=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",zt=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},He=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ft=async(i,e)=>{await i.removeItem(e)};function ci(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,s,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++)),r=o<<2|a>>4,s=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(r),c!=64&&s!=0&&(t=t+String.fromCharCode(s)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Fe=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Fe.promiseConstructor=Promise;function Gt(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 r=t[1];return JSON.parse(ci(r))}async function Xr(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Zr(i,e){return new Promise((r,s)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){s(o);return}}})()})}function li(i){return("0"+i.toString(16)).substr(-2)}function hi(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let n=0;n<56;n++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,li).join("")}async function ui(i){let t=new TextEncoder().encode(i),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(n=>String.fromCharCode(n)).join("")}function di(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function fi(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 ui(i);return di(t)}async function se(i,e,t=!1){let r=hi(),s=r;t&&(s+="/PASSWORD_RECOVERY"),await zt(i,`${e}-code-verifier`,s);let n=await fi(r);return[n,r===n?"plain":"s256"]}var pi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function es(i){let e=i.headers.get(qe);if(!e||!e.match(pi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Be=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function _(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var pt=class extends Be{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function ts(i){return _(i)&&i.name==="AuthApiError"}var ye=class extends Be{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},G=class extends Be{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},F=class extends G{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},ve=class extends G{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ie=class extends G{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ne=class extends G{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}}},ze=class extends G{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}}},we=class extends G{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function gt(i){return _(i)&&i.name==="AuthRetryableFetchError"}var Ge=class extends G{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var gi=function(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t},oe=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),mi=[502,503,504];async function rs(i){var e;if(!Qr(i))throw new we(oe(i),0);if(mi.includes(i.status))throw new we(oe(i),i.status);let t;try{t=await i.json()}catch(n){throw new ye(oe(n),n)}let r,s=es(i);if(s&&s.getTime()>=Bt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Ge(oe(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 Ge(oe(t),i.status,t.weak_password.reasons);throw new pt(oe(t),i.status||500,r)}var _i=(i,e,t,r)=>{let s={method:i,headers:e?.headers||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function v(i,e,t,r){var s;let n=Object.assign({},r?.headers);n[qe]||(n[qe]=Bt["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await yi(i,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function yi(i,e,t,r,s,n){let o=_i(e,r,s,n),a;try{a=await i(t,Object.assign({},o))}catch(c){throw console.error(c),new we(oe(c),0)}if(a.ok||await rs(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await rs(c)}}function J(i){var e;let t=null;vi(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Vr(i.expires_in)));let r=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:r},error:null}}function Jt(i){let e=J(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,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=i.weak_password),e}function H(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function ss(i){return{data:i,error:null}}function is(i){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n}=i,o=gi(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function ns(i){return i}function vi(i){return i.access_token&&i.refresh_token&&i.expires_in}var wi=function(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t},ae=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=dt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await v(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await v(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:H})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=wi(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await v(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:is,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await v(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:H})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await v(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&n!==void 0?n:""},xform:ns});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,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(g=>{let w=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(g.split(";")[1].split("=")[1]);h[`${b}Page`]=w}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(_(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await v(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:H})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await v(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:H})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await v(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:H})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await v(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await v(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 os={getItem:i=>Q()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{Q()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{Q()&&globalThis.localStorage.removeItem(i)}};function Wt(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function as(){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 ce={debug:!!(globalThis&&Q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Je=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},mt=class extends Je{};async function Kt(i,e,t){ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),ce.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:r.signal},async s=>{if(s){ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,s.name);try{return await t()}finally{ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,s.name)}}else{if(e===0)throw ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new mt(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(ce.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()}})}as();var bi={url:Jr,storageKey:Wr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Kr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},We=30*1e3,cs=3;async function ls(i,e,t){return await t()}var le=class i{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!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&&D()&&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 s=Object.assign(Object.assign({},bi),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new ae({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=dt(s.fetch),this.lock=s.lock||ls,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:D()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Kt:this.lock=ls,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?s.storage?this.storage=s.storage:Q()?this.storage=os:(this.memoryStorage={},this.storage=Wt(this.memoryStorage)):(this.memoryStorage={},this.storage=Wt(this.memoryStorage)),D()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ht}) ${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=D()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:s,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",s,"redirect type",n),await this._saveSession(s),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return _(e)?{error:e}:{error:new ye("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let n=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:J}),{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(_(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,s;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,g=null;this.flowType==="pkce"&&([f,g]=await se(this.storage,this.storageKey)),n=await v(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:f,code_challenge_method:g},xform:J})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(s=d?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:J})}else throw new ie("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(_(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 v(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:Jt})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await v(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:Jt})}else throw new ie("You must provide either an email or phone number and a password");let{data:r,error:s}=t;return s?{data:{user:null,session:null},error:s}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new ve}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.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 He(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(t??"").split("/"),{data:n,error:o}=await v(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:J});return await ft(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 ve}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:s??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:n,nonce:o}=e,a=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:J}),{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 ve}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,s,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await se(this.storage,this.storageKey));let{error:u}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!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 v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=c?.data)!==null&&s!==void 0?s:{},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 ie("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,r;try{let s,n;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:J});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(s){if(_(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,r,s;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await se(this.storage,this.storageKey)),await v(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e?.options)===null||s===void 0)&&s.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:ss})}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:r}=e;if(r)throw r;if(!t)throw new F;let{error:s}=await v(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}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:r,type:s,options:n}=e,{error:o}=await v(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:s,options:n}=e,{data:o,error:a}=await v(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new ie("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 r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await He(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(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:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:s},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 v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:H}):await this._useSession(async t=>{var r,s,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new F}:await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0,xform:H})})}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 r=>{let{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new F;let o=s.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await se(this.storage,this.storageKey));let{data:h,error:l}=await v(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:H});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(r){if(_(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return Gt(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 F;let t=Date.now()/1e3,r=t,s=!0,n=null,o=Gt(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){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:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new F;let{session:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!D())throw new ne("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ne("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new ze("Not a valid PKCE flow url.");let t=ut(window.location.href);if(e){if(!t.code)throw new ze("No code detected.");let{data:O,error:m}=await this._exchangeCodeForSession(t.code);if(m)throw m;let k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:O.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ne(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new ne("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=We&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let g=d-u;l-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,l):l-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,d,l);let{data:w,error:b}=await this._getUser(n);if(b)throw b;let P={provider_token:r,provider_refresh_token:s,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:P,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=ut(window.location.href);return!!(D()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=ut(window.location.href),t=await He(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return{error:n};let o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(ts(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await ft(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Yr(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await se(this.storage,this.storageKey,!0));try{return await v(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:s}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await v(this.fetch,"GET",f,{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(s)throw s;return D()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(_(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:o}=t;if(o)throw o;return await v(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s: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 r=Date.now();return await Zr(async s=>(s>0&&await Xr(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await v(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:J})),(s,n)=>{let o=200*Math.pow(2,s);return n&>(n)&&Date.now()+o-r<We})}catch(r){if(this._debug(t,"error",r),_(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),D()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await He(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let s=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<s+Ht;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Ht}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),gt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new F;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Fe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new F;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(s,"error",n),_(n)){let o={session:null,error:n};return gt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(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(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await zt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ft(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&D()&&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(),We);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/We);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${We}ms, refresh threshold is ${cs} ticks`),s<=cs&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Je)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D()||!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,r){let s=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await se(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);s.push(n.toString())}return r?.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?{data:null,error:n}:await v(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await v(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((s=a?.totp)===null||s===void 0)&&s.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(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 r;let{data:s,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?{data:null,error:n}:await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],s=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:s},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:s},error:n}=e;if(n)return{data:null,error:n};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(s.access_token),a=null;o.aal&&(a=o.aal);let c=a;((r=(t=s.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};le.nextInstanceID=0;var ki=le,Vt=ki;var _t=class extends Vt{constructor(e){super(e)}};var Si=function(i,e,t,r){function s(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(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((r=r.apply(i,e||[])).next())})},Ke=class{constructor(e,t,r){var s,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=zr(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:qr,realtime:Hr,auth:Object.assign(Object.assign({},Fr),{storageKey:c}),global:Mr},l=Gr(r??{},h);this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",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=Br(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Tr(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Te(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ne(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Si(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new _t({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new pe(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var hs=(i,e,t)=>new Ke(i,e,t);var W={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var yt=class{constructor(){this.sessionData=null;this.supabase=hs(W.supaBaseUrl,W.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||W.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||W.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||W.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:r,error:s}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(s)throw s;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw this.signOut(),console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let s=new Date;s.setTime(s.getTime()+r*24*60*60*1e3);let n=`expires=${s.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{await this.setSession(t,r)}catch(s){throw s}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,s]=t.split("=");return e[r]=s,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:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||W.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,s,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:s||W.redirectUri,data:{full_name:r},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,r){try{let{data:s,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:r}});if(n)throw n;if(!s.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:s.session.access_token,refreshToken:s.session.refresh_token}}catch(s){throw console.error("Error signing in with password:",s),s}}async resendVerificationEmail(e,t,r){try{let{error:s}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||W.redirectUri,captchaToken:r}});if(s)throw s;console.log("Verification email resent to:",e)}catch(s){throw console.error("Error resending verification email:",s),s}}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 B=null;function Yt(i,e=30,t){B&&(clearInterval(B),B=null);let r=e;i.style.pointerEvents="none",i.textContent=`Resend (${r}s)`,B=setInterval(()=>{r=r-1,i.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(i.style.pointerEvents="auto",B&&(clearInterval(B),B=null),t&&t())},1e3)}function us(){B&&(clearInterval(B),B=null)}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=!1,e=setTimeout(()=>{i||(document.body.style.visibility="visible")},4e3),t=new yt,{accessToken:r,refreshToken:s}=hr(),n=document.querySelector("#email-form"),o=document.querySelector("#email-input"),a=document.querySelector("#password-input"),c=document.querySelector("#full-name"),h=document.querySelector("#google-login"),l=document.querySelector("#apple-login"),u=document.querySelector("#microsoft-login"),d;(x=>(x.EMAIL_INPUT="email_input",x.LOGIN="login",x.SIGNUP="signup",x.OAUTH_USER="oauth_user",x.UNVERIFIED_EMAIL="unverified_email"))(d||(d={}));let f="email_input",g=document.querySelector("[email-element]"),w=document.querySelector("[different-provider]"),b=document.querySelector("[different-provider-name]"),P=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),m=document.querySelector("[email-signup-error]"),k=document.querySelector("[error-message]"),I=document.querySelector("[verification-email]"),be=document.querySelector("[email-signup-retry]"),Qt=document.querySelector("[email-signup-reset]"),he=document.querySelector("[unverified-email]"),Xt=document.querySelector("[unverified-email-address]"),N=document.querySelector("[resend-verification-email]"),Zt=document.querySelector("[unverified-email-reset]"),ds=localStorage.getItem("email"),ke=new URLSearchParams(window.location.search),er=ke.get("referral"),tr=ke.get("plan"),rr=ke.get("utm_source"),fs=ke.get("redirect"),Ei=ke.get("code"),ps=fs==="android-waitlist"?"/android-waitlist":"/downloads",z=`${window.location.origin}${ps}`,Se=new URLSearchParams;if(er&&Se.append("referral",er),tr&&Se.append("plan",tr),rr&&Se.append("utm_source",rr),Se.toString()&&(z+=`?${Se.toString()}`),r&&s)try{t.setCookies(r,s);let p=t.checkAndSetSession(),y=new Promise((S,K)=>setTimeout(()=>K(new Error("Session timeout")),3e3));await Promise.race([p,y]);let T=t.sessionData?.user.email;localStorage.setItem("email",T),i=!0,clearTimeout(e),window.location.href=z}catch(p){console.error("Error during session setup:",p),document.body.style.visibility="visible"}else ds&&localStorage.removeItem("email"),document.body.style.visibility="visible";h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(z)}catch(p){console.error("Error during sign-in:",p)}}),l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(z)}catch(p){console.error("Error during sign-in:",p)}}),u.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(z)}catch(p){console.error("Error during sign-in:",p)}});let vt=()=>{w&&(w.style.display="none"),O&&(O.style.display="none"),m&&(m.style.display="none"),he&&(he.style.display="none"),g&&(g.style.display="flex"),o.value="",o.removeAttribute("readonly"),o.classList.remove("disabled"),a.value="",a.style.display="none",a.removeAttribute("required"),c.value="",c.style.display="none",c.removeAttribute("required");let p=document.querySelector("[captcha-embed]"),y=document.querySelector("#h-captcha-container");p&&(p.style.display="none"),y&&(y.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),f="email_input",o.focus()},gs=()=>{o.setAttribute("readonly","true"),o.classList.add("disabled"),a.style.display="block",a.setAttribute("required","true"),a.focus(),c.style.display="none",c.removeAttribute("required");let p=document.querySelector("[captcha-embed]"),y=document.querySelector("#h-captcha-container");p&&(p.style.display="block"),y&&(y.style.display="block"),f="login",console.log("\u2705 Existing user detected - showing login form")},sr=()=>{o.setAttribute("readonly","true"),o.classList.add("disabled"),a.style.display="block",a.setAttribute("required","true"),c.style.display="block",c.setAttribute("required","true"),a.focus();let p=document.querySelector("[captcha-embed]"),y=document.querySelector("#h-captcha-container");p&&(p.style.display="block"),y&&(y.style.display="block"),f="signup",console.log("\u2705 New user detected - showing signup form")},ms=p=>{let y=or(p);g&&(g.style.display="none"),w&&(w.style.display="block"),b&&(b.textContent=y),P&&(P.onclick=()=>{w&&(w.style.display="none"),vt()}),f="oauth_user"},_s=p=>{g&&(g.style.display="none"),he&&(he.style.display="block"),Xt&&(Xt.textContent=p),N&&(N.onclick=async()=>{let y=N.textContent||"";try{let T=window.hcaptcha;if(!T)throw new Error("Verification system not loaded. Please refresh the page.");N.textContent="Verifying...",N.style.pointerEvents="none";let{response:S}=await T.execute({async:!0});if(!S)throw new Error("Verification cancelled");N.textContent="Sending...",await t.resendVerificationEmail(p,z,S),N.textContent="Verification email resent! \u2705",N.style.textDecoration="none",console.log("\u2705 Verification email resent to:",p),m&&(m.style.display="none"),T.reset()}catch(T){if(console.error("\u274C Error resending verification email:",T),N.textContent=y,N.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),m&&(m.style.display="block",k)){let S=T instanceof Error?T.message:"Failed to resend verification email";k.textContent=S}}}),Zt&&(Zt.onclick=()=>{he&&(he.style.display="none"),vt()}),f="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},ys=async(p,y)=>{let T=y.value;y.classList.add("loading"),y.value="";try{let S=await ar.checkUserStatus(p);console.log("User status check:",S),y.classList.remove("loading"),y.value=T,S.exists&&S.provider&&S.provider!=="email"?ms(S.provider):S.exists&&S.provider==="email"&&!S.verified?_s(p):S.exists&&S.provider==="email"?gs():sr()}catch(S){console.error("\u274C Error checking user status:",S),y.classList.remove("loading"),y.value=T,sr()}},vs=async(p,y,T,S)=>{if(!y||y.length<8){m&&(m.style.display="block",k&&(k.textContent="Password must be at least 8 characters"));return}let K=window.hcaptcha?.getResponse()||"";if(!K){m&&(m.style.display="block",k&&(k.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{console.log("\u2705 Attempting login for:",p);let{accessToken:x,refreshToken:R}=await t.signInWithPassword(p,y,K);t.setCookies(x,R),localStorage.setItem("email",p),i=!0,clearTimeout(e),window.location.href=z}catch(x){if(console.error("\u274C Login error:",x),window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=S,m&&(m.style.display="block",k)){let R=x instanceof Error?x.message:"Invalid login credentials";k.textContent=R}}},ws=async(p,y,T,S,K)=>{if(!y||y.length<8){m&&(m.style.display="block",k&&(k.textContent="Password must be at least 8 characters"));return}if(!T||T.trim().length<2){m&&(m.style.display="block",k&&(k.textContent="Please enter your full name"));return}let x=window.hcaptcha?.getResponse()||"";if(!x){m&&(m.style.display="block",k&&(k.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{console.log("\u2705 Creating new account for:",p),await t.signUpWithPassword(p,y,T,z,x),window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=K,g&&(g.style.display="none"),m&&(m.style.display="none"),O&&(O.style.display="block"),I&&(I.textContent=p),be&&(Yt(be,30),be.onclick=async()=>{if(be.style.pointerEvents!=="none")try{let R=window.hcaptcha?.getResponse()||"";await t.signUpWithPassword(p,y,T,z,R),window.hcaptcha&&window.hcaptcha.reset(),Yt(be,30),console.log("\u2705 Verification email resent to:",p)}catch(R){console.error("\u274C Error resending verification email:",R)}}),Qt&&(Qt.onclick=()=>{O&&(O.style.display="none"),us(),vt()})}catch(R){if(console.error("\u274C Signup error:",R),S.classList.remove("loading"),S.value=K,m&&(m.style.display="block",k)){let wt=R instanceof Error?R.message:"Signup failed";k.textContent=wt}}};n.addEventListener("submit",async p=>{p.stopPropagation(),p.preventDefault();let y=o.value,T=a?.value||"",S=c?.value||"";if(!y||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(y)){console.error("\u274C Email invalid"),m&&(m.style.display="block",k&&(k.textContent="Please enter a valid email address"));return}m&&(m.style.display="none"),k&&(k.textContent="");let x=n.querySelector('[type="submit"]'),R=x?.value||"";localStorage.setItem("signin_provider","email");try{f==="email_input"?await ys(y,x):f==="login"?await vs(y,T,x,R):f==="signup"&&await ws(y,T,S,x,R)}catch(wt){console.error("\u274C Signup error:",wt),x&&(x.classList.remove("loading"),x.value=R),m&&(m.style.display="block")}})});})();
|
|
1
|
+
"use strict";(()=>{var kr=Object.create;var Ve=Object.defineProperty;var Sr=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var Tr=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty;var Ar=(i,e)=>()=>(i&&(e=i(i=0)),e);var F=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Pr=(i,e)=>{for(var t in e)Ve(i,t,{get:e[t],enumerable:!0})},is=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Er(e))!xr.call(i,r)&&r!==t&&Ve(i,r,{get:()=>e[r],enumerable:!(s=Sr(e,r))||s.enumerable});return i};var ns=(i,e,t)=>(t=i!=null?kr(Tr(i)):{},is(e||!i||!i.__esModule?Ve(t,"default",{value:i,enumerable:!0}):t,i)),Or=i=>is(Ve({},"__esModule",{value:!0}),i);var X={};Pr(X,{Headers:()=>St,Request:()=>Ir,Response:()=>jr,default:()=>kt,fetch:()=>Cr});var Rr,ue,Cr,kt,St,Ir,jr,V=Ar(()=>{"use strict";Rr=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")},ue=Rr(),Cr=ue.fetch,kt=ue.fetch.bind(ue),St=ue.Headers,Ir=ue.Request,jr=ue.Response});var ds=F(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});var Et=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Tt.default=Et});var At=F(xe=>{"use strict";var fs=xe&&xe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(xe,"__esModule",{value:!0});var Lr=fs((V(),Or(X))),Ur=fs(ds()),xt=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=Lr.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,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let P=await n.text();P===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=P:l=JSON.parse(P))}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,f="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,f="OK")}catch{n.status===404&&w===""?(d=204,f="No Content"):h={message:w}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new Ur.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});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)}};xe.default=xt});var Ot=F(Ae=>{"use strict";var Dr=Ae&&Ae.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ae,"__esModule",{value:!0});var Nr=Dr(At()),Pt=class extends Nr.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}};Ae.default=Pt});var et=F(Pe=>{"use strict";var Mr=Pe&&Pe.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Pe,"__esModule",{value:!0});var qr=Mr(Ot()),Rt=class extends qr.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}};Pe.default=Rt});var It=F(Re=>{"use strict";var Fr=Re&&Re.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Re,"__esModule",{value:!0});var Oe=Fr(et()),Ct=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 Oe.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 Oe.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 Oe.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 Oe.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 Oe.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Re.default=Ct});var ps=F(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.version=void 0;tt.version="0.0.0-automated"});var gs=F(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.DEFAULT_HEADERS=void 0;var Hr=ps();st.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Hr.version}`}});var _s=F(Ce=>{"use strict";var ms=Ce&&Ce.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ce,"__esModule",{value:!0});var Br=ms(It()),zr=ms(et()),Gr=gs(),jt=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Gr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new Br.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 zr.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Ce.default=jt});var Ss=F(C=>{"use strict";var Ie=C&&C.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(C,"__esModule",{value:!0});C.PostgrestBuilder=C.PostgrestTransformBuilder=C.PostgrestFilterBuilder=C.PostgrestQueryBuilder=C.PostgrestClient=void 0;var ys=Ie(_s());C.PostgrestClient=ys.default;var vs=Ie(It());C.PostgrestQueryBuilder=vs.default;var ws=Ie(et());C.PostgrestFilterBuilder=ws.default;var bs=Ie(Ot());C.PostgrestTransformBuilder=bs.default;var ks=Ie(At());C.PostgrestBuilder=ks.default;C.default={PostgrestClient:ys.default,PostgrestQueryBuilder:vs.default,PostgrestFilterBuilder:ws.default,PostgrestTransformBuilder:bs.default,PostgrestBuilder:ks.default}});var Is=F((gn,Cs)=>{"use strict";Cs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var j="https://api.wisprflow.ai",bt=class{static async signupUser(e){try{let t=`${j}/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(`${j}/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(`${j}/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(`${j}/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(`${j}/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(`${j}/user_status?email=${encodeURIComponent(e)}`)).json()}static async getSubscriptionStatus(e){return await fetch(`${j}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${j}/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=`${j}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`¤cy=${s}`),await(await fetch(r,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${j}/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(`${j}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${j}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${j}/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(`${j}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:r,signal:s})}};function os(i){return i==="azure"?"Microsoft":i.charAt(0).toUpperCase()+i.slice(1)}var as=bt;var cs=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var ls=()=>{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 hs=()=>{let{access_token:i,refresh_token:e}=ls(),t=i,s=e;if(!t||!s){let r=cs();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var us=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),X)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Ee=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Ye=class extends Ee{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Qe=class extends Ee{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Xe=class extends Ee{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ze;(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"})(Ze||(Ze={}));var $r=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())})},Te=class{constructor(e,{headers:t={},customFetch:s,region:r=Ze.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=us(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return $r(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(m=>{throw new Ye(m)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new Qe(l);if(!l.ok)throw new Xe(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(r){return{data:null,error:r}}})}};var Es=ns(Ss(),1),{PostgrestClient:Ts,PostgrestQueryBuilder:Vi,PostgrestFilterBuilder:Yi,PostgrestTransformBuilder:Qi,PostgrestBuilder:Xi}=Es.default;var xs="2.10.2";var As={"X-Client-Info":`realtime-js/${xs}`},Ps="1.0.0",it=1e4,Os=1e3,Z;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(Z||(Z={}));var $;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})($||($={}));var L;(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"})(L||(L={}));var rt;(function(i){i.websocket="websocket"})(rt||(rt={}));var Y;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(Y||(Y={}));var je=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 ee=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 T;(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"})(T||(T={}));var Lt=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Jr(o,i,e,r),n),{})},Jr=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?Rs(n,o):$t(o)},Rs=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return Yr(e,t)}switch(i){case T.bool:return Wr(e);case T.float4:case T.float8:case T.int2:case T.int4:case T.int8:case T.numeric:case T.oid:return Kr(e);case T.json:case T.jsonb:return Vr(e);case T.timestamp:return Qr(e);case T.abstime:case T.date:case T.daterange:case T.int4range:case T.int8range:case T.money:case T.reltime:case T.text:case T.time:case T.timestamptz:case T.timetz:case T.tsrange:case T.tstzrange:return $t(e);default:return $t(e)}},$t=i=>i,Wr=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Kr=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Vr=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Yr=(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=>Rs(e,a))}return i},Qr=i=>typeof i=="string"?i.replace(" ","T"):i,nt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var te=class{constructor(e,t,s={},r=it){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 Ut;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Ut||(Ut={}));var de=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),f=u.map(b=>b.presence_ref),m=l.filter(b=>f.indexOf(b.presence_ref)<0),w=u.filter(b=>d.indexOf(b.presence_ref)<0);m.length>0&&(a[h]=m),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(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.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 Dt;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Dt||(Dt={}));var Nt;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Nt||(Nt={}));var Mt;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(Mt||(Mt={}));var fe=class i{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=$.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new te(this,L.join,this.params,this.timeout),this.rejoinTimer=new ee(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=$.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=$.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=$.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=$.errored,this.rejoinTimer.scheduleTimeout())}),this._on(L.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new de(this),this.broadcastEndpointURL=nt(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,f=(u=d?.length)!==null&&u!==void 0?u:0,m=[];for(let w=0;w<f;w++){let b=d[w],{filter:{event:P,schema:R,table:_,filter:k}}=b,I=l&&l[w];if(I&&I.event===P&&I.schema===R&&I.table===_&&I.filter===k)m.push(Object.assign(Object.assign({},b),{id:I.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=m,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=$.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(L.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new te(this,L.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 te(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}=L;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(f=>{var m,w,b;return((m=f.filter)===null||m===void 0?void 0:m.event)==="*"||((b=(w=f.filter)===null||w===void 0?void 0:w.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var m,w,b,P,R,_;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let k=f.id,I=(m=f.filter)===null||m===void 0?void 0:m.event;return k&&((w=t.ids)===null||w===void 0?void 0:w.includes(k))&&(I==="*"||I?.toLocaleLowerCase()===((b=t.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{let k=(R=(P=f?.filter)===null||P===void 0?void 0:P.event)===null||R===void 0?void 0:R.toLocaleLowerCase();return k==="*"||k===((_=t?.event)===null||_===void 0?void 0:_.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let m=d.data,{schema:w,table:b,commit_timestamp:P,type:R,errors:_}=m;d=Object.assign(Object.assign({},{schema:w,table:b,commit_timestamp:P,eventType:R,new:{},old:{},errors:_}),this._getPayloadRecords(m))}f.callback(d,s)})}_isClosed(){return this.state===$.closed}_isJoined(){return this.state===$.joined}_isJoining(){return this.state===$.joining}_isLeaving(){return this.state===$.leaving}_replyEventName(e){return`chan_reply_${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(L.close,{},e)}_onError(e){this._on(L.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=$.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Lt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Lt(e.columns,e.old_record)),t}};var Zr=()=>{},ei=typeof WebSocket<"u",pe=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=As,this.params={},this.timeout=it,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Zr,this.conn=null,this.sendBuffer=[],this.serializer=new je,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(V(),X)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${rt.websocket}`,this.httpEndpoint=nt(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 ee(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(ei){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new qt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ns(Is())).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 Z.connecting:return Y.Connecting;case Z.open:return Y.Open;case Z.closing:return Y.Closing;default:return Y.Closed}}isConnected(){return this.connectionState()===Y.Open}channel(e,t={config:{}}){let s=new fe(`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(L.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:Ps}))}_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(L.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(Os,"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=Z.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var ge=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function A(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var ot=class extends ge{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},$e=class extends ge{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};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())})},at=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),X)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},js=()=>ti(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(V(),X))).Response:Response});var me=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=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),si=(i,e)=>me(void 0,void 0,void 0,function*(){let t=yield js();i instanceof t?i.json().then(s=>{e(new ot(Ft(s),i.status||500))}).catch(s=>{e(new $e(Ft(s),s))}):e(new $e(Ft(i),i))}),ri=(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 ct(i,e,t,s,r,n){return me(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,ri(e,s,r,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>si(c,a))})})}function Le(i,e,t,s){return me(this,void 0,void 0,function*(){return ct(i,"GET",e,t,s)})}function H(i,e,t,s,r){return me(this,void 0,void 0,function*(){return ct(i,"POST",e,s,r,t)})}function $s(i,e,t,s,r){return me(this,void 0,void 0,function*(){return ct(i,"PUT",e,s,r,t)})}function lt(i,e,t,s,r){return me(this,void 0,void 0,function*(){return ct(i,"DELETE",e,s,r,t)})}var D=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())})},ii={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ls={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ue=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=at(r)}uploadOrUpdate(e,t,s,r){return D(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Ls),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(A(n))return{data:null,error:n};throw n}})}upload(e,t,s){return D(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return D(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:Ls.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(A(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return D(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 H(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 ge("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}})}update(e,t,s){return D(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return D(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}})}copy(e,t,s){return D(this,void 0,void 0,function*(){try{return{data:{path:(yield H(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(A(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return D(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield H(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(A(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return D(this,void 0,void 0,function*(){try{let r=yield H(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(A(r))return{data:null,error:r};throw r}})}download(e,t){return D(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 Le(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(A(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 D(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}list(e,t,s){return D(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},ii),t),{prefix:e||""});return{data:yield H(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(A(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 Us="2.6.0";var Ds={"X-Client-Info":`storage-js/${Us}`};var _e=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())})},De=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Ds),t),this.fetch=at(s)}listBuckets(){return _e(this,void 0,void 0,function*(){try{return{data:yield Le(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(A(e))return{data:null,error:e};throw e}})}getBucket(e){return _e(this,void 0,void 0,function*(){try{return{data:yield Le(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return _e(this,void 0,void 0,function*(){try{return{data:yield H(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(A(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return _e(this,void 0,void 0,function*(){try{return{data:yield $s(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(A(s))return{data:null,error:s};throw s}})}emptyBucket(e){return _e(this,void 0,void 0,function*(){try{return{data:yield H(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}deleteBucket(e){return _e(this,void 0,void 0,function*(){try{return{data:yield lt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(A(t))return{data:null,error:t};throw t}})}};var Ne=class extends De{constructor(e,t={},s){super(e,t,s)}from(e){return new Ue(this.url,this.headers,e,this.fetch)}};var Ns="2.44.4";var Me="";typeof Deno<"u"?Me="deno":typeof document<"u"?Me="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Me="react-native":Me="node";var ni={"X-Client-Info":`supabase-js-${Me}/${Ns}`},Ms={headers:ni},qs={schema:"public"},Fs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Hs={};V();var oi=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())})},ai=i=>{let e;return i?e=i:typeof fetch>"u"?e=kt:e=fetch,(...t)=>e(...t)},ci=()=>typeof Headers>"u"?St:Headers,Bs=(i,e,t)=>{let s=ai(t),r=ci();return(n,o)=>oi(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 zs(i){return i.replace(/\/$/,"")}function Gs(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 ht="2.64.4";var Js="http://localhost:9999",Ws="supabase.auth.token";var Ks={"X-Client-Info":`gotrue-js/${ht}`},Ht=10;var qe="X-Supabase-Api-Version",Bt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Vs(i){return Math.round(Date.now()/1e3)+i}function Ys(){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 N=()=>typeof document<"u",se={tested:!1,writable:!1},Q=()=>{if(!N())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(se.tested)return se.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),se.tested=!0,se.writable=!0}catch{se.tested=!0,se.writable=!1}return se.writable};function ut(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 dt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),X)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Qs=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",zt=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},He=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ft=async(i,e)=>{await i.removeItem(e)};function li(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 Fe=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Fe.promiseConstructor=Promise;function Gt(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(li(s))}async function Xs(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Zs(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 hi(i){return("0"+i.toString(16)).substr(-2)}function ui(){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,hi).join("")}async function di(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 fi(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pi(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 di(i);return fi(t)}async function re(i,e,t=!1){let s=ui(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await zt(i,`${e}-code-verifier`,r);let n=await pi(s);return[n,s===n?"plain":"s256"]}var gi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function er(i){let e=i.headers.get(qe);if(!e||!e.match(gi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Be=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 pt=class extends Be{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function tr(i){return y(i)&&i.name==="AuthApiError"}var ye=class extends Be{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},J=class extends Be{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},B=class extends J{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},ve=class extends J{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ie=class extends J{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ne=class extends J{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}}},ze=class extends J{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}}},we=class extends J{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function gt(i){return y(i)&&i.name==="AuthRetryableFetchError"}var Ge=class extends J{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var mi=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},oe=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),_i=[502,503,504];async function sr(i){var e;if(!Qs(i))throw new we(oe(i),0);if(_i.includes(i.status))throw new we(oe(i),i.status);let t;try{t=await i.json()}catch(n){throw new ye(oe(n),n)}let s,r=er(i);if(r&&r.getTime()>=Bt["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 Ge(oe(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 Ge(oe(t),i.status,t.weak_password.reasons);throw new pt(oe(t),i.status||500,s)}var yi=(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 v(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[qe]||(n[qe]=Bt["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 vi(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 vi(i,e,t,s,r,n){let o=yi(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(c){throw console.error(c),new we(oe(c),0)}if(a.ok||await sr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await sr(c)}}function W(i){var e;let t=null;wi(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Vs(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function Jt(i){let e=W(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 rr(i){return{data:i,error:null}}function ir(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=mi(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 nr(i){return i}function wi(i){return i.access_token&&i.refresh_token&&i.expires_in}var bi=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},ae=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=dt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await v(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 v(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=bi(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await v(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:ir,redirectTo:t?.redirectTo})}catch(t){if(y(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await v(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 v(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:nr});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,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{let w=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(m.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 v(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 v(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 v(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 v(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 v(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 or={getItem:i=>Q()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{Q()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{Q()&&globalThis.localStorage.removeItem(i)}};function Wt(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function ar(){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 ce={debug:!!(globalThis&&Q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Je=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},mt=class extends Je{};async function Kt(i,e,t){ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),ce.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){ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw ce.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new mt(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(ce.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()}})}ar();var ki={url:Js,storageKey:Ws,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ks,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},We=30*1e3,cr=3;async function lr(i,e,t){return await t()}var le=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&&N()&&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({},ki),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 ae({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=dt(r.fetch),this.lock=r.lock||lr,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:N()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Kt:this.lock=lr,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:Q()?this.storage=or:(this.memoryStorage={},this.storage=Wt(this.memoryStorage)):(this.memoryStorage={},this.storage=Wt(this.memoryStorage)),N()&&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} (${ht}) ${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=N()?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 ye("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await v(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:W}),{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,f=null,m=null;this.flowType==="pkce"&&([f,m]=await re(this.storage,this.storageKey)),n=await v(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:f,code_challenge_method:m},xform:W})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await v(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:W})}else throw new ie("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 v(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:Jt})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await v(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:Jt})}else throw new ie("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 ve}:(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 He(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await v(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:W});return await ft(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 ve}:(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 v(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:W}),{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 ve}:(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 re(this.storage,this.storageKey));let{error:u}=await v(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 v(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 ie("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 v(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:W});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 re(this.storage,this.storageKey)),await v(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:rr})}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 B;let{error:r}=await v(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 v(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 v(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 ie("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 He(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 v(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 B}:await v(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 B;let o=r.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await re(this.storage,this.storageKey));let{data:h,error:l}=await v(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 Gt(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,r=!0,n=null,o=Gt(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 B;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(!N())throw new ne("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ne("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new ze("Not a valid PKCE flow url.");let t=ut(window.location.href);if(e){if(!t.code)throw new ze("No code detected.");let{data:R,error:_}=await this._exchangeCodeForSession(t.code);if(_)throw _;let k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:R.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ne(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 ne("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=We&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let m=d-u;l-m>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,d,l):l-m<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",m,d,l);let{data:w,error:b}=await this._getUser(n);if(b)throw b;let P={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:P,redirectType:t.type},error:null}}catch(t){if(y(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=ut(window.location.href);return!!(N()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=ut(window.location.href),t=await He(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&&!(tr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await ft(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ys(),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 re(this.storage,this.storageKey,!0));try{return await v(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 f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await v(this.fetch,"GET",f,{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 N()&&!(!((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 v(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 Zs(async r=>(r>0&&await Xs(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await v(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:W})),(r,n)=>{let o=200*Math.pow(2,r);return n&>(n)&&Date.now()+o-s<We})}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),N()&&!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 He(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+Ht;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Ht}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),gt(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 r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new Fe;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(r,"error",n),y(n)){let o={session:null,error:n};return gt(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 zt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ft(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&N()&&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(),We);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)/We);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${We}ms, refresh threshold is ${cr} ticks`),r<=cr&&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 Je)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!N()||!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 re(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 v(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 v(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 v(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 v(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}}))}};le.nextInstanceID=0;var Si=le,Vt=Si;var _t=class extends Vt{constructor(e){super(e)}};var Ei=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())})},Ke=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=zs(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:qs,realtime:Hs,auth:Object.assign(Object.assign({},Fs),{storageKey:c}),global:Ms},l=Gs(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=Bs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Ts(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Te(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ne(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 Ei(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 _t({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 pe(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 hr=(i,e,t)=>new Ke(i,e,t);var K={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var yt=class{constructor(){this.sessionData=null;this.supabase=hr(K.supaBaseUrl,K.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||K.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||K.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||K.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 this.signOut(),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{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||K.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||K.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}}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||K.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 G=null;function Yt(i,e=30,t){G&&(clearInterval(G),G=null);let s=e;i.style.pointerEvents="none",i.textContent=`Resend (${s}s)`,G=setInterval(()=>{s=s-1,i.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(i.style.pointerEvents="auto",G&&(clearInterval(G),G=null),t&&t())},1e3)}function ur(){G&&(clearInterval(G),G=null)}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=!1,e=setTimeout(()=>{i||(document.body.style.visibility="visible")},4e3),t=new yt,{accessToken:s,refreshToken:r}=hs(),n=document.querySelector("#email-form"),o=document.querySelector("#email-input"),a=document.querySelector("#password-input"),c=document.querySelector("#full-name"),h=document.querySelector("#google-login"),l=document.querySelector("#apple-login"),u=document.querySelector("#microsoft-login"),d;(x=>(x.EMAIL_INPUT="email_input",x.LOGIN="login",x.SIGNUP="signup",x.OAUTH_USER="oauth_user",x.UNVERIFIED_EMAIL="unverified_email"))(d||(d={}));let f="email_input",m=document.querySelector("[email-element]"),w=document.querySelector("[different-provider]"),b=document.querySelector("[different-provider-name]"),P=document.querySelector("[different-provider-reset]"),R=document.querySelector("[email-signup-success]"),_=document.querySelector("[email-signup-error]"),k=document.querySelector("[error-message]"),I=document.querySelector("[verification-email]"),be=document.querySelector("[email-signup-retry]"),Qt=document.querySelector("[email-signup-reset]"),he=document.querySelector("[unverified-email]"),Xt=document.querySelector("[unverified-email-address]"),M=document.querySelector("[resend-verification-email]"),Zt=document.querySelector("[unverified-email-reset]"),dr=localStorage.getItem("email"),ke=new URLSearchParams(window.location.search),es=ke.get("referral"),ts=ke.get("plan"),ss=ke.get("utm_source"),fr=ke.get("redirect"),Ti=ke.get("code"),pr=fr==="android-waitlist"?"/android-waitlist":"/downloads",q=`${window.location.origin}${pr}`,Se=new URLSearchParams;es&&Se.append("referral",es),ts&&Se.append("plan",ts),ss&&Se.append("utm_source",ss),Se.toString()&&(q+=`?${Se.toString()}`);let gr=()=>{try{let p=document.cookie.split("; ");for(let g of p){let E=g.indexOf("=");if(E===-1||g.slice(0,E)!=="wispr_auth")continue;let U=g.slice(E+1),x=decodeURIComponent(U);return JSON.parse(x)}return null}catch{return null}};if(s&&r)try{t.setCookies(s,r);let p=t.checkAndSetSession(),g=new Promise((S,U)=>setTimeout(()=>U(new Error("Session timeout")),3e3));await Promise.race([p,g]),t.sessionData&&t.setCookies(t.sessionData.access_token,t.sessionData.refresh_token);let E=t.sessionData?.user.email;localStorage.setItem("email",E),i=!0,clearTimeout(e),window.location.href=q}catch(p){console.error("Error during session setup:",p),document.body.style.visibility="visible"}else{let p=gr();if(p?.access_token&&p?.refresh_token)try{t.setCookies(p.access_token,p.refresh_token);let g=t.checkAndSetSession(),E=new Promise((x,O)=>setTimeout(()=>O(new Error("Session timeout")),3e3));await Promise.race([g,E]),t.sessionData&&t.setCookies(t.sessionData.access_token,t.sessionData.refresh_token);let S=t.sessionData?.user.email,U=t.sessionData?.user.app_metadata.provider||"typing_test";localStorage.setItem("email",S),localStorage.setItem("signin_provider",U),i=!0,clearTimeout(e),window.location.href=q}catch(g){console.error("Error authenticating from typing test session:",g),p.email&&(o.value=p.email),document.body.style.visibility="visible"}else p?.email?(o.value=p.email,document.body.style.visibility="visible"):(dr&&localStorage.removeItem("email"),document.body.style.visibility="visible")}h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(q)}catch(p){console.error("Error during sign-in:",p)}}),l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(q)}catch(p){console.error("Error during sign-in:",p)}}),u.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(q)}catch(p){console.error("Error during sign-in:",p)}});let vt=()=>{w&&(w.style.display="none"),R&&(R.style.display="none"),_&&(_.style.display="none"),he&&(he.style.display="none"),m&&(m.style.display="flex"),o.value="",o.removeAttribute("readonly"),o.classList.remove("disabled"),a.value="",a.style.display="none",a.removeAttribute("required"),c.value="",c.style.display="none",c.removeAttribute("required");let p=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");p&&(p.style.display="none"),g&&(g.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),f="email_input",o.focus()},mr=()=>{o.setAttribute("readonly","true"),o.classList.add("disabled"),a.style.display="block",a.setAttribute("required","true"),a.focus(),c.style.display="none",c.removeAttribute("required");let p=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");p&&(p.style.display="block"),g&&(g.style.display="block"),f="login",console.log("\u2705 Existing user detected - showing login form")},rs=()=>{o.setAttribute("readonly","true"),o.classList.add("disabled"),a.style.display="block",a.setAttribute("required","true"),c.style.display="block",c.setAttribute("required","true"),a.focus();let p=document.querySelector("[captcha-embed]"),g=document.querySelector("#h-captcha-container");p&&(p.style.display="block"),g&&(g.style.display="block"),f="signup",console.log("\u2705 New user detected - showing signup form")},_r=p=>{let g=os(p);m&&(m.style.display="none"),w&&(w.style.display="block"),b&&(b.textContent=g),P&&(P.onclick=()=>{w&&(w.style.display="none"),vt()}),f="oauth_user"},yr=p=>{m&&(m.style.display="none"),he&&(he.style.display="block"),Xt&&(Xt.textContent=p),M&&(M.onclick=async()=>{let g=M.textContent||"";try{let E=window.hcaptcha;if(!E)throw new Error("Verification system not loaded. Please refresh the page.");M.textContent="Verifying...",M.style.pointerEvents="none";let{response:S}=await E.execute({async:!0});if(!S)throw new Error("Verification cancelled");M.textContent="Sending...",await t.resendVerificationEmail(p,q,S),M.textContent="Verification email resent! \u2705",M.style.textDecoration="none",console.log("\u2705 Verification email resent to:",p),_&&(_.style.display="none"),E.reset()}catch(E){if(console.error("\u274C Error resending verification email:",E),M.textContent=g,M.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),_&&(_.style.display="block",k)){let S=E instanceof Error?E.message:"Failed to resend verification email";k.textContent=S}}}),Zt&&(Zt.onclick=()=>{he&&(he.style.display="none"),vt()}),f="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},vr=async(p,g)=>{let E=g.value;g.classList.add("loading"),g.value="";try{let S=await as.checkUserStatus(p);console.log("User status check:",S),g.classList.remove("loading"),g.value=E,S.exists&&S.provider&&S.provider!=="email"?_r(S.provider):S.exists&&S.provider==="email"&&!S.verified?yr(p):S.exists&&S.provider==="email"?mr():rs()}catch(S){console.error("\u274C Error checking user status:",S),g.classList.remove("loading"),g.value=E,rs()}},wr=async(p,g,E,S)=>{if(!g||g.length<8){_&&(_.style.display="block",k&&(k.textContent="Password must be at least 8 characters"));return}let U=window.hcaptcha?.getResponse()||"";if(!U){_&&(_.style.display="block",k&&(k.textContent="Please complete the verification"));return}E.classList.add("loading"),E.value="";try{console.log("\u2705 Attempting login for:",p);let{accessToken:x,refreshToken:O}=await t.signInWithPassword(p,g,U);t.setCookies(x,O),localStorage.setItem("email",p),i=!0,clearTimeout(e),window.location.href=q}catch(x){if(console.error("\u274C Login error:",x),window.hcaptcha&&window.hcaptcha.reset(),E.classList.remove("loading"),E.value=S,_&&(_.style.display="block",k)){let O=x instanceof Error?x.message:"Invalid login credentials";k.textContent=O}}},br=async(p,g,E,S,U)=>{if(!g||g.length<8){_&&(_.style.display="block",k&&(k.textContent="Password must be at least 8 characters"));return}if(!E||E.trim().length<2){_&&(_.style.display="block",k&&(k.textContent="Please enter your full name"));return}let x=window.hcaptcha?.getResponse()||"";if(!x){_&&(_.style.display="block",k&&(k.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{console.log("\u2705 Creating new account for:",p),await t.signUpWithPassword(p,g,E,q,x),window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=U,m&&(m.style.display="none"),_&&(_.style.display="none"),R&&(R.style.display="block"),I&&(I.textContent=p),be&&(Yt(be,30),be.onclick=async()=>{if(be.style.pointerEvents!=="none")try{let O=window.hcaptcha?.getResponse()||"";await t.signUpWithPassword(p,g,E,q,O),window.hcaptcha&&window.hcaptcha.reset(),Yt(be,30),console.log("\u2705 Verification email resent to:",p)}catch(O){console.error("\u274C Error resending verification email:",O)}}),Qt&&(Qt.onclick=()=>{R&&(R.style.display="none"),ur(),vt()})}catch(O){if(console.error("\u274C Signup error:",O),S.classList.remove("loading"),S.value=U,_&&(_.style.display="block",k)){let wt=O instanceof Error?O.message:"Signup failed";k.textContent=wt}}};n.addEventListener("submit",async p=>{p.stopPropagation(),p.preventDefault();let g=o.value,E=a?.value||"",S=c?.value||"";if(!g||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g)){console.error("\u274C Email invalid"),_&&(_.style.display="block",k&&(k.textContent="Please enter a valid email address"));return}_&&(_.style.display="none"),k&&(k.textContent="");let x=n.querySelector('[type="submit"]'),O=x?.value||"";localStorage.setItem("signin_provider","email");try{f==="email_input"?await vr(g,x):f==="login"?await wr(g,E,x,O):f==="signup"&&await br(g,E,S,x,O)}catch(wt){console.error("\u274C Signup error:",wt),x&&(x.classList.remove("loading"),x.value=O),_&&(_.style.display="block")}})});})();
|