@tanay-wispr/webflow-package 6.7.3 → 6.7.5

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.
@@ -1 +1 @@
1
- "use strict";(()=>{var Di=Object.create;var Wt=Object.defineProperty;var Fi=Object.getOwnPropertyDescriptor;var Hi=Object.getOwnPropertyNames;var Wi=Object.getPrototypeOf,Vi=Object.prototype.hasOwnProperty;var Bi=(s,e)=>()=>(s&&(e=s(s=0)),e);var ie=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),zi=(s,e)=>{for(var t in e)Wt(s,t,{get:e[t],enumerable:!0})},ss=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Hi(e))!Vi.call(s,i)&&i!==t&&Wt(s,i,{get:()=>e[i],enumerable:!(r=Fi(e,i))||r.enumerable});return s};var is=(s,e,t)=>(t=s!=null?Di(Wi(s)):{},ss(e||!s||!s.__esModule?Wt(t,"default",{value:s,enumerable:!0}):t,s)),Ji=s=>ss(Wt({},"__esModule",{value:!0}),s);var Ee={};zi(Ee,{Headers:()=>Er,Request:()=>Qi,Response:()=>Zi,default:()=>Sr,fetch:()=>Xi});var Yi,Be,Xi,Sr,Er,Qi,Zi,we=Bi(()=>{"use strict";Yi=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")},Be=Yi(),Xi=Be.fetch,Sr=Be.fetch.bind(Be),Er=Be.Headers,Qi=Be.Request,Zi=Be.Response});var hs=ie(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});var Tr=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};xr.default=Tr});var Lr=ie(mt=>{"use strict";var fs=mt&&mt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(mt,"__esModule",{value:!0});var tn=fs((we(),Ji(Ee))),rn=fs(hs()),Ar=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=tn.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,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let c=null,d=null,u=null,p=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let C=await n.text();C===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?d=C:d=JSON.parse(C))}let S=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),v=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");S&&v&&v.length>1&&(u=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(c={code:"PGRST116",details:`Results contain ${d.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},d=null,u=null,p=406,m="Not Acceptable"):d.length===1?d=d[0]:d=null)}else{let S=await n.text();try{c=JSON.parse(S),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,m="OK")}catch{n.status===404&&S===""?(p=204,m="No Content"):c={message:S}}if(c&&this.isMaybeSingle&&(!((l=c?.details)===null||l===void 0)&&l.includes("0 rows"))&&(c=null,p=200,m="OK"),c&&this.shouldThrowOnError)throw new rn.default(c)}return{error:c,data:d,count:u,status:p,statusText:m}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};mt.default=Ar});var Rr=ie(gt=>{"use strict";var sn=gt&&gt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(gt,"__esModule",{value:!0});var nn=sn(Lr()),Cr=class extends nn.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!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:i=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};gt.default=Cr});var Kt=ie(_t=>{"use strict";var on=_t&&_t.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_t,"__esModule",{value:!0});var an=on(Rr()),Or=class extends an.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};_t.default=Or});var Ir=ie(wt=>{"use strict";var ln=wt&&wt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(wt,"__esModule",{value:!0});var yt=ln(Kt()),Pr=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new yt.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new yt.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,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),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){let c=[...new Set(l)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new yt.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",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new yt.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 yt.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};wt.default=Pr});var ps=ie(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.version=void 0;Yt.version="0.0.0-automated"});var ms=ie(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DEFAULT_HEADERS=void 0;var cn=ps();Xt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${cn.version}`}});var _s=ie(vt=>{"use strict";var gs=vt&&vt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(vt,"__esModule",{value:!0});var dn=gs(Ir()),un=gs(Kt()),hn=ms(),jr=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},hn.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new dn.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([d,u])=>u!==void 0).map(([d,u])=>[d,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([d,u])=>{a.searchParams.append(d,u)})):(o="POST",l=t);let c=Object.assign({},this.headers);return n&&(c.Prefer=`count=${n}`),new un.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};vt.default=jr});var Ss=ie(H=>{"use strict";var bt=H&&H.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(H,"__esModule",{value:!0});H.PostgrestBuilder=H.PostgrestTransformBuilder=H.PostgrestFilterBuilder=H.PostgrestQueryBuilder=H.PostgrestClient=void 0;var ys=bt(_s());H.PostgrestClient=ys.default;var ws=bt(Ir());H.PostgrestQueryBuilder=ws.default;var vs=bt(Kt());H.PostgrestFilterBuilder=vs.default;var bs=bt(Rr());H.PostgrestTransformBuilder=bs.default;var ks=bt(Lr());H.PostgrestBuilder=ks.default;H.default={PostgrestClient:ys.default,PostgrestQueryBuilder:ws.default,PostgrestFilterBuilder:vs.default,PostgrestTransformBuilder:bs.default,PostgrestBuilder:ks.default}});var Ps=ie((Go,Os)=>{"use strict";Os.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Vt=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,U="https://api.wisprflow.ai",fe=class extends Error{constructor(t,r,i){super(i);this.status=t;this.code=r;this.name="AriaAuthError"}},X=s=>s.trim().toLowerCase(),ns=(s,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof s.code=="string"?s.code:s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:typeof s.detail=="string"&&t.has(s.detail)?s.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},ht=(s,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[s]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Gi=(s,e,t)=>[s.message,s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"?s.detail.message:null,typeof s.detail=="string"?s.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??ht(e,t),Ve=(s,e)=>{let t=ns(s,e);return new fe(e,t,Gi(s,t,e))},Ki=(s,e)=>{let t=ns(s,e);return new fe(e,t,ht(t,e))},kr=class{static async signupUser(e){try{let t=`${U}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${U}/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(`${U}/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(`${U}/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(`${U}/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){let t=X(e),r=await fetch(`${U}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw Ve(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${U}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:X(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw Ve(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${U}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${U}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${U}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new fe(422,"invalid_code",ht("invalid_code",422));let t=await fetch(`${U}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok){let i=Ki(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new fe(t.status,"verification_failed",ht("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new fe(t.status,"authentication_failed",ht("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${U}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async getSubscriptionStatus(e){return await fetch(`${U}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${U}/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 i=`${U}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`&currency=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${U}/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(`${U}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${U}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${U}/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 i=new FormData;return i.append("screenshot",e),await fetch(`${U}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function os(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}function as(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var j=kr;var ls=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var cs=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var ds=()=>{let{access_token:s,refresh_token:e}=cs(),t=s,r=e;if(!t||!r){let i=ls();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var us=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ft=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Bt=class extends ft{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},zt=class extends ft{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Jt=class extends ft{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Gt;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Gt||(Gt={}));var en=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},pt=class{constructor(e,{headers:t={},customFetch:r,region:i=Gt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=us(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return en(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let c;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(a["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(a["Content-Type"]="application/json",c=JSON.stringify(o)));let d=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:c}).catch(y=>{throw new Bt(y)}),u=d.headers.get("x-relay-error");if(u&&u==="true")throw new zt(d);if(!d.ok)throw new Jt(d);let p=((r=d.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return p==="application/json"?m=yield d.json():p==="application/octet-stream"?m=yield d.blob():p==="text/event-stream"?m=d:p==="multipart/form-data"?m=yield d.formData():m=yield d.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}};var Es=is(Ss(),1),{PostgrestClient:Ts,PostgrestQueryBuilder:Co,PostgrestFilterBuilder:Ro,PostgrestTransformBuilder:Oo,PostgrestBuilder:Po}=Es.default;var xs="2.10.2";var As={"X-Client-Info":`realtime-js/${xs}`},Ls="1.0.0",Zt=1e4,Cs=1e3,Te;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(Te||(Te={}));var V;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(V||(V={}));var G;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(G||(G={}));var Qt;(function(s){s.websocket="websocket"})(Qt||(Qt={}));var ve;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(ve||(ve={}));var kt=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let l=r.decode(e.slice(o,o+n));o=o+n;let c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}};var xe=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 O;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(O||(O={}));var Ur=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=fn(o,s,e,i),n),{})},fn=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?Rs(n,o):$r(o)},Rs=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return _n(e,t)}switch(s){case O.bool:return pn(e);case O.float4:case O.float8:case O.int2:case O.int4:case O.int8:case O.numeric:case O.oid:return mn(e);case O.json:case O.jsonb:return gn(e);case O.timestamp:return yn(e);case O.abstime:case O.date:case O.daterange:case O.int4range:case O.int8range:case O.money:case O.reltime:case O.text:case O.time:case O.timestamptz:case O.timetz:case O.tsrange:case O.tstzrange:return $r(e);default:return $r(e)}},$r=s=>s,pn=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},mn=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},gn=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},_n=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Rs(e,a))}return s},yn=s=>typeof s=="string"?s.replace(" ","T"):s,er=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Ae=class{constructor(e,t,r={},i=Zt){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var 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 Mr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Mr||(Mr={}));var ze=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=s.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(c,d)=>{o[c]||(l[c]=d)}),this.map(o,(c,d)=>{let u=n[c];if(u){let p=d.map(v=>v.presence_ref),m=u.map(v=>v.presence_ref),y=d.filter(v=>m.indexOf(v.presence_ref)<0),S=u.filter(v=>p.indexOf(v.presence_ref)<0);y.length>0&&(a[c]=y),S.length>0&&(l[c]=S)}else a[c]=d}),this.syncDiff(n,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var c;let d=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),d.length>0){let u=e[a].map(m=>m.presence_ref),p=d.filter(m=>u.indexOf(m.presence_ref)<0);e[a].unshift(...p)}r(a,d,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let d=l.map(u=>u.presence_ref);c=c.filter(u=>d.indexOf(u.presence_ref)<0),e[a]=c,i(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Nr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Nr||(Nr={}));var qr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(qr||(qr={}));var Dr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Dr||(Dr={}));var Je=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=V.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 Ae(this,G.join,this.params,this.timeout),this.rejoinTimer=new xe(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=V.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=V.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=V.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=V.errored,this.rejoinTimer.scheduleTimeout())}),this._on(G.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new ze(this),this.broadcastEndpointURL=er(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(d=>e&&e("CHANNEL_ERROR",d)),this._onClose(()=>e&&e("CLOSED"));let l={},c={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(d=>d.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:c},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:d})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),d===void 0){e&&e("SUBSCRIBED");return}else{let p=this.bindings.postgres_changes,m=(u=p?.length)!==null&&u!==void 0?u:0,y=[];for(let S=0;S<m;S++){let v=p[S],{filter:{event:C,schema:h,table:g,filter:L}}=v,P=d&&d[S];if(P&&P.event===C&&P.schema===h&&P.table===g&&P.filter===L)y.push(Object.assign(Object.assign({},v),{id:P.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",d=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(d).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,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=V.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(G.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new Ae(this,G.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Ae(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:d}=G;if(r&&[a,l,c,d].indexOf(o)>=0&&r!==this._joinRef())return;let p=this._onMessage(o,t,r);if(t&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var y,S,v;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((v=(S=m.filter)===null||S===void 0?void 0:S.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===o}).map(m=>m.callback(p,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var y,S,v,C,h,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let L=m.id,P=(y=m.filter)===null||y===void 0?void 0:y.event;return L&&((S=t.ids)===null||S===void 0?void 0:S.includes(L))&&(P==="*"||P?.toLocaleLowerCase()===((v=t.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{let L=(h=(C=m?.filter)===null||C===void 0?void 0:C.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return L==="*"||L===((g=t?.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof p=="object"&&"ids"in p){let y=p.data,{schema:S,table:v,commit_timestamp:C,type:h,errors:g}=y;p=Object.assign(Object.assign({},{schema:S,table:v,commit_timestamp:C,eventType:h,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(p,r)})}_isClosed(){return this.state===V.closed}_isJoined(){return this.state===V.joined}_isJoining(){return this.state===V.joining}_isLeaving(){return this.state===V.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!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(G.close,{},e)}_onError(e){this._on(G.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=V.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Ur(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Ur(e.columns,e.old_record)),t}};var vn=()=>{},bn=typeof WebSocket<"u",Ge=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=As,this.params={},this.timeout=Zt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=vn,this.conn=null,this.sendBuffer=[],this.serializer=new kt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Qt.websocket}`,this.httpEndpoint=er(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new xe(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(bn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Fr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>is(Ps())).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 Te.connecting:return ve.Connecting;case Te.open:return ve.Open;case Te.closing:return ve.Closing;default:return ve.Closed}}isConnected(){return this.connectionState()===ve.Open}channel(e,t={config:{}}){let r=new Je(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(G.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:Ls}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(G.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Cs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Fr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Te.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Ke=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function M(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var tr=class extends Ke{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},St=class extends Ke{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var kn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},rr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Is=()=>kn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(we(),Ee))).Response:Response});var Ye=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Hr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Sn=(s,e)=>Ye(void 0,void 0,void 0,function*(){let t=yield Is();s instanceof t?s.json().then(r=>{e(new tr(Hr(r),s.status||500))}).catch(r=>{e(new St(Hr(r),r))}):e(new St(Hr(s),s))}),En=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function sr(s,e,t,r,i,n){return Ye(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,En(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Sn(l,a))})})}function Et(s,e,t,r){return Ye(this,void 0,void 0,function*(){return sr(s,"GET",e,t,r)})}function ne(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return sr(s,"POST",e,r,i,t)})}function js(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return sr(s,"PUT",e,r,i,t)})}function ir(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return sr(s,"DELETE",e,r,i,t)})}var Q=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Tn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},$s={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Tt=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=rr(i)}uploadOrUpdate(e,t,r,i){return Q(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},$s),i),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 l=this._removeEmptyFolders(t),c=this._getFinalPath(l),d=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield d.json();return d.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(M(n))return{data:null,error:n};throw n}})}upload(e,t,r){return Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return Q(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l,c=Object.assign({upsert:$s.upsert},i),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:d}),p=yield u.json();return u.ok?{data:{path:n,fullPath:p.Key},error:null}:{data:null,error:p}}catch(l){if(M(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return Q(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield ne(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ke("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(M(r))return{data:null,error:r};throw r}})}update(e,t,r){return Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return Q(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}copy(e,t,r){return Q(this,void 0,void 0,function*(){try{return{data:{path:(yield ne(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield ne(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=yield ne(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}download(e,t){return Q(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Et(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(M(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let c=i.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return Q(this,void 0,void 0,function*(){try{return{data:yield ir(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}list(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Tn),t),{prefix:e||""});return{data:yield ne(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(M(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var Us="2.6.0";var Ms={"X-Client-Info":`storage-js/${Us}`};var Xe=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},xt=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Ms),t),this.fetch=rr(r)}listBuckets(){return Xe(this,void 0,void 0,function*(){try{return{data:yield Et(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(M(e))return{data:null,error:e};throw e}})}getBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield Et(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Xe(this,void 0,void 0,function*(){try{return{data:yield ne(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(M(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Xe(this,void 0,void 0,function*(){try{return{data:yield js(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(M(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield ir(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(M(t))return{data:null,error:t};throw t}})}};var At=class extends xt{constructor(e,t={},r){super(e,t,r)}from(e){return new Tt(this.url,this.headers,e,this.fetch)}};var Ns="2.44.4";var Lt="";typeof Deno<"u"?Lt="deno":typeof document<"u"?Lt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Lt="react-native":Lt="node";var xn={"X-Client-Info":`supabase-js-${Lt}/${Ns}`},qs={headers:xn},Ds={schema:"public"},Fs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Hs={};we();var An=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Ln=s=>{let e;return s?e=s:typeof fetch>"u"?e=Sr:e=fetch,(...t)=>e(...t)},Cn=()=>typeof Headers>"u"?Er:Headers,Ws=(s,e,t)=>{let r=Ln(t),i=Cn();return(n,o)=>An(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:s,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",s),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:c}))})};function Vs(s){return s.replace(/\/$/,"")}function Bs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:l,global:c}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},c),n)}}var nr="2.64.4";var zs="http://localhost:9999",Js="supabase.auth.token";var Gs={"X-Client-Info":`gotrue-js/${nr}`},Wr=10;var Ct="X-Supabase-Api-Version",Vr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ks(s){return Math.round(Date.now()/1e3)+s}function Ys(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var Z=()=>typeof document<"u",Le={tested:!1,writable:!1},be=()=>{if(!Z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Le.tested)return Le.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Le.tested=!0,Le.writable=!0}catch{Le.tested=!0,Le.writable=!1}return Le.writable};function or(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var ar=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(we(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Xs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Br=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ot=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},lr=async(s,e)=>{await s.removeItem(e)};function Rn(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,l,c,d=0;for(s=s.replace("-","+").replace("_","/");d<s.length;)o=e.indexOf(s.charAt(d++)),a=e.indexOf(s.charAt(d++)),l=e.indexOf(s.charAt(d++)),c=e.indexOf(s.charAt(d++)),r=o<<2|a>>4,i=(a&15)<<4|l>>2,n=(l&3)<<6|c,t=t+String.fromCharCode(r),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),c!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Rt=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Rt.promiseConstructor=Promise;function zr(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.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(Rn(r))}async function Qs(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Zs(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function On(s){return("0"+s.toString(16)).substr(-2)}function Pn(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,On).join("")}async function In(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function jn(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function $n(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;let t=await In(s);return jn(t)}async function Ce(s,e,t=!1){let r=Pn(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Br(s,`${e}-code-verifier`,i);let n=await $n(r);return[n,r===n?"plain":"s256"]}var Un=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ei(s){let e=s.headers.get(Ct);if(!e||!e.match(Un))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Pt=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function E(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var cr=class extends Pt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function ti(s){return E(s)&&s.name==="AuthApiError"}var Qe=class extends Pt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},pe=class extends Pt{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},oe=class extends pe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ze=class extends pe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Re=class extends pe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Oe=class extends pe{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}}},It=class extends pe{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}}},et=class extends pe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function dr(s){return E(s)&&s.name==="AuthRetryableFetchError"}var jt=class extends pe{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Mn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Pe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Nn=[502,503,504];async function ri(s){var e;if(!Xs(s))throw new et(Pe(s),0);if(Nn.includes(s.status))throw new et(Pe(s),s.status);let t;try{t=await s.json()}catch(n){throw new Qe(Pe(n),n)}let r,i=ei(s);if(i&&i.getTime()>=Vr["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 jt(Pe(t),s.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 jt(Pe(t),s.status,t.weak_password.reasons);throw new cr(Pe(t),s.status||500,r)}var qn=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function x(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Ct]||(n[Ct]=Vr["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Dn(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function Dn(s,e,t,r,i,n){let o=qn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new et(Pe(l),0)}if(a.ok||await ri(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await ri(l)}}function me(s){var e;let t=null;Fn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ks(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Jr(s){let e=me(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function ae(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function si(s){return{data:s,error:null}}function ii(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Mn(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function ni(s){return s}function Fn(s){return s.access_token&&s.refresh_token&&s.expires_in}var Hn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Ie=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ar(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await x(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(E(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await x(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Hn(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await x(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ii,redirectTo:t?.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await x(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},d=await x(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:ni});if(d.error)throw d.error;let u=await d.json(),p=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=d.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{let S=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(y.split(";")[1].split("=")[1]);c[`${v}Page`]=S}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(E(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await x(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await x(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await x(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await x(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await x(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}};var oi={getItem:s=>be()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{be()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{be()&&globalThis.localStorage.removeItem(s)}};function Gr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function ai(){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 je={debug:!!(globalThis&&be()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},$t=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ur=class extends $t{};async function Kr(s,e,t){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),je.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{je.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw je.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ur(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(je.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()}})}ai();var Wn={url:zs,storageKey:Js,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Gs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ut=30*1e3,li=3;async function ci(s,e,t){return await t()}var $e=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&Z()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},Wn),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Ie({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ar(i.fetch),this.lock=i.lock||ci,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Z()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Kr:this.lock=ci,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:be()?this.storage=oi:(this.memoryStorage={},this.storage=Gr(this.memoryStorage)):(this.memoryStorage={},this.storage=Gr(this.memoryStorage)),Z()&&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} (${nr}) ${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=Z()?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:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return E(e)?{error:e}:{error:new Qe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await x(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:me}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:d,password:u,options:p}=e,m=null,y=null;this.flowType==="pkce"&&([m,y]=await Ce(this.storage,this.storageKey)),n=await x(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:d,password:u,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:m,code_challenge_method:y},xform:me})}else if("phone"in e){let{phone:d,password:u,options:p}=e;n=await x(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:u,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:me})}else throw new Re("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(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 x(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:Jr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await x(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:Jr})}else throw new Re("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Ze}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ot(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await x(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:me});return await lr(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 Ze}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await x(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:me}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Ze}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:l}=e,c=null,d=null;this.flowType==="pkce"&&([c,d]=await Ce(this.storage,this.storageKey));let{error:u}=await x(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:d},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:d}=await x(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:d}}throw new Re("You must provide either an email or phone number.")}catch(a){if(E(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await x(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:me});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Ce(this.storage,this.storageKey)),await x(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:si})}catch(n){if(E(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 oe;let{error:i}=await x(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(E(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await x(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await x(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Re("You must provide either an email or phone number and a type")}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ot(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:(l,c,d)=>(!o&&c==="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(l,c,d))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await x(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ae}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new oe}:await x(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:ae})})}catch(t){if(E(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:i,error:n}=r;if(n)throw n;if(!i.session)throw new oe;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Ce(this.storage,this.storageKey));let{data:c,error:d}=await x(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:ae});if(d)throw d;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return zr(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 oe;let t=Date.now()/1e3,r=t,i=!0,n=null,o=zr(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(E(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 oe;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!Z())throw new Oe("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Oe("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new It("Not a valid PKCE flow url.");let t=or(window.location.href);if(e){if(!t.code)throw new It("No code detected.");let{data:h,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;let L=new URL(window.location.href);return L.searchParams.delete("code"),window.history.replaceState(window.history.state,"",L.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Oe(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:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=t;if(!n||!a||!o||!c)throw new Oe("No session defined in URL");let d=Math.round(Date.now()/1e3),u=parseInt(a),p=d+u;l&&(p=parseInt(l));let m=p-d;m*1e3<=Ut&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${u}s`);let y=p-u;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,p,d);let{data:S,error:v}=await this._getUser(n);if(v)throw v;let C={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:p,refresh_token:o,token_type:c,user:S.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:C,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=or(window.location.href);return!!(Z()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=or(window.location.href),t=await Ot(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(ti(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await lr(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ys(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Ce(this.storage,this.storageKey,!0));try{return await x(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(E(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(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,l,c,d;let{data:u,error:p}=n;if(p)throw p;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await x(this.fetch,"GET",m,{headers:this.headers,jwt:(d=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&d!==void 0?d:void 0})});if(i)throw i;return Z()&&!(!((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(E(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await x(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(E(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 Zs(async i=>(i>0&&await Qs(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await x(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:me})),(i,n)=>{let o=200*Math.pow(2,i);return n&&dr(n)&&Date.now()+o-r<Ut})}catch(r){if(this._debug(t,"error",r),E(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),Z()&&!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 Ot(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Wr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Wr}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),dr(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 oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Rt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new oe;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),E(n)){let o={session:null,error:n};return dr(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(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Br(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await lr(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Z()&&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(),Ut);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/Ut);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ut}ms, refresh threshold is ${li} ticks`),i<=li&&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 $t)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Z()||!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 i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await Ce(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await x(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await x(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 l?{data:null,error:l}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await x(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await x(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let d=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:d},error:null}}))}};$e.nextInstanceID=0;var Vn=$e,Yr=Vn;var hr=class extends Yr{constructor(e){super(e)}};var Bn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Mt=class{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=Vs(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,c={db:Ds,realtime:Hs,auth:Object.assign(Object.assign({},Fs),{storageKey:l}),global:qs},d=Bs(r??{},c);this.storageKey=(i=d.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=d.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=d.auth)!==null&&o!==void 0?o:{},this.headers,d.global.fetch),this.fetch=Ws(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},d.realtime)),this.rest=new Ts(`${a}/rest/v1`,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new pt(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new At(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 Bn(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:i,storageKey:n,flowType:o,debug:a},l,c){var d;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new hr({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:c,hasCustomAuthorizationHeader:(d="Authorization"in this.headers)!==null&&d!==void 0?d:!1})}_initRealtimeClient(e){return new Ge(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 di=(s,e,t)=>new Mt(s,e,t);var ge={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var zn=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},fr=s=>{let[e,t]=s.split(".");return!e||!t?null:zn(t)},ui=s=>{let e=fr(s);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Jn="https://api.workos.com",Gn=60,tt=(s,e)=>typeof s[e]=="string"?s[e]:void 0,hi=(s,e,t)=>{let r=fr(s);if(!r)return null;let i=tt(r,"urn:wispr:user_external_id")??tt(r,"sub"),n=t?.email??tt(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,l={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:l}},Kn=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Jn,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:s,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},fi=async(s,e)=>{let t=fr(s);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=tt(t,"client_id");if(i-r<Gn&&n){let l=await Kn(e,n,tt(t,"iss"),tt(t,"org_id")),c=hi(l.access_token,l.refresh_token,l.user);if(!c)throw new Error("WorkOS refresh returned an invalid access token");return c}if(i<=r)throw new Error("WorkOS session expired");let a=hi(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var rt=class{constructor(){this.sessionData=null;this.supabase=di(ge.supaBaseUrl,ge.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ge.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||ge.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||ge.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:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw 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 i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{if(ui(t)==="workos"){this.sessionData=await fi(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ge.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=await j.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:i||ge.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),a}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await j.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(Vt(n))return{kind:"otp",challenge:n};if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0,provider:n.provider||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await j.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||ge.redirectUri,workos_capable:i?.workosCapable||void 0});return console.log("Verification request completed"),n}catch(n){throw console.error("Error resending verification email:",n),n}}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 pr=null;function Ue(){return new URLSearchParams(window.location.search).get("dev-mode")==="true"}var pi=(s,e)=>{if(!(s instanceof Error)||s.name!=="AriaAuthError")return e;let t={verification_failed:"Incorrect or expired code. Try again.",invalid_code:"Enter the six-digit code.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again."},{code:r}=s;return r&&t[r]||e},mr=()=>{pr!==null&&(window.clearInterval(pr),pr=null)};function st(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),mr()}function mi(s){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),r=document.querySelector("[otp-email]"),i=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),l=document.querySelector("[otp-resend-countdown]"),c=document.querySelector("[otp-resend-seconds]"),d=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),n&&(n.style.display="none"),l&&(l.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),mr(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let u=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},p=()=>{n&&(n.style.display="none")},m=!1,y=!1,S=h=>{i&&(i.style.pointerEvents=h?"none":"",h?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},v=async()=>{if(m)return;let h=t.map(g=>g.value).join("");if(h.length!==6){u("Please enter all 6 digits.");return}m=!0,S(!0),t.forEach(g=>g.setAttribute("disabled","true")),p();try{await s.onVerify(h),p(),i&&(i.textContent="Verified \u2705")}catch(g){m=!1,S(!1),t.forEach(L=>{L.value="",L.removeAttribute("disabled")}),u(pi(g,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,g)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&g<t.length-1&&t[g+1].focus(),p()},h.onkeydown=L=>{L.key==="Backspace"&&!h.value&&g>0?t[g-1].focus():L.key==="Enter"&&(L.preventDefault(),v())},h.onpaste=L=>{L.preventDefault();let P=(L.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);P.split("").forEach((B,se)=>{t[se]&&(t[se].value=B)});let ce=Math.min(P.length,t.length-1);t[ce]?.focus(),p()}}),i&&(i.onclick=h=>{h.preventDefault(),v()});let C=()=>{let h=30;a&&(a.style.display="none"),l&&(l.style.display="block"),c&&(c.textContent=String(h)),mr(),pr=window.setInterval(()=>{h-=1,c&&(c.textContent=String(h)),h<=0&&(mr(),a&&(a.style.display=""),l&&(l.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(y||a.style.display==="none")){y=!0,t.forEach(g=>{g.value="",g.removeAttribute("disabled")}),t[0]?.focus(),p(),C();try{await s.onResend?.()}catch(g){u(pi(g,"We couldn't send a new code. Please try again when the timer ends."))}finally{y=!1}}}),d&&(d.onclick=h=>{h.preventDefault(),st(),s.onReset?.()})}var Me=()=>window.hcaptcha,gr=async()=>{let s=Me();if(!s)throw new Error("Verification system not loaded");let e=await s.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Nt=(s,e)=>s instanceof Error?s.message:e,gi=(s,e)=>s instanceof fe?s.code==="sso_required"?(e.showSso(),!0):s.code==="scim_managed_domain"?(e.showScim(),!0):(s.code==="sign_in_to_continue"&&e.showLogin(),e.showError(s.message),!0):!1,_i=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:X(r.email)},s.beforeShow(),mi({email:e.email,onVerify:async i=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await j.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await s.onAuthenticated(n)},onResend:async()=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await gr();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{Me()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var le=null;function Xr(s,e=30,t){le&&(clearInterval(le),le=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,le=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",le&&(clearInterval(le),le=null),t&&t())},1e3)}function yi(){le&&(clearInterval(le),le=null)}var wi=/^[\p{L}\p{M}\s\-'.]+$/u;function Yn(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":wi.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Qr(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":wi.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function vi(s,e,t){let r="full-name-match-error",i=l=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let c=document.getElementById(r);c||(c=document.createElement("div"),c.id=r,c.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",c)),c.textContent=l},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let l=Yn(e.value,s.value);l?i(l):n()},a=()=>{let l=Qr(e.value,s.value);l?i(l):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var I=(s,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:s,retry_attempt:10-t}),window.posthog.capture(s,e)):t>0&&setTimeout(()=>I(s,e,t-1),200)},bi=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var Xn="wisprjam.com",Qn="wispr.ai",Zn="wispr_workos_capable",eo=s=>s.trim().toLowerCase().split("@")[1]??"",to=s=>{let e=eo(s);return e===Xn||e===Qn},ki=()=>{try{return window.sessionStorage.getItem(Zn)==="true"}catch{return!1}},ro=s=>Ue()&&to(s);function Si(s,e){let t=new rt,r="email_input",i=null,n=()=>{i?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),l=document.querySelector("#password-input"),c=document.querySelector("#full-name"),d=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),p=document.querySelector("#microsoft-login"),m=document.querySelector("[email-element]"),y=document.querySelector("[different-provider]"),S=document.querySelector("[different-provider-name]"),v=document.querySelector("[different-provider-reset]"),C=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),g=document.querySelector("[error-message]"),L=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),ce=document.querySelector("[email-signup-reset]"),B=document.querySelector("[scim-div]"),se=document.querySelector("[scim-reset]"),N=document.querySelector("[forgot-password]"),ke=document.querySelector("[forgot-password-success]"),it=document.querySelector("[forgot-password-email]"),ee=document.querySelector("[unverified-email]"),nt=document.querySelector("[unverified-email-address]"),de=document.querySelector("[resend-verification-email]"),Se=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(s)}catch(_){console.error("Error during Google sign-in:",_)}}),u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(s)}catch(_){console.error("Error during Apple sign-in:",_)}}),p&&p.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(s)}catch(_){console.error("Error during Microsoft sign-in:",_)}}));let K=()=>{n(),y&&(y.style.display="none"),C&&(C.style.display="none"),h&&(h.style.display="none"),ee&&(ee.style.display="none"),B&&(B.style.display="none"),N&&(N.style.display="none"),ke&&(ke.style.display="none"),st();let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="block"),m&&(m.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),l&&(l.value="",l.style.display="none",l.removeAttribute("required")),c&&(c.value="",c.style.display="none",c.removeAttribute("required"));let b=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");b&&(b.style.display="none"),A&&(A.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),r="email_input",a&&a.focus()},_e=()=>{m&&(m.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="none",c.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),N&&(N.style.display="block",N.onclick=async()=>{let A=a?.value||"",T=N.textContent||"";try{let{hcaptcha:q}=window;if(!q)throw new Error("Verification system not loaded. Please refresh the page.");N.style.pointerEvents="none",N.textContent="Sending...";let{response:R}=await q.execute({async:!0});if(!R)throw new Error("Verification cancelled");await j.requestPasswordReset(A,R),q.reset(),m&&(m.style.display="none"),N&&(N.style.display="none"),ke&&(ke.style.display="block"),it&&(it.textContent=A)}catch(q){console.error("Error sending password reset email:",q),N.textContent=T,N.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",g&&(g.textContent=q instanceof Error?q.message:"Failed to send reset email"))}}),r="login"},ot=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="block",c.setAttribute("required","true"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),r="signup"},at=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),B&&(B.style.display="block"),se&&(se.onclick=()=>{B&&(B.style.display="none"),_&&(_.style.display="block"),K()})},Ne=_=>{n();let b=as(_);m&&(m.style.display="none"),y&&(y.style.display="block"),S&&(S.textContent=b),v&&(v.onclick=()=>{y&&(y.style.display="none"),K()}),r="oauth_user"};i=_i({client:t,redirectUrl:s,isWorkosCapable:Ue,beforeShow:()=>{m&&(m.style.display="none"),ee&&(ee.style.display="none")},onAuthenticated:async _=>{n(),t.setCookies(_.access_token,_.refresh_token),localStorage.setItem("email",_.email),localStorage.setItem("user_id",_.user_id),localStorage.setItem("signin_provider","email");let b=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,b):window.location.href=s},onMissingChallenge:_e,onReset:K});let qe=_=>{m&&(m.style.display="none"),ee&&(ee.style.display="block"),nt&&(nt.textContent=_),de&&(de.onclick=async()=>{let b=de.textContent||"";try{let A=await gr();await t.resendVerificationEmail(_,s,A),de.textContent="Verification email resent! \u2705",de.style.textDecoration="none"}catch(A){de.textContent=b,h&&(h.style.display="block"),g&&(g.textContent=Nt(A,"Unable to resend verification."))}finally{Me()?.reset()}}),Se&&(Se.onclick=()=>{ee&&(ee.style.display="none"),K()}),r="unverified_email"},De=_=>gi(_,{showSso:()=>Ne("workos"),showScim:at,showLogin:_e,showError:b=>{h&&(h.style.display="block"),g&&(g.textContent=b)}}),Fe=async(_,b)=>{let A=b.value;b.classList.add("loading"),b.value="";try{let T=await j.checkUserStatus(_);b.classList.remove("loading"),b.value=A,!T.exists&&T.scim_managed?at():T.enforce_sso?Ne("workos"):T.exists&&T.provider&&T.provider!=="email"&&T.provider!=="workos"?Ne(T.provider):T.exists&&ro(_)||T.exists&&T.provider==="workos"?_e():T.exists&&T.provider==="email"&&!T.verified?qe(_):T.exists&&T.provider==="email"?_e():ot()}catch(T){console.error("Error checking user status:",T),b.classList.remove("loading"),b.value=A,De(T)||ot()}},qt=async(_,b,A,T)=>{if(!b||b.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}let q=window.hcaptcha?.getResponse()||"";if(!q){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let F=await j.signInWithEmail({email:_,password:b,mcp_login_state:e.mcpLoginState,workos_capable:ki()});if(!F.redirect_url)throw new Error(F.error||"Unable to continue connector login. Please try again.");I("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=F.redirect_url;return}let R=await t.signInWithPassword(_,b,q,{workosCapable:ki(),provision:!1});if(R.kind==="otp"){if(!Ue())throw new Error("OTP challenge returned outside dev mode");let F={pendingAuthenticationToken:R.challenge.pending_authentication_token,email:X(R.challenge.email||_)};Me()?.reset(),A.classList.remove("loading"),A.value=T,i?.show(F);return}t.setCookies(R.accessToken,R.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(R.accessToken,R.refreshToken,R.fullName):window.location.href=s}catch(R){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=T,!De(R)&&h&&(h.style.display="block",g&&(g.textContent=Nt(R,"Unable to sign in. Please try again.")))}},lt=async(_,b,A,T,q)=>{if(!b||b.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}if(!A||A.trim().length<2){h&&(h.style.display="block",g&&(g.textContent="Please enter your full name"));return}let R=Qr(A,b);if(R){h&&(h.style.display="block",g&&(g.textContent=R));return}let F=window.hcaptcha?.getResponse()||"";if(!F){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{let te=await t.signUpWithPassword(_,b,A,s,F,{workosCapable:Ue()});if(window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=q,m&&(m.style.display="none"),h&&(h.style.display="none"),Vt(te)){if(!Ue())throw new Error("OTP challenge returned outside dev mode");let Y={pendingAuthenticationToken:te.pending_authentication_token,email:X(te.email||_)};i?.show(Y);return}C&&(C.style.display="block"),L&&(L.textContent=_),P&&(Xr(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let Y=await gr();await t.resendVerificationEmail(_,s,Y,{workosCapable:Ue()}),Xr(P,30)}catch(Y){h&&(h.style.display="block"),g&&(g.textContent=Nt(Y,"Unable to resend verification. Please try again."))}finally{Me()?.reset()}}),ce&&(ce.onclick=()=>{C&&(C.style.display="none"),yi(),K()})}catch(te){T.classList.remove("loading"),T.value=q,Me()?.reset(),!De(te)&&h&&(h.style.display="block",g&&(g.textContent=Nt(te,"Unable to create the account. Please try again.")))}};return o&&l&&c&&vi(l,c,o.querySelector('[type="submit"]')),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let b=X(a?.value||"");a&&(a.value=b);let A=l?.value||"",T=c?.value||"";if(!b||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b)){h&&(h.style.display="block",g&&(g.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),g&&(g.textContent="");let R=o.querySelector('[type="submit"]'),F=R?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await Fe(b,R):r==="login"?await qt(b,A,R,F):r==="signup"&&await lt(b,A,T,R,F)}catch(te){console.error("Auth flow error:",te),R&&(R.classList.remove("loading"),R.value=F),h&&(h.style.display="block")}}),{reset:K}}var _r=function(){return _r=Object.assign||function(s){for(var e,t=1,r=arguments.length;t<r;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i]);return s},_r.apply(this,arguments)},Ei=function(){function s(e,t,r){var i=this;this.endVal=t,this.options=r,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){i.startTime||(i.startTime=n);var o=n-i.startTime;i.remaining=i.duration-o,i.useEasing?i.countDown?i.frameVal=i.startVal-i.easingFn(o,0,i.startVal-i.endVal,i.duration):i.frameVal=i.easingFn(o,i.startVal,i.endVal-i.startVal,i.duration):i.frameVal=i.startVal+(i.endVal-i.startVal)*(o/i.duration);var a=i.countDown?i.frameVal<i.endVal:i.frameVal>i.endVal;i.frameVal=a?i.endVal:i.frameVal,i.frameVal=Number(i.frameVal.toFixed(i.options.decimalPlaces)),i.printValue(i.frameVal),o<i.duration?i.rAF=requestAnimationFrame(i.count):i.finalEndVal!==null?i.update(i.finalEndVal):i.options.onCompleteCallback&&i.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,c,d=n<0?"-":"";o=Math.abs(n).toFixed(i.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?i.options.decimal+u[1]:"",i.options.useGrouping){c="";for(var p=3,m=0,y=0,S=a.length;y<S;++y)i.options.useIndianSeparators&&y===4&&(p=2,m=1),y!==0&&m%p==0&&(c=i.options.separator+c),m++,c=a[S-y-1]+c;a=c}return i.options.numerals&&i.options.numerals.length&&(a=a.replace(/[0-9]/g,function(v){return i.options.numerals[+v]}),l=l.replace(/[0-9]/g,function(v){return i.options.numerals[+v]})),d+i.options.prefix+a+l+i.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=_r(_r({},this.defaults),r),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return i.handleScroll(i)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return s.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,r=e.el.getBoundingClientRect(),i=r.top+window.pageYOffset,n=r.top+r.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||i>t)&&!e.paused&&e.reset()}},s.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var r=this.countDown?1:-1;this.endVal=e+r*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},s.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},s.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},s.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},s.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},s.prototype.printValue=function(e){var t;if(this.el){var r=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,r):this.el.tagName==="INPUT"?this.el.value=r:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=r:this.el.innerHTML=r}},s.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},s.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},s.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},s.prototype.parse=function(e){var t=function(o){return o.replace(/([.,'  ])/g,"\\$1")},r=t(this.options.separator),i=t(this.options.decimal),n=e.replace(new RegExp(r,"g"),"").replace(new RegExp(i,"g"),".");return parseFloat(n)},s}();var Ti=!1;function xi(){if(Ti)return;Ti=!0;let s=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(r=>{if(r.isIntersecting){let i=r.target;e.unobserve(i);let n=i.dataset.countDirection||"up",o=parseFloat(i.dataset.countOffset||"10")/100,a=parseFloat(i.dataset.countDuration||"2"),l=5,c=i.dataset.countTarget||i.textContent?.trim()||"0",d=parseFloat(c.replace(/,/g,""));if(isNaN(d))return;let u=d*o,p=Math.max(u,l),m=n==="down"?d+p:Math.max(0,d-p);new Ei(i,d,{startVal:Math.round(m),duration:a,useGrouping:!0}).start()}})},{threshold:0});s.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var Ai=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});async function so(s){let t=new TextEncoder().encode(s.toLowerCase().trim()),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new rt,{accessToken:t,refreshToken:r}=ds(),i=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),c=document.querySelector("[error-div]"),d=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),p=document.querySelector("[spots]"),m=document.querySelectorAll("[referral-code]"),y=document.querySelector("[referral-count]"),S=document.querySelector("[desktop-bonus-remaining]"),v=document.querySelector("[desktop-bonus-complete]"),C=document.querySelector("[climbed-dropped]"),h=document.querySelector("[keep-moving]"),g=document.querySelector("[rank-arrow-wrap]"),L=document.querySelector("[cohort-text]"),P=document.querySelector("[top-100]"),ce=document.querySelector("[top-1000]"),B=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),N=document.querySelector("[sms-bonus-complete]"),ke=document.querySelector("[total-boost]"),it=document.querySelector("[social-media-details]"),ee=document.querySelector("[sms-popup-button]"),nt=document.querySelector("[app-download]"),de=document.querySelector("[file-upload]"),Se=document.querySelector("[file-input]"),K=document.querySelector("[file-validation-error]"),_e=document.querySelector("[file-upload-loading]"),ot=document.querySelector("[cancel-upload-button]"),at=document.querySelector("[file-upload-verified]"),Ne=document.querySelector("[boost-earned]"),yr=document.querySelector("[boost-earned-location]"),qe=document.querySelector("[woohoo-button]"),De=document.querySelector("[file-upload-failed]"),Fe=document.querySelector("[upload-failed-text]"),qt=document.querySelector("[close-button]"),lt=document.querySelector("[share-on-x]"),_=document.querySelector("[share-on-linkedin]"),b=document.querySelector("[share-on-whatsapp]"),A=document.querySelector("[share-on-slack]"),T=document.querySelector("[share-on-discord]"),q=document.querySelector("[social-media-bonus-remaining]"),R=document.querySelector("[social-media-bonus-complete]"),F=document.querySelector("[share-on-other-channel]");it&&it.addEventListener("click",()=>{I("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),ee&&ee.addEventListener("click",()=>{I("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),nt&&nt.addEventListener("click",()=>{window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_app_download",source:"android-waitlist-page"}),I("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let te=async()=>{clearTimeout(s),document.body.style.visibility="visible",o.forEach(Ft=>{Ft.style.display="none"}),n&&(n.style.display="block");let Y=window.__abVariantPromise?await window.__abVariantPromise:"control",He=document.querySelector("[auth-hero-default]"),z=document.querySelector("[auth-hero-v1]"),re=document.querySelector("[auth-hero-v2]");He&&(He.style.display="none"),z&&(z.style.display="none"),re&&(re.style.display="none"),Y==="dictation-broken"&&z?z.style.display="block":Y==="smartest"&&re?re.style.display="block":He&&(He.style.display="block"),n&&(n.style.display="none"),i&&(i.style.display="block");let Dt=document.querySelector("[reusable-section-wrap]");Dt&&i&&i.appendChild(Dt);let ct=document.querySelector(".wl_cohort-spot-wrap");ct&&(ct.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),I("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),Si(`${window.location.origin}/android-waitlist`)};if(!t||!r){await te();return}try{e.setCookies(t,r);let Y=e.checkAndSetSession(),He=new Promise((f,k)=>setTimeout(()=>k(new Error("Session timeout")),3e3));await Promise.race([Y,He]),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(s),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(f=>{f.style.display="flex",f.dataset.bound||(f.dataset.bound="true",f.addEventListener("click",async k=>{k.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let z=e.sessionData?.access_token,re=e.sessionData?.user.email,Dt=e.sessionData?.user.user_metadata.full_name||" ",[ct,Ft]=os(Dt),dt=e.sessionData?.user.id;localStorage.setItem("email",re),dt&&localStorage.setItem("user_id",dt),dt&&bi(dt,{email:re,firstName:ct,lastName:Ft});let Li=Ai(),{dub_id:wr,referral:vr,promo_code:Zr}=Li,Ci=!!localStorage.getItem("conversion_sent"),We=!localStorage.getItem("android_waitlist_joined"),$={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},Ri={access_token:z,first_name:ct,last_name:Ft,dub_click_id:wr||void 0,referral:vr||void 0,promo_code:Zr||void 0};try{await j.signupUser(Ri),$.signup.success=!0}catch(f){$.signup.success=!1,$.signup.error=f instanceof Error?f.message:"Unknown error"}try{let f=await j.ensureReferralCode(z);if($.referral.success=f.ok,!f.ok){let k=await f.json().catch(()=>({}));$.referral.error=k.detail||k.message||`Status ${f.status}`}}catch(f){$.referral.success=!1,$.referral.error=f instanceof Error?f.message:"Network error"}Ci||(I("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:wr||void 0,referral:vr||void 0,email:re,user_id:dt||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"));let Oi={email:re,device_type:"android"},es=!1;try{await j.addToWaitlist(Oi),$.waitlist.success=!0,es=!0}catch(f){$.waitlist.success=!1,$.waitlist.error=f instanceof Error?f.message:"Unknown error"}We&&es&&(localStorage.setItem("android_waitlist_joined","true"),I("app_waitlist",{device_type:"android",source:"android-waitlist-page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:"android",source:"android-waitlist-page"}));let J=await j.getAndroidWaitlistStats(z);if(J.status===404&&!We){I("android_waitlist_recovery_attempted",{reason:"localStorage flag set but 404 from stats API"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_attempted",reason:"localStorage flag set but 404 from stats API"}),localStorage.removeItem("android_waitlist_joined");try{let f={email:re,device_type:"android"};await j.addToWaitlist(f),localStorage.setItem("android_waitlist_joined","true"),J=await j.getAndroidWaitlistStats(z),J.ok&&(I("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(f){console.error("Recovery addToWaitlist failed:",f)}}let Pi=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if($.stats.success=J.ok,J.status===401||J.status===429||!J.ok){let f="";try{let k=await J.json();f=JSON.stringify(k),$.stats.error=k.detail||k.message||f,d&&(d.textContent=`Status: ${J.status} | ${f}`)}catch{f="Could not parse response",$.stats.error=f,d&&(d.textContent=`Status: ${J.status} | ${f}`)}I("android_waitlist_api_error",{status:J.status,error:f,signup_success:$.signup.success,signup_error:$.signup.error,referral_success:$.referral.success,referral_error:$.referral.error,waitlist_success:$.waitlist.success,waitlist_error:$.waitlist.error,stats_error:$.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:J.status,error:f}),a&&(a.style.display="none"),c&&(c.style.display="block");return}let D=await J.json();if(We){let f=await so(re);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:D.current_rank,user_email_hash:f})}let ts=localStorage.getItem("android_waitlist_last_rank");if(ts&&!We){let f=parseInt(ts,10);D.current_rank<f&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:D.current_rank,positions_gained:f-D.current_rank,referral_count:D.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",D.current_rank.toString());let br=f=>{let k=f.current_rank;if(u){let w=k.toLocaleString("en-US");u.textContent=w,u instanceof HTMLElement&&(u.dataset.countTarget=w)}if(f.starting_rank!==null){let w=f.starting_rank-k;p&&(p.textContent=Math.abs(w).toLocaleString()),w<0?(C&&(C.textContent="fell"),h&&(h.style.display="none"),g&&g.classList.add("invert")):(C&&(C.textContent="climbed"),h&&(h.style.display="inline-block"),g&&g.classList.remove("invert"))}if(P&&P.classList.remove("active"),ce&&ce.classList.remove("active"),B&&B.classList.remove("active"),k<=100?P&&P.classList.add("active"):k<=1e3?ce&&ce.classList.add("active"):k<=1e5&&B&&B.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(w=>{w.style.display="none"}),k<=100){let w=document.querySelector('[cohort-wins="top-100"]');w&&(w.style.display="block")}else if(k<=1e3){let w=document.querySelector('[cohort-wins="top-1000"]');w&&(w.style.display="block")}else if(k<=1e5){let w=document.querySelector('[cohort-wins="top-100k"]');w&&(w.style.display="block")}if(L)if(k<=100)L.innerHTML="You're in the <strong>top 100!</strong>";else if(k<=1e3){let w=k-100;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100`}else if(k<=1e5){let w=k-1e3;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 1,000`}else{let w=k-1e5;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100,000`}m.forEach(w=>{w.textContent=f.referral_code}),y&&(y.textContent=f.referrals_count.toString()),f.desktop_dictation_bonus_earned?(S&&(S.style.display="none"),v&&(v.style.display="block")):(S&&(S.style.display="block"),v&&(v.style.display="none")),f.phone_number_bonus_earned?(se&&(se.style.display="none"),N&&(N.style.display="block")):(se&&(se.style.display="block"),N&&(N.style.display="none")),f.verified_share_twitter&&lt&&lt.classList.add("verified"),f.verified_share_linkedin&&_&&_.classList.add("verified"),f.verified_share_whatsapp&&b&&b.classList.add("verified"),f.verified_share_slack&&A&&A.classList.add("verified"),f.verified_share_discord&&T&&T.classList.add("verified");let W=f.verified_share_twitter&&f.verified_share_linkedin&&f.verified_share_whatsapp&&f.verified_share_slack&&f.verified_share_discord;if(W&&(q&&(q.style.display="none"),R&&(R.style.display="block")),ke){let w=[f.phone_number_bonus_earned,f.desktop_dictation_bonus_earned,W].filter(Boolean).length;ke.textContent=`${w} of 3`}};br(D);let rs=f=>f<=100?"top-100":f<=1e3?"top-1000":f<=1e5?"top-100k":"below-100k";I("android_waitlist_page_view",{rank:D.current_rank,total_boost:D.total_boost,referrals_count:D.referrals_count,cohort:rs(D.current_rank),is_first_visit:We}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:D.current_rank,total_boost:D.total_boost,referrals_count:D.referrals_count,cohort:rs(D.current_rank),is_first_visit:We});let Ii=`https://wisprflow.ai/waitlist?${D.referral_code}`;document.querySelectorAll("[share]").forEach(f=>{let k=f.getAttribute("share");if(!k)return;let w=document.querySelector(`[share-content="${k}"]`)?.textContent||"";f.addEventListener("click",async()=>{switch(I("android_waitlist_share_clicked",{platform:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:k}),k){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(w)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(w),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(Ii)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(w)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(w),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(w),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async f=>{let k=f,{phoneNumber:W}=k.detail;try{let w=await j.submitPhoneNumber(W,z),ue=await w.json();if(!w.ok||!ue.success){let Ht=ue.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:Ht}})),I("android_waitlist_sms_error",{error:Ht}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:Ht});return}window.dispatchEvent(new CustomEvent("sms:success"));let he=await j.getAndroidWaitlistStats(z);he.ok&&br(await he.json()),I("android_waitlist_sms_submitted",{boost_earned:ue.boost_earned,new_rank:ue.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:ue.boost_earned,new_rank:ue.current_rank})}catch(w){console.error("SMS submission error:",w),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}})),I("android_waitlist_sms_error",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:"network_error"})}});let ye=f=>{de&&(de.style.display=f==="idle"?"block":"none"),_e&&(_e.style.display=f==="loading"?"block":"none"),at&&(at.style.display=f==="verified"?"block":"none"),De&&(De.style.display=f==="failed"?"block":"none"),K&&(K.style.display="none")},ji=f=>{let W=["image/png","image/jpeg","image/jpg"];return f.size>20971520?"File too large. Maximum size is 20MB.":W.includes(f.type)?null:"Please upload a PNG or JPEG image."},$i={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},Ui=f=>$i[f]||"Social Media",Mi={social_share_x:lt,social_share_linkedin:_,social_share_whatsapp:b,social_share_slack:A,social_share_discord:T},Ni=f=>{let k=Mi[f];k&&k.classList.add("verified")},qi=f=>({file_too_large:"File exceeds 20MB limit. (file_too_large)",invalid_file_type:"Please upload a PNG or JPEG. (invalid_file_type)","User not on Android waitlist":"Please join the waitlist first. (User not on Android waitlist)",all_platforms_already_claimed:"You've claimed all social share bonuses! (all_platforms_already_claimed)",x_already_claimed:"You've already received the X bonus. (x_already_claimed)",linkedin_already_claimed:"You've already received the LinkedIn bonus. (linkedin_already_claimed)",whatsapp_already_claimed:"You've already received the WhatsApp bonus. (whatsapp_already_claimed)",slack_already_claimed:"You've already received the Slack bonus. (slack_already_claimed)",discord_already_claimed:"You've already received the Discord bonus. (discord_already_claimed)",not_posted:"This looks like a draft, not a published post. (not_posted)",no_wispr_mention:"Post must mention Wispr Flow or wisprflow.ai. (no_wispr_mention)",invalid:"We couldn't verify this screenshot. Try a clearer image. (invalid)","An error occurred":"Something went wrong. Please try again. (An error occurred)"})[f??""]??`Verification failed. (${f})`,ut=null;Se&&Se.addEventListener("change",async()=>{let f=Se.files?.[0];if(!f)return;Se.value="";let k=ji(f);if(k){K&&(K.textContent=k,K.style.display="block"),I("android_waitlist_social_validation_error",{error:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:k});return}I("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),ye("loading"),ut=new AbortController;try{let W=await j.submitSocialShare(f,z,ut.signal),w=await W.json();if(!W.ok||!w.success){ye("failed"),Fe&&(Fe.textContent=qi(w.error)),I("android_waitlist_social_upload_failed",{error:w.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:w.error});return}ye("verified"),Ne&&(Ne.textContent=w.boost_earned.toLocaleString()),yr&&(yr.textContent=Ui(w.action)),Ni(w.action);let ue=await j.getAndroidWaitlistStats(z);if(ue.ok){let he=await ue.json();br(he),he.verified_share_twitter&&he.verified_share_linkedin&&he.verified_share_whatsapp&&he.verified_share_slack&&he.verified_share_discord&&(qe&&(qe.style.display="none"),F&&(F.style.display="none"),I("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}I("android_waitlist_social_share_verified",{platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank})}catch(W){if(W instanceof Error&&W.name==="AbortError"){ye("idle");return}console.error("Social share upload error:",W),ye("failed"),Fe&&(Fe.textContent="Network error. Please try again."),I("android_waitlist_social_upload_failed",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:"network_error"})}finally{ut=null}}),ot&&ot.addEventListener("click",()=>{ut&&ut.abort(),ye("idle"),I("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),qe&&qe.addEventListener("click",()=>{ye("idle")}),qt&&qt.addEventListener("click",()=>{ye("idle")}),Pi(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),xi()}catch(Y){console.error("Error on android-waitlist page:",Y),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await te()}});})();
1
+ "use strict";(()=>{var qi=Object.create;var Ht=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var Fi=Object.getOwnPropertyNames;var Hi=Object.getPrototypeOf,Wi=Object.prototype.hasOwnProperty;var Vi=(i,e)=>()=>(i&&(e=i(i=0)),e);var ie=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Bi=(i,e)=>{for(var t in e)Ht(i,t,{get:e[t],enumerable:!0})},rs=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fi(e))!Wi.call(i,s)&&s!==t&&Ht(i,s,{get:()=>e[s],enumerable:!(r=Di(e,s))||r.enumerable});return i};var ss=(i,e,t)=>(t=i!=null?qi(Hi(i)):{},rs(e||!i||!i.__esModule?Ht(t,"default",{value:i,enumerable:!0}):t,i)),zi=i=>rs(Ht({},"__esModule",{value:!0}),i);var Ee={};Bi(Ee,{Headers:()=>Sr,Request:()=>Xi,Response:()=>Qi,default:()=>kr,fetch:()=>Yi});var Ki,Ve,Yi,kr,Sr,Xi,Qi,ye=Vi(()=>{"use strict";Ki=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")},Ve=Ki(),Yi=Ve.fetch,kr=Ve.fetch.bind(Ve),Sr=Ve.Headers,Xi=Ve.Request,Qi=Ve.Response});var us=ie(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});var Er=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Tr.default=Er});var Ar=ie(pt=>{"use strict";var hs=pt&&pt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(pt,"__esModule",{value:!0});var en=hs((ye(),zi(Ee))),tn=hs(us()),xr=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=en.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,l;let c=null,d=null,u=null,p=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let C=await n.text();C===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?d=C:d=JSON.parse(C))}let S=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),v=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");S&&v&&v.length>1&&(u=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(c={code:"PGRST116",details:`Results contain ${d.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},d=null,u=null,p=406,m="Not Acceptable"):d.length===1?d=d[0]:d=null)}else{let S=await n.text();try{c=JSON.parse(S),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,m="OK")}catch{n.status===404&&S===""?(p=204,m="No Content"):c={message:S}}if(c&&this.isMaybeSingle&&(!((l=c?.details)===null||l===void 0)&&l.includes("0 rows"))&&(c=null,p=200,m="OK"),c&&this.shouldThrowOnError)throw new tn.default(c)}return{error:c,data:d,count:u,status:p,statusText:m}});return this.shouldThrowOnError||(s=s.catch(n=>{var o,a,l;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}};pt.default=xr});var Cr=ie(mt=>{"use strict";var rn=mt&&mt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(mt,"__esModule",{value:!0});var sn=rn(Ar()),Lr=class extends sn.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 l=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};mt.default=Lr});var Gt=ie(gt=>{"use strict";var nn=gt&&gt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(gt,"__esModule",{value:!0});var on=nn(Cr()),Rr=class extends on.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}};gt.default=Rr});var Pr=ie(yt=>{"use strict";var an=yt&&yt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(yt,"__esModule",{value:!0});var _t=an(Gt()),Or=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 _t.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,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new _t.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 l=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){let c=[...new Set(l)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new _t.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 _t.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 _t.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};yt.default=Or});var fs=ie(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.version=void 0;Kt.version="0.0.0-automated"});var ps=ie(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.DEFAULT_HEADERS=void 0;var ln=fs();Yt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ln.version}`}});var gs=ie(wt=>{"use strict";var ms=wt&&wt.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(wt,"__esModule",{value:!0});var cn=ms(Pr()),dn=ms(Gt()),un=ps(),Ir=class i{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},un.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new cn.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}`),l;r||s?(o=r?"HEAD":"GET",Object.entries(t).filter(([d,u])=>u!==void 0).map(([d,u])=>[d,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([d,u])=>{a.searchParams.append(d,u)})):(o="POST",l=t);let c=Object.assign({},this.headers);return n&&(c.Prefer=`count=${n}`),new dn.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};wt.default=Ir});var ks=ie(W=>{"use strict";var vt=W&&W.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(W,"__esModule",{value:!0});W.PostgrestBuilder=W.PostgrestTransformBuilder=W.PostgrestFilterBuilder=W.PostgrestQueryBuilder=W.PostgrestClient=void 0;var _s=vt(gs());W.PostgrestClient=_s.default;var ys=vt(Pr());W.PostgrestQueryBuilder=ys.default;var ws=vt(Gt());W.PostgrestFilterBuilder=ws.default;var vs=vt(Cr());W.PostgrestTransformBuilder=vs.default;var bs=vt(Ar());W.PostgrestBuilder=bs.default;W.default={PostgrestClient:_s.default,PostgrestQueryBuilder:ys.default,PostgrestFilterBuilder:ws.default,PostgrestTransformBuilder:vs.default,PostgrestBuilder:bs.default}});var Os=ie((Ho,Rs)=>{"use strict";Rs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Wt=i=>i.verification_method==="email_otp"&&typeof i.pending_authentication_token=="string"&&i.pending_authentication_token.length>0,U="https://api.wisprflow.ai",fe=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="AriaAuthError"}},Q=i=>i.trim().toLowerCase(),is=(i,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof i.code=="string"?i.code:i.detail&&!Array.isArray(i.detail)&&typeof i.detail=="object"&&typeof i.detail.code=="string"?i.detail.code:typeof i.detail=="string"&&t.has(i.detail)?i.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},ut=(i,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[i]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Ji=(i,e,t)=>[i.message,i.detail&&!Array.isArray(i.detail)&&typeof i.detail=="object"?i.detail.message:null,typeof i.detail=="string"?i.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??ut(e,t),We=(i,e)=>{let t=is(i,e);return new fe(e,t,Ji(i,t,e))},Gi=(i,e)=>{let t=is(i,e);return new fe(e,t,ut(t,e))},br=class{static async signupUser(e){try{let t=`${U}/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(`${U}/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(`${U}/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(`${U}/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(`${U}/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){let t=Q(e),r=await fetch(`${U}/user_status?email=${encodeURIComponent(t)}`),s=await r.json().catch(()=>({}));if(!r.ok)throw We(s,r.status);return s}static async requestPasswordReset(e,t){let r=await fetch(`${U}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:Q(e),captcha_token:t})});if(!r.ok){let s=await r.json().catch(()=>({}));throw We(s,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${U}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${U}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${U}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new fe(422,"invalid_code",ut("invalid_code",422));let t=await fetch(`${U}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok){let s=Gi(r,t.status);throw s.code==="rate_limited"||s.code==="provider_unavailable"||s.code==="validation_error"?s:new fe(t.status,"verification_failed",ut("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new fe(t.status,"authentication_failed",ut("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${U}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async getSubscriptionStatus(e){return await fetch(`${U}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${U}/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=`${U}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(s+=`&currency=${r}`),await(await fetch(s,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${U}/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(`${U}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${U}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${U}/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(`${U}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:s,signal:r})}};function ns(i){let[e,...t]=i.split(" "),r=t.join(" ");return[e,r]}function os(i){return i==="azure"?"Microsoft":i==="workos"?"SSO":i.charAt(0).toUpperCase()+i.slice(1)}var j=br;var as=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,r]=e.split("=");return i[t]=r,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 cs=()=>{let{access_token:i,refresh_token:e}=ls(),t=i,r=e;if(!t||!r){let s=as();t=s.access_token,r=s.refresh_token}return{accessToken:t,refreshToken:r}};var ds=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ht=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Vt=class extends ht{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Bt=class extends ht{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},zt=class extends ht{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Jt;(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"})(Jt||(Jt={}));var Zi=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(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):s(d.value).then(a,l)}c((r=r.apply(i,e||[])).next())})},ft=class{constructor(e,{headers:t={},customFetch:r,region:s=Jt.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=ds(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return Zi(this,void 0,void 0,function*(){try{let{headers:s,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let c;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",c=o):typeof o=="string"?(a["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(a["Content-Type"]="application/json",c=JSON.stringify(o)));let d=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),s),body:c}).catch(y=>{throw new Vt(y)}),u=d.headers.get("x-relay-error");if(u&&u==="true")throw new Bt(d);if(!d.ok)throw new zt(d);let p=((r=d.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return p==="application/json"?m=yield d.json():p==="application/octet-stream"?m=yield d.blob():p==="text/event-stream"?m=d:p==="multipart/form-data"?m=yield d.formData():m=yield d.text(),{data:m,error:null}}catch(s){return{data:null,error:s}}})}};var Ss=ss(ks(),1),{PostgrestClient:Es,PostgrestQueryBuilder:So,PostgrestFilterBuilder:Eo,PostgrestTransformBuilder:To,PostgrestBuilder:xo}=Ss.default;var Ts="2.10.2";var xs={"X-Client-Info":`realtime-js/${Ts}`},As="1.0.0",Qt=1e4,Ls=1e3,Te;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(Te||(Te={}));var B;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(B||(B={}));var K;(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"})(K||(K={}));var Xt;(function(i){i.websocket="websocket"})(Xt||(Xt={}));var we;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(we||(we={}));var bt=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 l=r.decode(e.slice(o,o+n));o=o+n;let c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}};var xe=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 R;(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"})(R||(R={}));var $r=(i,e,t={})=>{var r;let s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=hn(o,i,e,s),n),{})},hn=(i,e,t,r)=>{let s=e.find(a=>a.name===i),n=s?.type,o=t[i];return n&&!r.includes(n)?Cs(n,o):jr(o)},Cs=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return gn(e,t)}switch(i){case R.bool:return fn(e);case R.float4:case R.float8:case R.int2:case R.int4:case R.int8:case R.numeric:case R.oid:return pn(e);case R.json:case R.jsonb:return mn(e);case R.timestamp:return _n(e);case R.abstime:case R.date:case R.daterange:case R.int4range:case R.int8range:case R.money:case R.reltime:case R.text:case R.time:case R.timestamptz:case R.timetz:case R.tsrange:case R.tstzrange:return jr(e);default:return jr(e)}},jr=i=>i,fn=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},pn=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},mn=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},gn=(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=>Cs(e,a))}return i},_n=i=>typeof i=="string"?i.replace(" ","T"):i,Zt=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Ae=class{constructor(e,t,r={},s=Qt){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 Ur;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Ur||(Ur={}));var Be=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(l=>{this.state=i.syncDiff(this.state,l,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={},l={};return this.map(n,(c,d)=>{o[c]||(l[c]=d)}),this.map(o,(c,d)=>{let u=n[c];if(u){let p=d.map(v=>v.presence_ref),m=u.map(v=>v.presence_ref),y=d.filter(v=>m.indexOf(v.presence_ref)<0),S=u.filter(v=>p.indexOf(v.presence_ref)<0);y.length>0&&(a[c]=y),S.length>0&&(l[c]=S)}else a[c]=d}),this.syncDiff(n,{joins:a,leaves:l},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,l)=>{var c;let d=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),d.length>0){let u=e[a].map(m=>m.presence_ref),p=d.filter(m=>u.indexOf(m.presence_ref)<0);e[a].unshift(...p)}r(a,d,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let d=l.map(u=>u.presence_ref);c=c.filter(u=>d.indexOf(u.presence_ref)<0),e[a]=c,s(a,c,l),c.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 Mr;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Mr||(Mr={}));var Nr;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Nr||(Nr={}));var qr;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(qr||(qr={}));var ze=class i{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=B.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 Ae(this,K.join,this.params,this.timeout),this.rejoinTimer=new xe(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=B.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=B.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=B.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=B.errored,this.rejoinTimer.scheduleTimeout())}),this._on(K.reply,{},(s,n)=>{this._trigger(this._replyEventName(n),s)}),this.presence=new Be(this),this.broadcastEndpointURL=Zt(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(d=>e&&e("CHANNEL_ERROR",d)),this._onClose(()=>e&&e("CLOSED"));let l={},c={broadcast:n,presence:o,postgres_changes:(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(d=>d.filter))!==null&&s!==void 0?s:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:c},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:d})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),d===void 0){e&&e("SUBSCRIBED");return}else{let p=this.bindings.postgres_changes,m=(u=p?.length)!==null&&u!==void 0?u:0,y=[];for(let S=0;S<m;S++){let v=p[S],{filter:{event:C,schema:h,table:g,filter:L}}=v,O=d&&d[S];if(O&&O.event===C&&O.schema===h&&O.table===g&&O.filter===L)y.push(Object.assign(Object.assign({},v),{id:O.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",d=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(d).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 l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=l.body)===null||s===void 0?void 0:s.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=B.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(K.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let s=new Ae(this,K.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 Ae(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:l,leave:c,join:d}=K;if(r&&[a,l,c,d].indexOf(o)>=0&&r!==this._joinRef())return;let p=this._onMessage(o,t,r);if(t&&!p)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(m=>{var y,S,v;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((v=(S=m.filter)===null||S===void 0?void 0:S.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===o}).map(m=>m.callback(p,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var y,S,v,C,h,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let L=m.id,O=(y=m.filter)===null||y===void 0?void 0:y.event;return L&&((S=t.ids)===null||S===void 0?void 0:S.includes(L))&&(O==="*"||O?.toLocaleLowerCase()===((v=t.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{let L=(h=(C=m?.filter)===null||C===void 0?void 0:C.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return L==="*"||L===((g=t?.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof p=="object"&&"ids"in p){let y=p.data,{schema:S,table:v,commit_timestamp:C,type:h,errors:g}=y;p=Object.assign(Object.assign({},{schema:S,table:v,commit_timestamp:C,eventType:h,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(p,r)})}_isClosed(){return this.state===B.closed}_isJoined(){return this.state===B.joined}_isJoining(){return this.state===B.joining}_isLeaving(){return this.state===B.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(K.close,{},e)}_onError(e){this._on(K.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=B.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=$r(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=$r(e.columns,e.old_record)),t}};var wn=()=>{},vn=typeof WebSocket<"u",Je=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=xs,this.params={},this.timeout=Qt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=wn,this.conn=null,this.sendBuffer=[],this.serializer=new bt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Xt.websocket}`,this.httpEndpoint=Zt(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 xe(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(vn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Dr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ss(Os())).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 Te.connecting:return we.Connecting;case Te.open:return we.Open;case Te.closing:return we.Closing;default:return we.Closed}}isConnected(){return this.connectionState()===we.Open}channel(e,t={config:{}}){let r=new ze(`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 l;(l=this.conn)===null||l===void 0||l.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(K.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:As}))}_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(K.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(Ls,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Dr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Te.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Ge=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function N(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var er=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}}},kt=class extends Ge{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var bn=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(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):s(d.value).then(a,l)}c((r=r.apply(i,e||[])).next())})},tr=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Ps=()=>bn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ye(),Ee))).Response:Response});var Ke=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(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):s(d.value).then(a,l)}c((r=r.apply(i,e||[])).next())})},Fr=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),kn=(i,e)=>Ke(void 0,void 0,void 0,function*(){let t=yield Ps();i instanceof t?i.json().then(r=>{e(new er(Fr(r),i.status||500))}).catch(r=>{e(new kt(Fr(r),r))}):e(new kt(Fr(i),i))}),Sn=(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 rr(i,e,t,r,s,n){return Ke(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Sn(e,r,s,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>kn(l,a))})})}function St(i,e,t,r){return Ke(this,void 0,void 0,function*(){return rr(i,"GET",e,t,r)})}function ne(i,e,t,r,s){return Ke(this,void 0,void 0,function*(){return rr(i,"POST",e,r,s,t)})}function Is(i,e,t,r,s){return Ke(this,void 0,void 0,function*(){return rr(i,"PUT",e,r,s,t)})}function sr(i,e,t,r,s){return Ke(this,void 0,void 0,function*(){return rr(i,"DELETE",e,r,s,t)})}var Z=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(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):s(d.value).then(a,l)}c((r=r.apply(i,e||[])).next())})},En={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},js={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Et=class{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=tr(s)}uploadOrUpdate(e,t,r,s){return Z(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},js),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 l=this._removeEmptyFolders(t),c=this._getFinalPath(l),d=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield d.json();return d.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(N(n))return{data:null,error:n};throw n}})}upload(e,t,r){return Z(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return Z(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l,c=Object.assign({upsert:js.upsert},s),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:d}),p=yield u.json();return u.ok?{data:{path:n,fullPath:p.Key},error:null}:{data:null,error:p}}catch(l){if(N(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return Z(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 ne(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(N(r))return{data:null,error:r};throw r}})}update(e,t,r){return Z(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return Z(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(N(s))return{data:null,error:s};throw s}})}copy(e,t,r){return Z(this,void 0,void 0,function*(){try{return{data:{path:(yield ne(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(N(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,r){return Z(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=yield ne(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(N(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return Z(this,void 0,void 0,function*(){try{let s=yield ne(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(N(s))return{data:null,error:s};throw s}})}download(e,t){return Z(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 St(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(N(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",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&s.push(l);let c=s.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return Z(this,void 0,void 0,function*(){try{return{data:yield sr(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}list(e,t,r){return Z(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},En),t),{prefix:e||""});return{data:yield ne(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(N(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 $s="2.6.0";var Us={"X-Client-Info":`storage-js/${$s}`};var Ye=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(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):s(d.value).then(a,l)}c((r=r.apply(i,e||[])).next())})},Tt=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Us),t),this.fetch=tr(r)}listBuckets(){return Ye(this,void 0,void 0,function*(){try{return{data:yield St(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(N(e))return{data:null,error:e};throw e}})}getBucket(e){return Ye(this,void 0,void 0,function*(){try{return{data:yield St(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Ye(this,void 0,void 0,function*(){try{return{data:yield ne(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(N(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Ye(this,void 0,void 0,function*(){try{return{data:yield Is(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(N(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Ye(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Ye(this,void 0,void 0,function*(){try{return{data:yield sr(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(N(t))return{data:null,error:t};throw t}})}};var xt=class extends Tt{constructor(e,t={},r){super(e,t,r)}from(e){return new Et(this.url,this.headers,e,this.fetch)}};var Ms="2.44.4";var At="";typeof Deno<"u"?At="deno":typeof document<"u"?At="web":typeof navigator<"u"&&navigator.product==="ReactNative"?At="react-native":At="node";var Tn={"X-Client-Info":`supabase-js-${At}/${Ms}`},Ns={headers:Tn},qs={schema:"public"},Ds={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Fs={};ye();var xn=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(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):s(d.value).then(a,l)}c((r=r.apply(i,e||[])).next())})},An=i=>{let e;return i?e=i:typeof fetch>"u"?e=kr:e=fetch,(...t)=>e(...t)},Ln=()=>typeof Headers>"u"?Sr:Headers,Hs=(i,e,t)=>{let r=An(t),s=Ln();return(n,o)=>xn(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:i,c=new s(o?.headers);return c.has("apikey")||c.set("apikey",i),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:c}))})};function Ws(i){return i.replace(/\/$/,"")}function Vs(i,e){let{db:t,auth:r,realtime:s,global:n}=i,{db:o,auth:a,realtime:l,global:c}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),s),global:Object.assign(Object.assign({},c),n)}}var ir="2.64.4";var Bs="http://localhost:9999",zs="supabase.auth.token";var Js={"X-Client-Info":`gotrue-js/${ir}`},Hr=10;var Lt="X-Supabase-Api-Version",Wr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Gs(i){return Math.round(Date.now()/1e3)+i}function Ks(){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 ee=()=>typeof document<"u",Le={tested:!1,writable:!1},ve=()=>{if(!ee())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Le.tested)return Le.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),Le.tested=!0,Le.writable=!0}catch{Le.tested=!0,Le.writable=!1}return Le.writable};function nr(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 or=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Ys=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",Vr=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},Rt=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ar=async(i,e)=>{await i.removeItem(e)};function Cn(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,s,n,o,a,l,c,d=0;for(i=i.replace("-","+").replace("_","/");d<i.length;)o=e.indexOf(i.charAt(d++)),a=e.indexOf(i.charAt(d++)),l=e.indexOf(i.charAt(d++)),c=e.indexOf(i.charAt(d++)),r=o<<2|a>>4,s=(a&15)<<4|l>>2,n=(l&3)<<6|c,t=t+String.fromCharCode(r),l!=64&&s!=0&&(t=t+String.fromCharCode(s)),c!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Ct=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Ct.promiseConstructor=Promise;function Br(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(Cn(r))}async function Xs(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Qs(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 Rn(i){return("0"+i.toString(16)).substr(-2)}function On(){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,Rn).join("")}async function Pn(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 In(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function jn(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 Pn(i);return In(t)}async function Ce(i,e,t=!1){let r=On(),s=r;t&&(s+="/PASSWORD_RECOVERY"),await Vr(i,`${e}-code-verifier`,s);let n=await jn(r);return[n,r===n?"plain":"s256"]}var $n=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Zs(i){let e=i.headers.get(Lt);if(!e||!e.match($n))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Ot=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function E(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var lr=class extends Ot{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function ei(i){return E(i)&&i.name==="AuthApiError"}var Xe=class extends Ot{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},pe=class extends Ot{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},oe=class extends pe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Qe=class extends pe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Re=class extends pe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Oe=class extends pe{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}}},Pt=class extends pe{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}}},Ze=class extends pe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function cr(i){return E(i)&&i.name==="AuthRetryableFetchError"}var It=class extends pe{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Un=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},Pe=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Mn=[502,503,504];async function ti(i){var e;if(!Ys(i))throw new Ze(Pe(i),0);if(Mn.includes(i.status))throw new Ze(Pe(i),i.status);let t;try{t=await i.json()}catch(n){throw new Xe(Pe(n),n)}let r,s=Zs(i);if(s&&s.getTime()>=Wr["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 It(Pe(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 It(Pe(t),i.status,t.weak_password.reasons);throw new lr(Pe(t),i.status||500,r)}var Nn=(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 T(i,e,t,r){var s;let n=Object.assign({},r?.headers);n[Lt]||(n[Lt]=Wr["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():"",l=await qn(i,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function qn(i,e,t,r,s,n){let o=Nn(e,r,s,n),a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new Ze(Pe(l),0)}if(a.ok||await ti(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await ti(l)}}function me(i){var e;let t=null;Dn(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Gs(i.expires_in)));let r=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:r},error:null}}function zr(i){let e=me(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 ae(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function ri(i){return{data:i,error:null}}function si(i){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n}=i,o=Un(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},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function ii(i){return i}function Dn(i){return i.access_token&&i.refresh_token&&i.expires_in}var Fn=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},Ie=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=or(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await T(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(E(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await T(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Fn(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:si,redirectTo:t?.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await T(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,n,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},d=await T(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:ii});if(d.error)throw d.error;let u=await d.json(),p=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=d.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{let S=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(y.split(";")[1].split("=")[1]);c[`${v}Page`]=S}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(E(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await T(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await T(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await T(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(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await T(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}};var ni={getItem:i=>ve()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{ve()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{ve()&&globalThis.localStorage.removeItem(i)}};function Jr(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function oi(){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 je={debug:!!(globalThis&&ve()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},jt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},dr=class extends jt{};async function Gr(i,e,t){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),je.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){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,s.name);try{return await t()}finally{je.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,s.name)}}else{if(e===0)throw je.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new dr(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(je.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()}})}oi();var Hn={url:Bs,storageKey:zs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Js,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},$t=30*1e3,ai=3;async function li(i,e,t){return await t()}var $e=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&&ee()&&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({},Hn),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 Ie({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=or(s.fetch),this.lock=s.lock||li,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:ee()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Gr:this.lock=li,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:ve()?this.storage=ni:(this.memoryStorage={},this.storage=Jr(this.memoryStorage)):(this.memoryStorage={},this.storage=Jr(this.memoryStorage)),ee()&&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} (${ir}) ${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=ee()?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(e)?{error:e}:{error:new Xe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let n=await T(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:me}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(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:d,password:u,options:p}=e,m=null,y=null;this.flowType==="pkce"&&([m,y]=await Ce(this.storage,this.storageKey)),n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:d,password:u,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:m,code_challenge_method:y},xform:me})}else if("phone"in e){let{phone:d,password:u,options:p}=e;n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:u,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(s=p?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:me})}else throw new Re("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(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 T(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:zr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await T(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:zr})}else throw new Re("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 Qe}:(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(E(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 Rt(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(t??"").split("/"),{data:n,error:o}=await T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:me});return await ar(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 Qe}:(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 T(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:me}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Qe}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(E(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:l}=e,c=null,d=null;this.flowType==="pkce"&&([c,d]=await Ce(this.storage,this.storageKey));let{error:u}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:d},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:d}}throw new Re("You must provide either an email or phone number.")}catch(a){if(E(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 T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:me});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(s){if(E(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 Ce(this.storage,this.storageKey)),await T(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:ri})}catch(n){if(E(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 oe;let{error:s}=await T(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(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 T(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 T(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 Re("You must provide either an email or phone number and a type")}catch(t){if(E(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 Rt(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:(l,c,d)=>(!o&&c==="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(l,c,d))})}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 T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ae}):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 oe}:await T(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:ae})})}catch(t){if(E(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 oe;let o=s.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Ce(this.storage,this.storageKey));let{data:c,error:d}=await T(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:ae});if(d)throw d;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return Br(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 oe;let t=Date.now()/1e3,r=t,s=!0,n=null,o=Br(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(E(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 oe;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(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!ee())throw new Oe("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Oe("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Pt("Not a valid PKCE flow url.");let t=nr(window.location.href);if(e){if(!t.code)throw new Pt("No code detected.");let{data:h,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;let L=new URL(window.location.href);return L.searchParams.delete("code"),window.history.replaceState(window.history.state,"",L.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Oe(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:l,token_type:c}=t;if(!n||!a||!o||!c)throw new Oe("No session defined in URL");let d=Math.round(Date.now()/1e3),u=parseInt(a),p=d+u;l&&(p=parseInt(l));let m=p-d;m*1e3<=$t&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${u}s`);let y=p-u;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,p,d);let{data:S,error:v}=await this._getUser(n);if(v)throw v;let C={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:u,expires_at:p,refresh_token:o,token_type:c,user:S.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:C,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=nr(window.location.href);return!!(ee()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=nr(window.location.href),t=await Rt(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&&!(ei(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await ar(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ks(),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 Ce(this.storage,this.storageKey,!0));try{return await T(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(E(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(E(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,l,c,d;let{data:u,error:p}=n;if(p)throw p;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",m,{headers:this.headers,jwt:(d=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&d!==void 0?d:void 0})});if(s)throw s;return ee()&&!(!((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(E(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 T(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(E(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 Qs(async s=>(s>0&&await Xs(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:me})),(s,n)=>{let o=200*Math.pow(2,s);return n&&cr(n)&&Date.now()+o-r<$t})}catch(r){if(this._debug(t,"error",r),E(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),ee()&&!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 Rt(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+Hr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Hr}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),cr(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 oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Ct;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new oe;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),E(n)){let o={session:null,error:n};return cr(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(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Vr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ar(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ee()&&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(),$t);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)/$t);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${$t}ms, refresh threshold is ${ai} ticks`),s<=ai&&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 jt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ee()||!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 Ce(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 T(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(E(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:l}=await T(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 l?{data:null,error:l}:(!((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(E(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 T(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(E(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 T(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(E(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 l=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&&(l="aal2");let d=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:d},error:null}}))}};$e.nextInstanceID=0;var Wn=$e,Kr=Wn;var ur=class extends Kr{constructor(e){super(e)}};var Vn=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(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):s(d.value).then(a,l)}c((r=r.apply(i,e||[])).next())})},Ut=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=Ws(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,c={db:qs,realtime:Fs,auth:Object.assign(Object.assign({},Ds),{storageKey:l}),global:Ns},d=Vs(r??{},c);this.storageKey=(s=d.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=d.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=d.auth)!==null&&o!==void 0?o:{},this.headers,d.global.fetch),this.fetch=Hs(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},d.realtime)),this.rest=new Es(`${a}/rest/v1`,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new ft(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new xt(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 Vn(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},l,c){var d;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ur({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,flowType:o,debug:a,fetch:c,hasCustomAuthorizationHeader:(d="Authorization"in this.headers)!==null&&d!==void 0?d:!1})}_initRealtimeClient(e){return new Je(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 ci=(i,e,t)=>new Ut(i,e,t);var ge={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Bn=i=>{try{let e=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(i.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},hr=i=>{let[e,t]=i.split(".");return!e||!t?null:Bn(t)},di=i=>{let e=hr(i);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var zn="https://api.workos.com",Jn=60,et=(i,e)=>typeof i[e]=="string"?i[e]:void 0,ui=(i,e,t)=>{let r=hr(i);if(!r)return null;let s=et(r,"urn:wispr:user_external_id")??et(r,"sub"),n=t?.email??et(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,l={id:s??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:i,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:l}},Gn=async(i,e,t,r)=>{let s=t?.startsWith("https://")?t.replace(/\/$/,""):zn,n=await fetch(`${s}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:i,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},hi=async(i,e)=>{let t=hr(i);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),s=typeof t.exp=="number"?t.exp:0,n=et(t,"client_id");if(s-r<Jn&&n){let l=await Gn(e,n,et(t,"iss"),et(t,"org_id")),c=ui(l.access_token,l.refresh_token,l.user);if(!c)throw new Error("WorkOS refresh returned an invalid access token");return c}if(s<=r)throw new Error("WorkOS session expired");let a=ui(i,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var tt=class{constructor(){this.sessionData=null;this.supabase=ci(ge.supaBaseUrl,ge.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ge.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||ge.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||ge.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 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{if(di(t)==="workos"){this.sessionData=await hi(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}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||ge.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,s,n,o){try{if(!n)throw new Error("Please complete the verification");let a=await j.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:s||ge.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),a}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,r,s){try{if(!r)throw new Error("Please complete the verification");let n=await j.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:s?.provision??!1,workos_capable:s?.workosCapable||void 0});if(Wt(n))return{kind:"otp",challenge:n};if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0,provider:n.provider||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r,s){try{if(!r)throw new Error("Please complete the verification");let n=await j.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||ge.redirectUri,workos_capable:s?.workosCapable||void 0});return console.log("Verification request completed"),n}catch(n){throw console.error("Error resending verification email:",n),n}}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 fr=null,fi=(i,e)=>{if(!(i instanceof Error)||i.name!=="AriaAuthError")return e;let t={verification_failed:"Incorrect or expired code. Try again.",invalid_code:"Enter the six-digit code.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again."},{code:r}=i;return r&&t[r]||e},pr=()=>{fr!==null&&(window.clearInterval(fr),fr=null)};function rt(){let i=document.querySelector("[otp-verification]");i&&(i.style.display="none"),pr()}function pi(i){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),r=document.querySelector("[otp-email]"),s=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),l=document.querySelector("[otp-resend-countdown]"),c=document.querySelector("[otp-resend-seconds]"),d=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),n&&(n.style.display="none"),l&&(l.style.display="none"),a&&(a.style.display=""),s&&(s.textContent="Verify",s.style.pointerEvents="",s.removeAttribute("aria-disabled")),pr(),r&&(r.textContent=i.email),e.style.display="block",t[0]?.focus();let u=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},p=()=>{n&&(n.style.display="none")},m=!1,y=!1,S=h=>{s&&(s.style.pointerEvents=h?"none":"",h?s.setAttribute("aria-disabled","true"):s.removeAttribute("aria-disabled"),s instanceof HTMLButtonElement&&(s.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},v=async()=>{if(m)return;let h=t.map(g=>g.value).join("");if(h.length!==6){u("Please enter all 6 digits.");return}m=!0,S(!0),t.forEach(g=>g.setAttribute("disabled","true")),p();try{await i.onVerify(h),p(),s&&(s.textContent="Verified \u2705")}catch(g){m=!1,S(!1),t.forEach(L=>{L.value="",L.removeAttribute("disabled")}),u(fi(g,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,g)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&g<t.length-1&&t[g+1].focus(),p()},h.onkeydown=L=>{L.key==="Backspace"&&!h.value&&g>0?t[g-1].focus():L.key==="Enter"&&(L.preventDefault(),v())},h.onpaste=L=>{L.preventDefault();let O=(L.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((z,se)=>{t[se]&&(t[se].value=z)});let ce=Math.min(O.length,t.length-1);t[ce]?.focus(),p()}}),s&&(s.onclick=h=>{h.preventDefault(),v()});let C=()=>{let h=30;a&&(a.style.display="none"),l&&(l.style.display="block"),c&&(c.textContent=String(h)),pr(),fr=window.setInterval(()=>{h-=1,c&&(c.textContent=String(h)),h<=0&&(pr(),a&&(a.style.display=""),l&&(l.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(y||a.style.display==="none")){y=!0,t.forEach(g=>{g.value="",g.removeAttribute("disabled")}),t[0]?.focus(),p(),C();try{await i.onResend?.()}catch(g){u(fi(g,"We couldn't send a new code. Please try again when the timer ends."))}finally{y=!1}}}),d&&(d.onclick=h=>{h.preventDefault(),rt(),i.onReset?.()})}var Ue=()=>window.hcaptcha,mr=async()=>{let i=Ue();if(!i)throw new Error("Verification system not loaded");let e=await i.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Mt=(i,e)=>i instanceof Error?i.message:e,mi=(i,e)=>i instanceof fe?i.code==="sso_required"?(e.showSso(),!0):i.code==="scim_managed_domain"?(e.showScim(),!0):(i.code==="sign_in_to_continue"&&e.showLogin(),e.showError(i.message),!0):!1,gi=i=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:Q(r.email)},i.beforeShow(),pi({email:e.email,onVerify:async s=>{if(!e)throw rt(),i.onMissingChallenge(),new Error("Missing OTP challenge");let n=await j.verifyEmailOtp({code:s,pending_authentication_token:e.pendingAuthenticationToken});t(),await i.onAuthenticated(n)},onResend:async()=>{if(!e)throw rt(),i.onMissingChallenge(),new Error("Missing OTP challenge");let s=await mr();try{await i.client.resendVerificationEmail(e.email,i.redirectUrl,s,{workosCapable:i.isWorkosCapable(e.email)})}finally{Ue()?.reset()}},onReset:()=>{t(),i.onReset()}})}}};var le=null;function Yr(i,e=30,t){le&&(clearInterval(le),le=null);let r=e;i.style.pointerEvents="none",i.textContent=`Resend (${r}s)`,le=setInterval(()=>{r=r-1,i.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(i.style.pointerEvents="auto",le&&(clearInterval(le),le=null),t&&t())},1e3)}function _i(){le&&(clearInterval(le),le=null)}var yi=/^[\p{L}\p{M}\s\-'.]+$/u;function Kn(i,e){let t=i.trim();return t?/\d/.test(t)?"Your name can't include numbers":yi.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Xr(i,e){let t=i.trim();return t?/\d/.test(t)?"Your name can't include numbers":yi.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function wi(i,e,t){let r="full-name-match-error",s=l=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let c=document.getElementById(r);c||(c=document.createElement("div"),c.id=r,c.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",c)),c.textContent=l},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let l=Kn(e.value,i.value);l?s(l):n()},a=()=>{let l=Xr(e.value,i.value);l?s(l):n()};i.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var P=(i,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:i,retry_attempt:10-t}),window.posthog.capture(i,e)):t>0&&setTimeout(()=>P(i,e,t-1),200)},vi=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};var Yn="wispr_workos_capable";var bi=()=>{try{return window.sessionStorage.getItem(Yn)==="true"}catch{return!1}};function ki(i,e){let t=new tt,r="email_input",s=null,n=()=>{s?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),l=document.querySelector("#password-input"),c=document.querySelector("#full-name"),d=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),p=document.querySelector("#microsoft-login"),m=document.querySelector("[email-element]"),y=document.querySelector("[different-provider]"),S=document.querySelector("[different-provider-name]"),v=document.querySelector("[different-provider-reset]"),C=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),g=document.querySelector("[error-message]"),L=document.querySelector("[verification-email]"),O=document.querySelector("[email-signup-retry]"),ce=document.querySelector("[email-signup-reset]"),z=document.querySelector("[scim-div]"),se=document.querySelector("[scim-reset]"),q=document.querySelector("[forgot-password]"),be=document.querySelector("[forgot-password-success]"),st=document.querySelector("[forgot-password-email]"),te=document.querySelector("[unverified-email]"),it=document.querySelector("[unverified-email-address]"),de=document.querySelector("[resend-verification-email]"),ke=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(i)}catch(_){console.error("Error during Google sign-in:",_)}}),u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(i)}catch(_){console.error("Error during Apple sign-in:",_)}}),p&&p.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(i)}catch(_){console.error("Error during Microsoft sign-in:",_)}}));let Y=()=>{n(),y&&(y.style.display="none"),C&&(C.style.display="none"),h&&(h.style.display="none"),te&&(te.style.display="none"),z&&(z.style.display="none"),q&&(q.style.display="none"),be&&(be.style.display="none"),rt();let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="block"),m&&(m.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),l&&(l.value="",l.style.display="none",l.removeAttribute("required")),c&&(c.value="",c.style.display="none",c.removeAttribute("required"));let b=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");b&&(b.style.display="none"),A&&(A.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),r="email_input",a&&a.focus()},Se=()=>{m&&(m.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="none",c.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),q&&(q.style.display="block",q.onclick=async()=>{let A=a?.value||"",x=q.textContent||"";try{let{hcaptcha:D}=window;if(!D)throw new Error("Verification system not loaded. Please refresh the page.");q.style.pointerEvents="none",q.textContent="Sending...";let{response:I}=await D.execute({async:!0});if(!I)throw new Error("Verification cancelled");await j.requestPasswordReset(A,I),D.reset(),m&&(m.style.display="none"),q&&(q.style.display="none"),be&&(be.style.display="block"),st&&(st.textContent=A)}catch(D){console.error("Error sending password reset email:",D),q.textContent=x,q.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",g&&(g.textContent=D instanceof Error?D.message:"Failed to send reset email"))}}),r="login"},nt=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="block",c.setAttribute("required","true"));let _=document.querySelector("[captcha-embed]"),b=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),b&&(b.style.display="block"),r="signup"},ot=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),z&&(z.style.display="block"),se&&(se.onclick=()=>{z&&(z.style.display="none"),_&&(_.style.display="block"),Y()})},Me=_=>{n();let b=os(_);m&&(m.style.display="none"),y&&(y.style.display="block"),S&&(S.textContent=b),v&&(v.onclick=()=>{y&&(y.style.display="none"),Y()}),r="oauth_user"};s=gi({client:t,redirectUrl:i,isWorkosCapable:()=>!0,beforeShow:()=>{m&&(m.style.display="none"),te&&(te.style.display="none")},onAuthenticated:async _=>{n(),t.setCookies(_.access_token,_.refresh_token),localStorage.setItem("email",_.email),localStorage.setItem("user_id",_.user_id),localStorage.setItem("signin_provider","email");let b=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,b):window.location.href=i},onMissingChallenge:Se,onReset:Y});let Ne=_=>{m&&(m.style.display="none"),te&&(te.style.display="block"),it&&(it.textContent=_),de&&(de.onclick=async()=>{let b=de.textContent||"";try{let A=await mr();await t.resendVerificationEmail(_,i,A),de.textContent="Verification email resent! \u2705",de.style.textDecoration="none"}catch(A){de.textContent=b,h&&(h.style.display="block"),g&&(g.textContent=Mt(A,"Unable to resend verification."))}finally{Ue()?.reset()}}),ke&&(ke.onclick=()=>{te&&(te.style.display="none"),Y()}),r="unverified_email"},qe=_=>mi(_,{showSso:()=>Me("workos"),showScim:ot,showLogin:Se,showError:b=>{h&&(h.style.display="block"),g&&(g.textContent=b)}}),De=async(_,b)=>{let A=b.value;b.classList.add("loading"),b.value="";try{let x=await j.checkUserStatus(_);b.classList.remove("loading"),b.value=A,!x.exists&&x.scim_managed?ot():x.enforce_sso?Me("workos"):x.exists&&x.provider&&x.provider!=="email"&&x.provider!=="workos"?Me(x.provider):x.exists&&x.provider==="workos"?Se():x.exists&&x.provider==="email"&&!x.verified?Ne(_):x.exists&&x.provider==="email"?Se():nt()}catch(x){console.error("Error checking user status:",x),b.classList.remove("loading"),b.value=A,qe(x)||nt()}},Nt=async(_,b,A,x)=>{if(!b||b.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}let D=window.hcaptcha?.getResponse()||"";if(!D){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let F=await j.signInWithEmail({email:_,password:b,mcp_login_state:e.mcpLoginState,workos_capable:bi()});if(!F.redirect_url)throw new Error(F.error||"Unable to continue connector login. Please try again.");P("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=F.redirect_url;return}let I=bi(),M=await t.signInWithPassword(_,b,D,{workosCapable:I,provision:!1});if(M.kind==="otp"){if(!I)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let F={pendingAuthenticationToken:M.challenge.pending_authentication_token,email:Q(M.challenge.email||_)};Ue()?.reset(),A.classList.remove("loading"),A.value=x,s?.show(F);return}t.setCookies(M.accessToken,M.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(M.accessToken,M.refreshToken,M.fullName):window.location.href=i}catch(I){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=x,!qe(I)&&h&&(h.style.display="block",g&&(g.textContent=Mt(I,"Unable to sign in. Please try again.")))}},at=async(_,b,A,x,D)=>{if(!b||b.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}if(!A||A.trim().length<2){h&&(h.style.display="block",g&&(g.textContent="Please enter your full name"));return}let I=Xr(A,b);if(I){h&&(h.style.display="block",g&&(g.textContent=I));return}let M=window.hcaptcha?.getResponse()||"";if(!M){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{let F=await t.signUpWithPassword(_,b,A,i,M,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=D,m&&(m.style.display="none"),h&&(h.style.display="none"),Wt(F)){let X={pendingAuthenticationToken:F.pending_authentication_token,email:Q(F.email||_)};s?.show(X);return}C&&(C.style.display="block"),L&&(L.textContent=_),O&&(Yr(O,30),O.onclick=async()=>{if(O.style.pointerEvents!=="none")try{let X=await mr();await t.resendVerificationEmail(_,i,X,{workosCapable:!0}),Yr(O,30)}catch(X){h&&(h.style.display="block"),g&&(g.textContent=Mt(X,"Unable to resend verification. Please try again."))}finally{Ue()?.reset()}}),ce&&(ce.onclick=()=>{C&&(C.style.display="none"),_i(),Y()})}catch(F){x.classList.remove("loading"),x.value=D,Ue()?.reset(),!qe(F)&&h&&(h.style.display="block",g&&(g.textContent=Mt(F,"Unable to create the account. Please try again.")))}};return o&&l&&c&&wi(l,c,o.querySelector('[type="submit"]')),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let b=Q(a?.value||"");a&&(a.value=b);let A=l?.value||"",x=c?.value||"";if(!b||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b)){h&&(h.style.display="block",g&&(g.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),g&&(g.textContent="");let I=o.querySelector('[type="submit"]'),M=I?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await De(b,I):r==="login"?await Nt(b,A,I,M):r==="signup"&&await at(b,A,x,I,M)}catch(F){console.error("Auth flow error:",F),I&&(I.classList.remove("loading"),I.value=M),h&&(h.style.display="block")}}),{reset:Y}}var gr=function(){return gr=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++)for(var s in e=arguments[t])Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=e[s]);return i},gr.apply(this,arguments)},Si=function(){function i(e,t,r){var s=this;this.endVal=t,this.options=r,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){s.startTime||(s.startTime=n);var o=n-s.startTime;s.remaining=s.duration-o,s.useEasing?s.countDown?s.frameVal=s.startVal-s.easingFn(o,0,s.startVal-s.endVal,s.duration):s.frameVal=s.easingFn(o,s.startVal,s.endVal-s.startVal,s.duration):s.frameVal=s.startVal+(s.endVal-s.startVal)*(o/s.duration);var a=s.countDown?s.frameVal<s.endVal:s.frameVal>s.endVal;s.frameVal=a?s.endVal:s.frameVal,s.frameVal=Number(s.frameVal.toFixed(s.options.decimalPlaces)),s.printValue(s.frameVal),o<s.duration?s.rAF=requestAnimationFrame(s.count):s.finalEndVal!==null?s.update(s.finalEndVal):s.options.onCompleteCallback&&s.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,c,d=n<0?"-":"";o=Math.abs(n).toFixed(s.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?s.options.decimal+u[1]:"",s.options.useGrouping){c="";for(var p=3,m=0,y=0,S=a.length;y<S;++y)s.options.useIndianSeparators&&y===4&&(p=2,m=1),y!==0&&m%p==0&&(c=s.options.separator+c),m++,c=a[S-y-1]+c;a=c}return s.options.numerals&&s.options.numerals.length&&(a=a.replace(/[0-9]/g,function(v){return s.options.numerals[+v]}),l=l.replace(/[0-9]/g,function(v){return s.options.numerals[+v]})),d+s.options.prefix+a+l+s.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=gr(gr({},this.defaults),r),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return s.handleScroll(s)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,r=e.el.getBoundingClientRect(),s=r.top+window.pageYOffset,n=r.top+r.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||s>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var r=this.countDown?1:-1;this.endVal=e+r*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var r=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,r):this.el.tagName==="INPUT"?this.el.value=r:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=r:this.el.innerHTML=r}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,'  ])/g,"\\$1")},r=t(this.options.separator),s=t(this.options.decimal),n=e.replace(new RegExp(r,"g"),"").replace(new RegExp(s,"g"),".");return parseFloat(n)},i}();var Ei=!1;function Ti(){if(Ei)return;Ei=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(r=>{if(r.isIntersecting){let s=r.target;e.unobserve(s);let n=s.dataset.countDirection||"up",o=parseFloat(s.dataset.countOffset||"10")/100,a=parseFloat(s.dataset.countDuration||"2"),l=5,c=s.dataset.countTarget||s.textContent?.trim()||"0",d=parseFloat(c.replace(/,/g,""));if(isNaN(d))return;let u=d*o,p=Math.max(u,l),m=n==="down"?d+p:Math.max(0,d-p);new Si(s,d,{startVal:Math.round(m),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var xi=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,r]=e.split("=");return i[t]=r,i},{});async function Xn(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new tt,{accessToken:t,refreshToken:r}=cs(),s=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),c=document.querySelector("[error-div]"),d=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),p=document.querySelector("[spots]"),m=document.querySelectorAll("[referral-code]"),y=document.querySelector("[referral-count]"),S=document.querySelector("[desktop-bonus-remaining]"),v=document.querySelector("[desktop-bonus-complete]"),C=document.querySelector("[climbed-dropped]"),h=document.querySelector("[keep-moving]"),g=document.querySelector("[rank-arrow-wrap]"),L=document.querySelector("[cohort-text]"),O=document.querySelector("[top-100]"),ce=document.querySelector("[top-1000]"),z=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),q=document.querySelector("[sms-bonus-complete]"),be=document.querySelector("[total-boost]"),st=document.querySelector("[social-media-details]"),te=document.querySelector("[sms-popup-button]"),it=document.querySelector("[app-download]"),de=document.querySelector("[file-upload]"),ke=document.querySelector("[file-input]"),Y=document.querySelector("[file-validation-error]"),Se=document.querySelector("[file-upload-loading]"),nt=document.querySelector("[cancel-upload-button]"),ot=document.querySelector("[file-upload-verified]"),Me=document.querySelector("[boost-earned]"),_r=document.querySelector("[boost-earned-location]"),Ne=document.querySelector("[woohoo-button]"),qe=document.querySelector("[file-upload-failed]"),De=document.querySelector("[upload-failed-text]"),Nt=document.querySelector("[close-button]"),at=document.querySelector("[share-on-x]"),_=document.querySelector("[share-on-linkedin]"),b=document.querySelector("[share-on-whatsapp]"),A=document.querySelector("[share-on-slack]"),x=document.querySelector("[share-on-discord]"),D=document.querySelector("[social-media-bonus-remaining]"),I=document.querySelector("[social-media-bonus-complete]"),M=document.querySelector("[share-on-other-channel]");st&&st.addEventListener("click",()=>{P("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),te&&te.addEventListener("click",()=>{P("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),it&&it.addEventListener("click",()=>{window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_app_download",source:"android-waitlist-page"}),P("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let F=async()=>{clearTimeout(i),document.body.style.visibility="visible",o.forEach(Dt=>{Dt.style.display="none"}),n&&(n.style.display="block");let X=window.__abVariantPromise?await window.__abVariantPromise:"control",Fe=document.querySelector("[auth-hero-default]"),J=document.querySelector("[auth-hero-v1]"),re=document.querySelector("[auth-hero-v2]");Fe&&(Fe.style.display="none"),J&&(J.style.display="none"),re&&(re.style.display="none"),X==="dictation-broken"&&J?J.style.display="block":X==="smartest"&&re?re.style.display="block":Fe&&(Fe.style.display="block"),n&&(n.style.display="none"),s&&(s.style.display="block");let qt=document.querySelector("[reusable-section-wrap]");qt&&s&&s.appendChild(qt);let lt=document.querySelector(".wl_cohort-spot-wrap");lt&&(lt.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),P("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),ki(`${window.location.origin}/android-waitlist`)};if(!t||!r){await F();return}try{e.setCookies(t,r);let X=e.checkAndSetSession(),Fe=new Promise((f,k)=>setTimeout(()=>k(new Error("Session timeout")),3e3));await Promise.race([X,Fe]),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(i),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(f=>{f.style.display="flex",f.dataset.bound||(f.dataset.bound="true",f.addEventListener("click",async k=>{k.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let J=e.sessionData?.access_token,re=e.sessionData?.user.email,qt=e.sessionData?.user.user_metadata.full_name||" ",[lt,Dt]=ns(qt),ct=e.sessionData?.user.id;localStorage.setItem("email",re),ct&&localStorage.setItem("user_id",ct),ct&&vi(ct,{email:re,firstName:lt,lastName:Dt});let Ai=xi(),{dub_id:yr,referral:wr,promo_code:Qr}=Ai,Li=!!localStorage.getItem("conversion_sent"),He=!localStorage.getItem("android_waitlist_joined"),$={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},Ci={access_token:J,first_name:lt,last_name:Dt,dub_click_id:yr||void 0,referral:wr||void 0,promo_code:Qr||void 0};try{await j.signupUser(Ci),$.signup.success=!0}catch(f){$.signup.success=!1,$.signup.error=f instanceof Error?f.message:"Unknown error"}try{let f=await j.ensureReferralCode(J);if($.referral.success=f.ok,!f.ok){let k=await f.json().catch(()=>({}));$.referral.error=k.detail||k.message||`Status ${f.status}`}}catch(f){$.referral.success=!1,$.referral.error=f instanceof Error?f.message:"Network error"}Li||(P("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:yr||void 0,referral:wr||void 0,email:re,user_id:ct||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"));let Ri={email:re,device_type:"android"},Zr=!1;try{await j.addToWaitlist(Ri),$.waitlist.success=!0,Zr=!0}catch(f){$.waitlist.success=!1,$.waitlist.error=f instanceof Error?f.message:"Unknown error"}He&&Zr&&(localStorage.setItem("android_waitlist_joined","true"),P("app_waitlist",{device_type:"android",source:"android-waitlist-page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:"android",source:"android-waitlist-page"}));let G=await j.getAndroidWaitlistStats(J);if(G.status===404&&!He){P("android_waitlist_recovery_attempted",{reason:"localStorage flag set but 404 from stats API"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_attempted",reason:"localStorage flag set but 404 from stats API"}),localStorage.removeItem("android_waitlist_joined");try{let f={email:re,device_type:"android"};await j.addToWaitlist(f),localStorage.setItem("android_waitlist_joined","true"),G=await j.getAndroidWaitlistStats(J),G.ok&&(P("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(f){console.error("Recovery addToWaitlist failed:",f)}}let Oi=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if($.stats.success=G.ok,G.status===401||G.status===429||!G.ok){let f="";try{let k=await G.json();f=JSON.stringify(k),$.stats.error=k.detail||k.message||f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}catch{f="Could not parse response",$.stats.error=f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}P("android_waitlist_api_error",{status:G.status,error:f,signup_success:$.signup.success,signup_error:$.signup.error,referral_success:$.referral.success,referral_error:$.referral.error,waitlist_success:$.waitlist.success,waitlist_error:$.waitlist.error,stats_error:$.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:G.status,error:f}),a&&(a.style.display="none"),c&&(c.style.display="block");return}let H=await G.json();if(He){let f=await Xn(re);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:H.current_rank,user_email_hash:f})}let es=localStorage.getItem("android_waitlist_last_rank");if(es&&!He){let f=parseInt(es,10);H.current_rank<f&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:H.current_rank,positions_gained:f-H.current_rank,referral_count:H.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",H.current_rank.toString());let vr=f=>{let k=f.current_rank;if(u){let w=k.toLocaleString("en-US");u.textContent=w,u instanceof HTMLElement&&(u.dataset.countTarget=w)}if(f.starting_rank!==null){let w=f.starting_rank-k;p&&(p.textContent=Math.abs(w).toLocaleString()),w<0?(C&&(C.textContent="fell"),h&&(h.style.display="none"),g&&g.classList.add("invert")):(C&&(C.textContent="climbed"),h&&(h.style.display="inline-block"),g&&g.classList.remove("invert"))}if(O&&O.classList.remove("active"),ce&&ce.classList.remove("active"),z&&z.classList.remove("active"),k<=100?O&&O.classList.add("active"):k<=1e3?ce&&ce.classList.add("active"):k<=1e5&&z&&z.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(w=>{w.style.display="none"}),k<=100){let w=document.querySelector('[cohort-wins="top-100"]');w&&(w.style.display="block")}else if(k<=1e3){let w=document.querySelector('[cohort-wins="top-1000"]');w&&(w.style.display="block")}else if(k<=1e5){let w=document.querySelector('[cohort-wins="top-100k"]');w&&(w.style.display="block")}if(L)if(k<=100)L.innerHTML="You're in the <strong>top 100!</strong>";else if(k<=1e3){let w=k-100;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100`}else if(k<=1e5){let w=k-1e3;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 1,000`}else{let w=k-1e5;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100,000`}m.forEach(w=>{w.textContent=f.referral_code}),y&&(y.textContent=f.referrals_count.toString()),f.desktop_dictation_bonus_earned?(S&&(S.style.display="none"),v&&(v.style.display="block")):(S&&(S.style.display="block"),v&&(v.style.display="none")),f.phone_number_bonus_earned?(se&&(se.style.display="none"),q&&(q.style.display="block")):(se&&(se.style.display="block"),q&&(q.style.display="none")),f.verified_share_twitter&&at&&at.classList.add("verified"),f.verified_share_linkedin&&_&&_.classList.add("verified"),f.verified_share_whatsapp&&b&&b.classList.add("verified"),f.verified_share_slack&&A&&A.classList.add("verified"),f.verified_share_discord&&x&&x.classList.add("verified");let V=f.verified_share_twitter&&f.verified_share_linkedin&&f.verified_share_whatsapp&&f.verified_share_slack&&f.verified_share_discord;if(V&&(D&&(D.style.display="none"),I&&(I.style.display="block")),be){let w=[f.phone_number_bonus_earned,f.desktop_dictation_bonus_earned,V].filter(Boolean).length;be.textContent=`${w} of 3`}};vr(H);let ts=f=>f<=100?"top-100":f<=1e3?"top-1000":f<=1e5?"top-100k":"below-100k";P("android_waitlist_page_view",{rank:H.current_rank,total_boost:H.total_boost,referrals_count:H.referrals_count,cohort:ts(H.current_rank),is_first_visit:He}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:H.current_rank,total_boost:H.total_boost,referrals_count:H.referrals_count,cohort:ts(H.current_rank),is_first_visit:He});let Pi=`https://wisprflow.ai/waitlist?${H.referral_code}`;document.querySelectorAll("[share]").forEach(f=>{let k=f.getAttribute("share");if(!k)return;let w=document.querySelector(`[share-content="${k}"]`)?.textContent||"";f.addEventListener("click",async()=>{switch(P("android_waitlist_share_clicked",{platform:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:k}),k){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(w)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(w),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(Pi)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(w)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(w),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(w),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async f=>{let k=f,{phoneNumber:V}=k.detail;try{let w=await j.submitPhoneNumber(V,J),ue=await w.json();if(!w.ok||!ue.success){let Ft=ue.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:Ft}})),P("android_waitlist_sms_error",{error:Ft}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:Ft});return}window.dispatchEvent(new CustomEvent("sms:success"));let he=await j.getAndroidWaitlistStats(J);he.ok&&vr(await he.json()),P("android_waitlist_sms_submitted",{boost_earned:ue.boost_earned,new_rank:ue.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:ue.boost_earned,new_rank:ue.current_rank})}catch(w){console.error("SMS submission error:",w),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}})),P("android_waitlist_sms_error",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:"network_error"})}});let _e=f=>{de&&(de.style.display=f==="idle"?"block":"none"),Se&&(Se.style.display=f==="loading"?"block":"none"),ot&&(ot.style.display=f==="verified"?"block":"none"),qe&&(qe.style.display=f==="failed"?"block":"none"),Y&&(Y.style.display="none")},Ii=f=>{let V=["image/png","image/jpeg","image/jpg"];return f.size>20971520?"File too large. Maximum size is 20MB.":V.includes(f.type)?null:"Please upload a PNG or JPEG image."},ji={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},$i=f=>ji[f]||"Social Media",Ui={social_share_x:at,social_share_linkedin:_,social_share_whatsapp:b,social_share_slack:A,social_share_discord:x},Mi=f=>{let k=Ui[f];k&&k.classList.add("verified")},Ni=f=>({file_too_large:"File exceeds 20MB limit. (file_too_large)",invalid_file_type:"Please upload a PNG or JPEG. (invalid_file_type)","User not on Android waitlist":"Please join the waitlist first. (User not on Android waitlist)",all_platforms_already_claimed:"You've claimed all social share bonuses! (all_platforms_already_claimed)",x_already_claimed:"You've already received the X bonus. (x_already_claimed)",linkedin_already_claimed:"You've already received the LinkedIn bonus. (linkedin_already_claimed)",whatsapp_already_claimed:"You've already received the WhatsApp bonus. (whatsapp_already_claimed)",slack_already_claimed:"You've already received the Slack bonus. (slack_already_claimed)",discord_already_claimed:"You've already received the Discord bonus. (discord_already_claimed)",not_posted:"This looks like a draft, not a published post. (not_posted)",no_wispr_mention:"Post must mention Wispr Flow or wisprflow.ai. (no_wispr_mention)",invalid:"We couldn't verify this screenshot. Try a clearer image. (invalid)","An error occurred":"Something went wrong. Please try again. (An error occurred)"})[f??""]??`Verification failed. (${f})`,dt=null;ke&&ke.addEventListener("change",async()=>{let f=ke.files?.[0];if(!f)return;ke.value="";let k=Ii(f);if(k){Y&&(Y.textContent=k,Y.style.display="block"),P("android_waitlist_social_validation_error",{error:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:k});return}P("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),_e("loading"),dt=new AbortController;try{let V=await j.submitSocialShare(f,J,dt.signal),w=await V.json();if(!V.ok||!w.success){_e("failed"),De&&(De.textContent=Ni(w.error)),P("android_waitlist_social_upload_failed",{error:w.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:w.error});return}_e("verified"),Me&&(Me.textContent=w.boost_earned.toLocaleString()),_r&&(_r.textContent=$i(w.action)),Mi(w.action);let ue=await j.getAndroidWaitlistStats(J);if(ue.ok){let he=await ue.json();vr(he),he.verified_share_twitter&&he.verified_share_linkedin&&he.verified_share_whatsapp&&he.verified_share_slack&&he.verified_share_discord&&(Ne&&(Ne.style.display="none"),M&&(M.style.display="none"),P("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}P("android_waitlist_social_share_verified",{platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank})}catch(V){if(V instanceof Error&&V.name==="AbortError"){_e("idle");return}console.error("Social share upload error:",V),_e("failed"),De&&(De.textContent="Network error. Please try again."),P("android_waitlist_social_upload_failed",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:"network_error"})}finally{dt=null}}),nt&&nt.addEventListener("click",()=>{dt&&dt.abort(),_e("idle"),P("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),Ne&&Ne.addEventListener("click",()=>{_e("idle")}),Nt&&Nt.addEventListener("click",()=>{_e("idle")}),Oi(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Ti()}catch(X){console.error("Error on android-waitlist page:",X),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await F()}});})();