@tanay-wispr/webflow-package 6.8.5 → 6.8.7

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 Vi=Object.create;var Ht=Object.defineProperty;var Bi=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,Gi=Object.prototype.hasOwnProperty;var Ki=(s,e)=>()=>(s&&(e=s(s=0)),e);var ie=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Yi=(s,e)=>{for(var t in e)Ht(s,t,{get:e[t],enumerable:!0})},ns=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zi(e))!Gi.call(s,i)&&i!==t&&Ht(s,i,{get:()=>e[i],enumerable:!(r=Bi(e,i))||r.enumerable});return s};var os=(s,e,t)=>(t=s!=null?Vi(Ji(s)):{},ns(e||!s||!s.__esModule?Ht(t,"default",{value:s,enumerable:!0}):t,s)),Xi=s=>ns(Ht({},"__esModule",{value:!0}),s);var Te={};Yi(Te,{Headers:()=>Tr,Request:()=>cn,Response:()=>dn,default:()=>Er,fetch:()=>ln});var an,Be,ln,Er,Tr,cn,dn,ye=Ki(()=>{"use strict";an=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=an(),ln=Be.fetch,Er=Be.fetch.bind(Be),Tr=Be.Headers,cn=Be.Request,dn=Be.Response});var _s=ie(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});var xr=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ar.default=xr});var Rr=ie(mt=>{"use strict";var ys=mt&&mt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(mt,"__esModule",{value:!0});var hn=ys((ye(),Xi(Te))),fn=ys(_s()),Lr=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=hn.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 k=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),b=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");k&&b&&b.length>1&&(u=parseInt(b[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 k=await n.text();try{c=JSON.parse(k),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,m="OK")}catch{n.status===404&&k===""?(p=204,m="No Content"):c={message:k}}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 fn.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=Lr});var Pr=ie(gt=>{"use strict";var pn=gt&&gt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(gt,"__esModule",{value:!0});var mn=pn(Rr()),Cr=class extends mn.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 gn=_t&&_t.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_t,"__esModule",{value:!0});var _n=gn(Pr()),Or=class extends _n.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 jr=ie(wt=>{"use strict";var yn=wt&&wt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(wt,"__esModule",{value:!0});var yt=yn(Kt()),Ir=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=Ir});var ws=ie(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.version=void 0;Yt.version="0.0.0-automated"});var vs=ie(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DEFAULT_HEADERS=void 0;var wn=ws();Xt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${wn.version}`}});var ks=ie(vt=>{"use strict";var bs=vt&&vt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(vt,"__esModule",{value:!0});var vn=bs(jr()),bn=bs(Kt()),kn=vs(),$r=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},kn.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new vn.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 bn.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};vt.default=$r});var Ls=ie(V=>{"use strict";var bt=V&&V.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(V,"__esModule",{value:!0});V.PostgrestBuilder=V.PostgrestTransformBuilder=V.PostgrestFilterBuilder=V.PostgrestQueryBuilder=V.PostgrestClient=void 0;var Ss=bt(ks());V.PostgrestClient=Ss.default;var Es=bt(jr());V.PostgrestQueryBuilder=Es.default;var Ts=bt(Kt());V.PostgrestFilterBuilder=Ts.default;var xs=bt(Pr());V.PostgrestTransformBuilder=xs.default;var As=bt(Rr());V.PostgrestBuilder=As.default;V.default={PostgrestClient:Ss.default,PostgrestQueryBuilder:Es.default,PostgrestFilterBuilder:Ts.default,PostgrestTransformBuilder:xs.default,PostgrestBuilder:As.default}});var Ms=ie((sa,Us)=>{"use strict";Us.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var ut=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var R=(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(()=>R(s,e,t-1),200)},as=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var Vt=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,$="https://api.wisprflow.ai",re=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},X=s=>s.trim().toLowerCase(),ls=(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."),Qi=(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=ls(s,e);return new re(e,t,Qi(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},Zi=(s,e)=>{let t=ls(s,e);return new re(e,t,ht(t,e))},Wt="promo_code",en=4e3,tn=new Set([200,400,403,404,409,422]),cs=s=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},ds=s=>{if(!s)return"";try{return decodeURIComponent(s).trim()}catch{return""}},rn=()=>{let s=ut()[Wt];if(s===void 0)return"";let e=ds(s);return e||cs(Wt),e},sn=s=>{ds(ut()[Wt])===s&&cs(Wt)},nn=s=>s instanceof DOMException&&(s.name==="TimeoutError"||s.name==="AbortError"),on=(s,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:e===422?"validation_error":"unknown",Sr=class{static async signupUser(e){try{let t=`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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 re(422,"invalid_code",ht("invalid_code",422));let t=await fetch(`${$}/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=Zi(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new re(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 re(t.status,"authentication_failed",ht("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${$}/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 applyPromoCodeFromCookie(e,t=rn()){if(t)try{let r=await fetch(`${$}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(en)}),{status:i}=r;if(!tn.has(i)){R("promo_cookie_apply",{outcome:"deferred",status:i});return}if(sn(t),r.ok){R("promo_cookie_apply",{outcome:"attached",status:i});return}let n=await r.json().catch(()=>({}));R("promo_cookie_apply",{outcome:"rejected",status:i,reason:on(n,i)})}catch(r){console.error("Promo cookie apply deferred:",r),R("promo_cookie_apply",nn(r)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${$}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${$}/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=`${$}/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(`${$}/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(`${$}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${$}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${$}/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(`${$}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function us(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}function hs(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var U=Sr;var fs=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var ps=()=>{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 ms=()=>{let{access_token:s,refresh_token:e}=ps(),t=s,r=e;if(!t||!r){let i=fs();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var gs=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Te)).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 un=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=gs(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return un(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 Rs=os(Ls(),1),{PostgrestClient:Cs,PostgrestQueryBuilder:No,PostgrestFilterBuilder:Do,PostgrestTransformBuilder:qo,PostgrestBuilder:Fo}=Rs.default;var Ps="2.10.2";var Os={"X-Client-Info":`realtime-js/${Ps}`},Is="1.0.0",Zt=1e4,js=1e3,xe;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(xe||(xe={}));var z;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(z||(z={}));var K;(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"})(K||(K={}));var Qt;(function(s){s.websocket="websocket"})(Qt||(Qt={}));var we;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(we||(we={}));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 Ae=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 P;(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"})(P||(P={}));var Mr=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Sn(o,s,e,i),n),{})},Sn=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?$s(n,o):Ur(o)},$s=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return An(e,t)}switch(s){case P.bool:return En(e);case P.float4:case P.float8:case P.int2:case P.int4:case P.int8:case P.numeric:case P.oid:return Tn(e);case P.json:case P.jsonb:return xn(e);case P.timestamp:return Ln(e);case P.abstime:case P.date:case P.daterange:case P.int4range:case P.int8range:case P.money:case P.reltime:case P.text:case P.time:case P.timestamptz:case P.timetz:case P.tsrange:case P.tstzrange:return Ur(e);default:return Ur(e)}},Ur=s=>s,En=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Tn=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},xn=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},An=(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=>$s(e,a))}return s},Ln=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 Le=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 Nr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Nr||(Nr={}));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(b=>b.presence_ref),m=u.map(b=>b.presence_ref),y=d.filter(b=>m.indexOf(b.presence_ref)<0),k=u.filter(b=>p.indexOf(b.presence_ref)<0);y.length>0&&(a[c]=y),k.length>0&&(l[c]=k)}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 Dr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Dr||(Dr={}));var qr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(qr||(qr={}));var Fr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Fr||(Fr={}));var Je=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=z.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 Le(this,K.join,this.params,this.timeout),this.rejoinTimer=new Ae(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=z.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=z.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this._on(K.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 k=0;k<m;k++){let b=p[k],{filter:{event:C,schema:h,table:g,filter:L}}=b,O=d&&d[k];if(O&&O.event===C&&O.schema===h&&O.table===g&&O.filter===L)y.push(Object.assign(Object.assign({},b),{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,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=z.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 i=new Le(this,K.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 Le(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}=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)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var y,k,b;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((b=(k=m.filter)===null||k===void 0?void 0:k.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(m=>m.callback(p,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var y,k,b,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&&((k=t.ids)===null||k===void 0?void 0:k.includes(L))&&(O==="*"||O?.toLocaleLowerCase()===((b=t.data)===null||b===void 0?void 0:b.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:k,table:b,commit_timestamp:C,type:h,errors:g}=y;p=Object.assign(Object.assign({},{schema:k,table:b,commit_timestamp:C,eventType:h,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(p,r)})}_isClosed(){return this.state===z.closed}_isJoined(){return this.state===z.joined}_isJoining(){return this.state===z.joining}_isLeaving(){return this.state===z.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(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=z.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Mr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Mr(e.columns,e.old_record)),t}};var Cn=()=>{},Pn=typeof WebSocket<"u",Ge=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Os,this.params={},this.timeout=Zt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Cn,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(()=>(ye(),Te)).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 Ae(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(Pn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Hr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>os(Ms())).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 xe.connecting:return we.Connecting;case xe.open:return we.Open;case xe.closing:return we.Closing;default:return we.Closed}}isConnected(){return this.connectionState()===we.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(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:Is}))}_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(K.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(js,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Hr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=xe.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 q(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 On=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(()=>(ye(),Te)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Ns=()=>On(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ye(),Te))).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())})},Wr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),In=(s,e)=>Ye(void 0,void 0,void 0,function*(){let t=yield Ns();s instanceof t?s.json().then(r=>{e(new tr(Wr(r),s.status||500))}).catch(r=>{e(new St(Wr(r),r))}):e(new St(Wr(s),s))}),jn=(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,jn(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>In(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 Ds(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())})},$n={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},qs={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({},qs),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(q(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:qs.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(q(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(q(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(q(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(q(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(q(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(q(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(q(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(q(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({},$n),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(q(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 Fs="2.6.0";var Hs={"X-Client-Info":`storage-js/${Fs}`};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({},Hs),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(q(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(q(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(q(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Xe(this,void 0,void 0,function*(){try{return{data:yield Ds(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(q(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(q(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(q(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 Ws="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 Un={"X-Client-Info":`supabase-js-${Lt}/${Ws}`},Vs={headers:Un},Bs={schema:"public"},zs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Js={};ye();var Mn=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())})},Nn=s=>{let e;return s?e=s:typeof fetch>"u"?e=Er:e=fetch,(...t)=>e(...t)},Dn=()=>typeof Headers>"u"?Tr:Headers,Gs=(s,e,t)=>{let r=Nn(t),i=Dn();return(n,o)=>Mn(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 Ks(s){return s.replace(/\/$/,"")}function Ys(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 Xs="http://localhost:9999",Qs="supabase.auth.token";var Zs={"X-Client-Info":`gotrue-js/${nr}`},Vr=10;var Rt="X-Supabase-Api-Version",Br={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function ei(s){return Math.round(Date.now()/1e3)+s}function ti(){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",Re={tested:!1,writable:!1},ve=()=>{if(!Z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Re.tested)return Re.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Re.tested=!0,Re.writable=!0}catch{Re.tested=!0,Re.writable=!1}return Re.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(()=>(ye(),Te)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},ri=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",zr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Pt=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 qn(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 Ct=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Ct.promiseConstructor=Promise;function Jr(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(qn(r))}async function si(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function ii(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 Fn(s){return("0"+s.toString(16)).substr(-2)}function Hn(){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,Fn).join("")}async function Wn(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 Vn(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Bn(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 Wn(s);return Vn(t)}async function Ce(s,e,t=!1){let r=Hn(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await zr(s,`${e}-code-verifier`,i);let n=await Bn(r);return[n,r===n?"plain":"s256"]}var zn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ni(s){let e=s.headers.get(Rt);if(!e||!e.match(zn))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(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var cr=class extends Ot{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function oi(s){return E(s)&&s.name==="AuthApiError"}var Qe=class extends Ot{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},fe=class extends Ot{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},oe=class extends fe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ze=class extends fe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Pe=class extends fe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Oe=class extends fe{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 fe{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 fe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function dr(s){return E(s)&&s.name==="AuthRetryableFetchError"}var jt=class extends fe{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Jn=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=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Gn=[502,503,504];async function ai(s){var e;if(!ri(s))throw new et(Ie(s),0);if(Gn.includes(s.status))throw new et(Ie(s),s.status);let t;try{t=await s.json()}catch(n){throw new Qe(Ie(n),n)}let r,i=ni(s);if(i&&i.getTime()>=Br["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(Ie(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(Ie(t),s.status,t.weak_password.reasons);throw new cr(Ie(t),s.status||500,r)}var Kn=(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 T(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Rt]||(n[Rt]=Br["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 Yn(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 Yn(s,e,t,r,i,n){let o=Kn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new et(Ie(l),0)}if(a.ok||await ai(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await ai(l)}}function pe(s){var e;let t=null;Xn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=ei(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Gr(s){let e=pe(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 li(s){return{data:s,error:null}}function ci(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Jn(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 di(s){return s}function Xn(s){return s.access_token&&s.refresh_token&&s.expires_in}var Qn=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},je=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 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=Qn(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ci,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,i,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=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:di});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 k=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);c[`${b}Page`]=k}),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: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 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 ui={getItem:s=>ve()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{ve()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{ve()&&globalThis.localStorage.removeItem(s)}};function Kr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function hi(){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 $e={debug:!!(globalThis&&ve()&&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 Yr(s,e,t){$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),$e.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){$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw $e.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ur(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if($e.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()}})}hi();var Zn={url:Xs,storageKey:Qs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Zs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ut=30*1e3,fi=3;async function pi(s,e,t){return await t()}var Ue=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({},Zn),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 je({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||pi,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=Yr:this.lock=pi,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:ve()?this.storage=ui:(this.memoryStorage={},this.storage=Kr(this.memoryStorage)):(this.memoryStorage={},this.storage=Kr(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 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:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:pe}),{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 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:pe})}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:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:pe})}else throw new Pe("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:Gr})}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:Gr})}else throw new Pe("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 Pt(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(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:pe});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 T(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:pe}),{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 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:(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 Pe("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 T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:pe});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 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}),!((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:li})}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 T(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 T(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 T(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 Pe("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 Pt(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 T(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 T(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 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 Jr(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=Jr(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:k,error:b}=await this._getUser(n);if(b)throw b;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:k.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 Pt(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&&!(oi(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=ti(),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 T(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 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(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 T(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 ii(async i=>(i>0&&await si(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:pe})),(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 Pt(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+Vr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Vr}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 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(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 zr(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 ${fi} ticks`),i<=fi&&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 T(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 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}:(!((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 T(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 T(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}}))}};Ue.nextInstanceID=0;var eo=Ue,Xr=eo;var hr=class extends Xr{constructor(e){super(e)}};var to=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=Ks(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:Bs,realtime:Js,auth:Object.assign(Object.assign({},zs),{storageKey:l}),global:Vs},d=Ys(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=Gs(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},d.realtime)),this.rest=new Cs(`${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 to(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 mi=(s,e,t)=>new Mt(s,e,t);var me={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var ro=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:ro(t)},gi=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 so="https://api.workos.com",io=60,tt=(s,e)=>typeof s[e]=="string"?s[e]:void 0,_i=(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}},no=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):so,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()},yi=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<io&&n){let l=await no(e,n,tt(t,"iss"),tt(t,"org_id")),c=_i(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=_i(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var rt=class{constructor(){this.sessionData=null;this.supabase=mi(me.supaBaseUrl,me.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||me.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||me.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||me.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(gi(t)==="workos"){this.sessionData=await yi(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||me.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 U.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:i||me.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 U.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 U.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||me.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,wi=(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 vi(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,k=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")))},b=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,k(!0),t.forEach(g=>g.setAttribute("disabled","true")),p();try{await s.onVerify(h),p(),i&&(i.textContent="Verified \u2705")}catch(g){m=!1,k(!1),t.forEach(L=>{L.value="",L.removeAttribute("disabled")}),u(wi(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(),b())},h.onpaste=L=>{L.preventDefault();let O=(L.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((J,se)=>{t[se]&&(t[se].value=J)});let ce=Math.min(O.length,t.length-1);t[ce]?.focus(),p()}}),i&&(i.onclick=h=>{h.preventDefault(),b()});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(wi(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,bi=(s,e)=>s instanceof re?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,ki=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(),vi({email:e.email,onVerify:async i=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await U.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 Qr(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 Si(){le&&(clearInterval(le),le=null)}var Ei=/^[\p{L}\p{M}\s\-'.]+$/u;function oo(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Ei.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 Zr(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Ei.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 Ti(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=oo(e.value,s.value);l?i(l):n()},a=()=>{let l=Zr(e.value,s.value);l?i(l):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var xi="password-rejection-error",Ai=s=>s instanceof re?s.passwordRejectionMessage:null,Dt=s=>{s.classList.remove("error"),document.getElementById(xi)?.remove()},es=(s,e)=>{if(Dt(s),e.length===0)return;s.classList.add("error");let t=document.createElement("div");t.id=xi,t.style.fontSize="0.875rem",t.textContent=e,s.insertAdjacentElement("afterend",t)};var ao="wispr_workos_capable";var Li=()=>{try{return window.sessionStorage.getItem(ao)==="true"}catch{return!1}};function Ri(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]"),k=document.querySelector("[different-provider-name]"),b=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]"),J=document.querySelector("[scim-div]"),se=document.querySelector("[scim-reset]"),F=document.querySelector("[forgot-password]"),be=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]"),ke=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 Y=()=>{n(),y&&(y.style.display="none"),C&&(C.style.display="none"),h&&(h.style.display="none"),ee&&(ee.style.display="none"),J&&(J.style.display="none"),F&&(F.style.display="none"),be&&(be.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"),Dt(l)),c&&(c.value="",c.style.display="none",c.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");v&&(v.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]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),F&&(F.style.display="block",F.onclick=async()=>{let A=a?.value||"",x=F.textContent||"";try{let{hcaptcha:H}=window;if(!H)throw new Error("Verification system not loaded. Please refresh the page.");F.style.pointerEvents="none",F.textContent="Sending...";let{response:I}=await H.execute({async:!0});if(!I)throw new Error("Verification cancelled");await U.requestPasswordReset(A,I),H.reset(),m&&(m.style.display="none"),F&&(F.style.display="none"),be&&(be.style.display="block"),it&&(it.textContent=A)}catch(H){console.error("Error sending password reset email:",H),F.textContent=x,F.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",g&&(g.textContent=H instanceof Error?H.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]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),r="signup"},at=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),J&&(J.style.display="block"),se&&(se.onclick=()=>{J&&(J.style.display="none"),_&&(_.style.display="block"),Y()})},Ne=_=>{n();let v=hs(_);m&&(m.style.display="none"),y&&(y.style.display="block"),k&&(k.textContent=v),b&&(b.onclick=()=>{y&&(y.style.display="none"),Y()}),r="oauth_user"};i=ki({client:t,redirectUrl:s,isWorkosCapable:()=>!0,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 v=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,v):window.location.href=s},onMissingChallenge:Se,onReset:Y});let De=_=>{m&&(m.style.display="none"),ee&&(ee.style.display="block"),nt&&(nt.textContent=_),de&&(de.onclick=async()=>{let v=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=v,h&&(h.style.display="block"),g&&(g.textContent=Nt(A,"Unable to resend verification."))}finally{Me()?.reset()}}),ke&&(ke.onclick=()=>{ee&&(ee.style.display="none"),Y()}),r="unverified_email"},qe=_=>bi(_,{showSso:()=>Ne("workos"),showScim:at,showLogin:Se,showError:v=>{h&&(h.style.display="block"),g&&(g.textContent=v)}}),Fe=async(_,v)=>{let A=v.value;v.classList.add("loading"),v.value="";try{let x=await U.checkUserStatus(_);v.classList.remove("loading"),v.value=A,!x.exists&&x.scim_managed?at():x.enforce_sso?Ne("workos"):x.exists&&x.provider&&x.provider!=="email"&&x.provider!=="workos"?Ne(x.provider):x.exists&&x.provider==="workos"?Se():x.exists&&x.provider==="email"&&!x.verified?De(_):x.exists&&x.provider==="email"?Se():ot()}catch(x){console.error("Error checking user status:",x),v.classList.remove("loading"),v.value=A,qe(x)||ot()}},qt=async(_,v,A,x)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}let H=window.hcaptcha?.getResponse()||"";if(!H){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let D=await U.signInWithEmail({email:_,password:v,mcp_login_state:e.mcpLoginState,workos_capable:Li()});if(!D.redirect_url)throw new Error(D.error||"Unable to continue connector login. Please try again.");R("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=D.redirect_url;return}let I=Li(),N=await t.signInWithPassword(_,v,H,{workosCapable:I,provision:!1});if(N.kind==="otp"){if(!I)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let D={pendingAuthenticationToken:N.challenge.pending_authentication_token,email:X(N.challenge.email||_)};Me()?.reset(),A.classList.remove("loading"),A.value=x,i?.show(D);return}t.setCookies(N.accessToken,N.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(N.accessToken,N.refreshToken,N.fullName):window.location.href=s}catch(I){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=x,!qe(I)&&h&&(h.style.display="block",g&&(g.textContent=Nt(I,"Unable to sign in. Please try again.")))}},lt=async(_,v,A,x,H)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}if(v.trim().toLowerCase()===_.trim().toLowerCase()){es(l,"Password can't be the same as your email address.");return}if(!A||A.trim().length<2){h&&(h.style.display="block",g&&(g.textContent="Please enter your full name"));return}let I=Zr(A,v);if(I){h&&(h.style.display="block",g&&(g.textContent=I));return}let N=window.hcaptcha?.getResponse()||"";if(!N){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{let D=await t.signUpWithPassword(_,v,A,s,N,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=H,m&&(m.style.display="none"),h&&(h.style.display="none"),Vt(D)){let j={pendingAuthenticationToken:D.pending_authentication_token,email:X(D.email||_)};i?.show(j);return}C&&(C.style.display="block"),L&&(L.textContent=_),O&&(Qr(O,30),O.onclick=async()=>{if(O.style.pointerEvents!=="none")try{let j=await gr();await t.resendVerificationEmail(_,s,j,{workosCapable:!0}),Qr(O,30)}catch(j){h&&(h.style.display="block"),g&&(g.textContent=Nt(j,"Unable to resend verification. Please try again."))}finally{Me()?.reset()}}),ce&&(ce.onclick=()=>{C&&(C.style.display="none"),Si(),Y()})}catch(D){x.classList.remove("loading"),x.value=H,Me()?.reset();let j=Ai(D);j&&l?es(l,j):!qe(D)&&h&&(h.style.display="block",g&&(g.textContent=Nt(D,"Unable to create the account. Please try again.")))}};return o&&l&&c&&(Ti(l,c,o.querySelector('[type="submit"]')),l.addEventListener("input",()=>Dt(l))),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let v=X(a?.value||"");a&&(a.value=v);let A=l?.value||"",x=c?.value||"";if(!v||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){h&&(h.style.display="block",g&&(g.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),g&&(g.textContent=""),l&&Dt(l);let I=o.querySelector('[type="submit"]'),N=I?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await Fe(v,I):r==="login"?await qt(v,A,I,N):r==="signup"&&await lt(v,A,x,I,N)}catch(D){console.error("Auth flow error:",D),I&&(I.classList.remove("loading"),I.value=N),h&&(h.style.display="block")}}),{reset:Y}}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)},Ci=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,k=a.length;y<k;++y)i.options.useIndianSeparators&&y===4&&(p=2,m=1),y!==0&&m%p==0&&(c=i.options.separator+c),m++,c=a[k-y-1]+c;a=c}return i.options.numerals&&i.options.numerals.length&&(a=a.replace(/[0-9]/g,function(b){return i.options.numerals[+b]}),l=l.replace(/[0-9]/g,function(b){return i.options.numerals[+b]})),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 Pi=!1;function Oi(){if(Pi)return;Pi=!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 Ci(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)})}async function lo(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}=ms(),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]"),k=document.querySelector("[desktop-bonus-remaining]"),b=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]"),J=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),F=document.querySelector("[sms-bonus-complete]"),be=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]"),ke=document.querySelector("[file-input]"),Y=document.querySelector("[file-validation-error]"),Se=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]"),De=document.querySelector("[woohoo-button]"),qe=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]"),v=document.querySelector("[share-on-whatsapp]"),A=document.querySelector("[share-on-slack]"),x=document.querySelector("[share-on-discord]"),H=document.querySelector("[social-media-bonus-remaining]"),I=document.querySelector("[social-media-bonus-complete]"),N=document.querySelector("[share-on-other-channel]");it&&it.addEventListener("click",()=>{R("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),ee&&ee.addEventListener("click",()=>{R("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"}),R("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let D=async()=>{clearTimeout(s),document.body.style.visibility="visible",o.forEach(wr=>{wr.style.display="none"}),n&&(n.style.display="block");let j=window.__abVariantPromise?await window.__abVariantPromise:"control",te=document.querySelector("[auth-hero-default]"),He=document.querySelector("[auth-hero-v1]"),Ee=document.querySelector("[auth-hero-v2]");te&&(te.style.display="none"),He&&(He.style.display="none"),Ee&&(Ee.style.display="none"),j==="dictation-broken"&&He?He.style.display="block":j==="smartest"&&Ee?Ee.style.display="block":te&&(te.style.display="block"),n&&(n.style.display="none"),i&&(i.style.display="block");let ct=document.querySelector("[reusable-section-wrap]");ct&&i&&i.appendChild(ct);let ge=document.querySelector(".wl_cohort-spot-wrap");ge&&(ge.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),R("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),Ri(`${window.location.origin}/android-waitlist`)};if(!t||!r){await D();return}try{e.setCookies(t,r),await e.checkAndSetSession(),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 S=>{S.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,te=e.sessionData?.user.email,He=e.sessionData?.user.user_metadata.full_name||" ",[Ee,ct]=us(He),ge=e.sessionData?.user.id;localStorage.setItem("email",te),ge&&localStorage.setItem("user_id",ge),ge&&as(ge,{email:te,firstName:Ee,lastName:ct});let wr=ut(),{dub_id:vr,referral:br,promo_code:ts}=wr,Ii=!!localStorage.getItem("conversion_sent"),We=!localStorage.getItem("android_waitlist_joined"),M={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},ji={access_token:j,first_name:Ee,last_name:ct,dub_click_id:vr||void 0,referral:br||void 0,promo_code:ts||void 0};try{await U.signupUser(ji),M.signup.success=!0}catch(f){M.signup.success=!1,M.signup.error=f instanceof Error?f.message:"Unknown error"}try{let f=await U.ensureReferralCode(j);if(M.referral.success=f.ok,!f.ok){let S=await f.json().catch(()=>({}));M.referral.error=S.detail||S.message||`Status ${f.status}`}}catch(f){M.referral.success=!1,M.referral.error=f instanceof Error?f.message:"Network error"}Ii||(R("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:vr||void 0,referral:br||void 0,email:te,user_id:ge||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 $i={email:te,device_type:"android"},rs=!1;try{await U.addToWaitlist($i),M.waitlist.success=!0,rs=!0}catch(f){M.waitlist.success=!1,M.waitlist.error=f instanceof Error?f.message:"Unknown error"}We&&rs&&(localStorage.setItem("android_waitlist_joined","true"),R("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 U.getAndroidWaitlistStats(j);if(G.status===404&&!We){R("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:te,device_type:"android"};await U.addToWaitlist(f),localStorage.setItem("android_waitlist_joined","true"),G=await U.getAndroidWaitlistStats(j),G.ok&&(R("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 Ui=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if(M.stats.success=G.ok,G.status===401||G.status===429||!G.ok){let f="";try{let S=await G.json();f=JSON.stringify(S),M.stats.error=S.detail||S.message||f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}catch{f="Could not parse response",M.stats.error=f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}R("android_waitlist_api_error",{status:G.status,error:f,signup_success:M.signup.success,signup_error:M.signup.error,referral_success:M.referral.success,referral_error:M.referral.error,waitlist_success:M.waitlist.success,waitlist_error:M.waitlist.error,stats_error:M.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 W=await G.json();if(We){let f=await lo(te);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:W.current_rank,user_email_hash:f})}let ss=localStorage.getItem("android_waitlist_last_rank");if(ss&&!We){let f=parseInt(ss,10);W.current_rank<f&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:W.current_rank,positions_gained:f-W.current_rank,referral_count:W.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",W.current_rank.toString());let kr=f=>{let S=f.current_rank;if(u){let w=S.toLocaleString("en-US");u.textContent=w,u instanceof HTMLElement&&(u.dataset.countTarget=w)}if(f.starting_rank!==null){let w=f.starting_rank-S;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"),J&&J.classList.remove("active"),S<=100?O&&O.classList.add("active"):S<=1e3?ce&&ce.classList.add("active"):S<=1e5&&J&&J.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(w=>{w.style.display="none"}),S<=100){let w=document.querySelector('[cohort-wins="top-100"]');w&&(w.style.display="block")}else if(S<=1e3){let w=document.querySelector('[cohort-wins="top-1000"]');w&&(w.style.display="block")}else if(S<=1e5){let w=document.querySelector('[cohort-wins="top-100k"]');w&&(w.style.display="block")}if(L)if(S<=100)L.innerHTML="You're in the <strong>top 100!</strong>";else if(S<=1e3){let w=S-100;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100`}else if(S<=1e5){let w=S-1e3;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 1,000`}else{let w=S-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?(k&&(k.style.display="none"),b&&(b.style.display="block")):(k&&(k.style.display="block"),b&&(b.style.display="none")),f.phone_number_bonus_earned?(se&&(se.style.display="none"),F&&(F.style.display="block")):(se&&(se.style.display="block"),F&&(F.style.display="none")),f.verified_share_twitter&&lt&&lt.classList.add("verified"),f.verified_share_linkedin&&_&&_.classList.add("verified"),f.verified_share_whatsapp&&v&&v.classList.add("verified"),f.verified_share_slack&&A&&A.classList.add("verified"),f.verified_share_discord&&x&&x.classList.add("verified");let B=f.verified_share_twitter&&f.verified_share_linkedin&&f.verified_share_whatsapp&&f.verified_share_slack&&f.verified_share_discord;if(B&&(H&&(H.style.display="none"),I&&(I.style.display="block")),be){let w=[f.phone_number_bonus_earned,f.desktop_dictation_bonus_earned,B].filter(Boolean).length;be.textContent=`${w} of 3`}};kr(W);let is=f=>f<=100?"top-100":f<=1e3?"top-1000":f<=1e5?"top-100k":"below-100k";R("android_waitlist_page_view",{rank:W.current_rank,total_boost:W.total_boost,referrals_count:W.referrals_count,cohort:is(W.current_rank),is_first_visit:We}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:W.current_rank,total_boost:W.total_boost,referrals_count:W.referrals_count,cohort:is(W.current_rank),is_first_visit:We});let Mi=`https://wisprflow.ai/waitlist?${W.referral_code}`;document.querySelectorAll("[share]").forEach(f=>{let S=f.getAttribute("share");if(!S)return;let w=document.querySelector(`[share-content="${S}"]`)?.textContent||"";f.addEventListener("click",async()=>{switch(R("android_waitlist_share_clicked",{platform:S}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:S}),S){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(Mi)}`,"_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 S=f,{phoneNumber:B}=S.detail;try{let w=await U.submitPhoneNumber(B,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}})),R("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 U.getAndroidWaitlistStats(j);he.ok&&kr(await he.json()),R("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."}})),R("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"),at&&(at.style.display=f==="verified"?"block":"none"),qe&&(qe.style.display=f==="failed"?"block":"none"),Y&&(Y.style.display="none")},Ni=f=>{let B=["image/png","image/jpeg","image/jpg"];return f.size>20971520?"File too large. Maximum size is 20MB.":B.includes(f.type)?null:"Please upload a PNG or JPEG image."},Di={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},qi=f=>Di[f]||"Social Media",Fi={social_share_x:lt,social_share_linkedin:_,social_share_whatsapp:v,social_share_slack:A,social_share_discord:x},Hi=f=>{let S=Fi[f];S&&S.classList.add("verified")},Wi=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 S=Ni(f);if(S){Y&&(Y.textContent=S,Y.style.display="block"),R("android_waitlist_social_validation_error",{error:S}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:S});return}R("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 B=await U.submitSocialShare(f,j,dt.signal),w=await B.json();if(!B.ok||!w.success){_e("failed"),Fe&&(Fe.textContent=Wi(w.error)),R("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"),Ne&&(Ne.textContent=w.boost_earned.toLocaleString()),yr&&(yr.textContent=qi(w.action)),Hi(w.action);let ue=await U.getAndroidWaitlistStats(j);if(ue.ok){let he=await ue.json();kr(he),he.verified_share_twitter&&he.verified_share_linkedin&&he.verified_share_whatsapp&&he.verified_share_slack&&he.verified_share_discord&&(De&&(De.style.display="none"),N&&(N.style.display="none"),R("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}R("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(B){if(B instanceof Error&&B.name==="AbortError"){_e("idle");return}console.error("Social share upload error:",B),_e("failed"),Fe&&(Fe.textContent="Network error. Please try again."),R("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}}),ot&&ot.addEventListener("click",()=>{dt&&dt.abort(),_e("idle"),R("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),De&&De.addEventListener("click",()=>{_e("idle")}),qt&&qt.addEventListener("click",()=>{_e("idle")}),Ui(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Oi()}catch(j){console.error("Error on android-waitlist page:",j),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await D()}});})();
1
+ "use strict";(()=>{var Vi=Object.create;var Ht=Object.defineProperty;var Bi=Object.getOwnPropertyDescriptor;var zi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,Gi=Object.prototype.hasOwnProperty;var Ki=(s,e)=>()=>(s&&(e=s(s=0)),e);var ie=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Yi=(s,e)=>{for(var t in e)Ht(s,t,{get:e[t],enumerable:!0})},ns=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zi(e))!Gi.call(s,i)&&i!==t&&Ht(s,i,{get:()=>e[i],enumerable:!(r=Bi(e,i))||r.enumerable});return s};var os=(s,e,t)=>(t=s!=null?Vi(Ji(s)):{},ns(e||!s||!s.__esModule?Ht(t,"default",{value:s,enumerable:!0}):t,s)),Xi=s=>ns(Ht({},"__esModule",{value:!0}),s);var Te={};Yi(Te,{Headers:()=>Tr,Request:()=>cn,Response:()=>dn,default:()=>Er,fetch:()=>ln});var an,Be,ln,Er,Tr,cn,dn,ye=Ki(()=>{"use strict";an=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=an(),ln=Be.fetch,Er=Be.fetch.bind(Be),Tr=Be.Headers,cn=Be.Request,dn=Be.Response});var _s=ie(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});var xr=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ar.default=xr});var Cr=ie(mt=>{"use strict";var ys=mt&&mt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(mt,"__esModule",{value:!0});var hn=ys((ye(),Xi(Te))),fn=ys(_s()),Lr=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=hn.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 R=await n.text();R===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?d=R:d=JSON.parse(R))}let k=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),b=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");k&&b&&b.length>1&&(u=parseInt(b[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 k=await n.text();try{c=JSON.parse(k),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,m="OK")}catch{n.status===404&&k===""?(p=204,m="No Content"):c={message:k}}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 fn.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=Lr});var Pr=ie(gt=>{"use strict";var pn=gt&&gt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(gt,"__esModule",{value:!0});var mn=pn(Cr()),Rr=class extends mn.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=Rr});var Kt=ie(_t=>{"use strict";var gn=_t&&_t.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_t,"__esModule",{value:!0});var _n=gn(Pr()),Or=class extends _n.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 jr=ie(wt=>{"use strict";var yn=wt&&wt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(wt,"__esModule",{value:!0});var yt=yn(Kt()),Ir=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=Ir});var ws=ie(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.version=void 0;Yt.version="0.0.0-automated"});var vs=ie(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DEFAULT_HEADERS=void 0;var wn=ws();Xt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${wn.version}`}});var ks=ie(vt=>{"use strict";var bs=vt&&vt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(vt,"__esModule",{value:!0});var vn=bs(jr()),bn=bs(Kt()),kn=vs(),$r=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},kn.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new vn.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 bn.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};vt.default=$r});var Ls=ie(V=>{"use strict";var bt=V&&V.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(V,"__esModule",{value:!0});V.PostgrestBuilder=V.PostgrestTransformBuilder=V.PostgrestFilterBuilder=V.PostgrestQueryBuilder=V.PostgrestClient=void 0;var Ss=bt(ks());V.PostgrestClient=Ss.default;var Es=bt(jr());V.PostgrestQueryBuilder=Es.default;var Ts=bt(Kt());V.PostgrestFilterBuilder=Ts.default;var xs=bt(Pr());V.PostgrestTransformBuilder=xs.default;var As=bt(Cr());V.PostgrestBuilder=As.default;V.default={PostgrestClient:Ss.default,PostgrestQueryBuilder:Es.default,PostgrestFilterBuilder:Ts.default,PostgrestTransformBuilder:xs.default,PostgrestBuilder:As.default}});var Ms=ie((sa,Us)=>{"use strict";Us.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var ut=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var C=(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(()=>C(s,e,t-1),200)},as=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var Vt=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,$="https://api.wisprflow.ai",re=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},X=s=>s.trim().toLowerCase(),ls=(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."),Qi=(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=ls(s,e);return new re(e,t,Qi(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},Zi=(s,e)=>{let t=ls(s,e);return new re(e,t,ht(t,e))},Wt="promo_code",en=4e3,tn=new Set([200,400,403,404,409,422]),cs=s=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},ds=s=>{if(!s)return"";try{return decodeURIComponent(s).trim()}catch{return""}},rn=()=>{let s=ut()[Wt];if(s===void 0)return"";let e=ds(s);return e||cs(Wt),e},sn=s=>{ds(ut()[Wt])===s&&cs(Wt)},nn=s=>s instanceof DOMException&&(s.name==="TimeoutError"||s.name==="AbortError"),on=(s,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:e===422?"validation_error":"unknown",Sr=class{static async signupUser(e){try{let t=`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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(`${$}/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 re(422,"invalid_code",ht("invalid_code",422));let t=await fetch(`${$}/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=Zi(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new re(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 re(t.status,"authentication_failed",ht("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${$}/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 applyPromoCodeFromCookie(e,t=rn()){if(t)try{let r=await fetch(`${$}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(en)}),{status:i}=r;if(!tn.has(i)){C("promo_cookie_apply",{outcome:"deferred",status:i});return}if(sn(t),r.ok){C("promo_cookie_apply",{outcome:"attached",status:i});return}let n=await r.json().catch(()=>({}));C("promo_cookie_apply",{outcome:"rejected",status:i,reason:on(n,i)})}catch(r){console.error("Promo cookie apply deferred:",r),C("promo_cookie_apply",nn(r)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${$}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${$}/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=`${$}/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(`${$}/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(`${$}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${$}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${$}/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(`${$}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function us(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}function hs(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var U=Sr;var fs=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var ps=()=>{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 ms=()=>{let{access_token:s,refresh_token:e}=ps(),t=s,r=e;if(!t||!r){let i=fs();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var gs=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Te)).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 un=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=gs(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return un(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 Cs=os(Ls(),1),{PostgrestClient:Rs,PostgrestQueryBuilder:No,PostgrestFilterBuilder:Do,PostgrestTransformBuilder:qo,PostgrestBuilder:Fo}=Cs.default;var Ps="2.10.2";var Os={"X-Client-Info":`realtime-js/${Ps}`},Is="1.0.0",Zt=1e4,js=1e3,xe;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(xe||(xe={}));var z;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(z||(z={}));var K;(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"})(K||(K={}));var Qt;(function(s){s.websocket="websocket"})(Qt||(Qt={}));var we;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(we||(we={}));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 Ae=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 P;(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"})(P||(P={}));var Mr=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Sn(o,s,e,i),n),{})},Sn=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?$s(n,o):Ur(o)},$s=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return An(e,t)}switch(s){case P.bool:return En(e);case P.float4:case P.float8:case P.int2:case P.int4:case P.int8:case P.numeric:case P.oid:return Tn(e);case P.json:case P.jsonb:return xn(e);case P.timestamp:return Ln(e);case P.abstime:case P.date:case P.daterange:case P.int4range:case P.int8range:case P.money:case P.reltime:case P.text:case P.time:case P.timestamptz:case P.timetz:case P.tsrange:case P.tstzrange:return Ur(e);default:return Ur(e)}},Ur=s=>s,En=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Tn=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},xn=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},An=(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=>$s(e,a))}return s},Ln=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 Le=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 Nr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Nr||(Nr={}));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(b=>b.presence_ref),m=u.map(b=>b.presence_ref),y=d.filter(b=>m.indexOf(b.presence_ref)<0),k=u.filter(b=>p.indexOf(b.presence_ref)<0);y.length>0&&(a[c]=y),k.length>0&&(l[c]=k)}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 Dr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Dr||(Dr={}));var qr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(qr||(qr={}));var Fr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Fr||(Fr={}));var Je=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=z.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 Le(this,K.join,this.params,this.timeout),this.rejoinTimer=new Ae(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=z.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=z.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this._on(K.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 k=0;k<m;k++){let b=p[k],{filter:{event:R,schema:h,table:g,filter:L}}=b,O=d&&d[k];if(O&&O.event===R&&O.schema===h&&O.table===g&&O.filter===L)y.push(Object.assign(Object.assign({},b),{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,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=z.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 i=new Le(this,K.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 Le(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}=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)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var y,k,b;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((b=(k=m.filter)===null||k===void 0?void 0:k.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(m=>m.callback(p,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var y,k,b,R,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&&((k=t.ids)===null||k===void 0?void 0:k.includes(L))&&(O==="*"||O?.toLocaleLowerCase()===((b=t.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{let L=(h=(R=m?.filter)===null||R===void 0?void 0:R.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:k,table:b,commit_timestamp:R,type:h,errors:g}=y;p=Object.assign(Object.assign({},{schema:k,table:b,commit_timestamp:R,eventType:h,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(p,r)})}_isClosed(){return this.state===z.closed}_isJoined(){return this.state===z.joined}_isJoining(){return this.state===z.joining}_isLeaving(){return this.state===z.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(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=z.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Mr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Mr(e.columns,e.old_record)),t}};var Rn=()=>{},Pn=typeof WebSocket<"u",Ge=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Os,this.params={},this.timeout=Zt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Rn,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(()=>(ye(),Te)).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 Ae(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(Pn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Hr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>os(Ms())).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 xe.connecting:return we.Connecting;case xe.open:return we.Open;case xe.closing:return we.Closing;default:return we.Closed}}isConnected(){return this.connectionState()===we.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(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:Is}))}_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(K.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(js,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Hr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=xe.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 q(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 On=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(()=>(ye(),Te)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Ns=()=>On(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ye(),Te))).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())})},Wr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),In=(s,e)=>Ye(void 0,void 0,void 0,function*(){let t=yield Ns();s instanceof t?s.json().then(r=>{e(new tr(Wr(r),s.status||500))}).catch(r=>{e(new St(Wr(r),r))}):e(new St(Wr(s),s))}),jn=(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,jn(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>In(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 Ds(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())})},$n={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},qs={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({},qs),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(q(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:qs.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(q(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(q(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(q(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(q(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(q(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(q(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(q(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(q(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({},$n),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(q(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 Fs="2.6.0";var Hs={"X-Client-Info":`storage-js/${Fs}`};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({},Hs),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(q(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(q(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(q(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Xe(this,void 0,void 0,function*(){try{return{data:yield Ds(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(q(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(q(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(q(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 Ws="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 Un={"X-Client-Info":`supabase-js-${Lt}/${Ws}`},Vs={headers:Un},Bs={schema:"public"},zs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Js={};ye();var Mn=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())})},Nn=s=>{let e;return s?e=s:typeof fetch>"u"?e=Er:e=fetch,(...t)=>e(...t)},Dn=()=>typeof Headers>"u"?Tr:Headers,Gs=(s,e,t)=>{let r=Nn(t),i=Dn();return(n,o)=>Mn(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 Ks(s){return s.replace(/\/$/,"")}function Ys(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 Xs="http://localhost:9999",Qs="supabase.auth.token";var Zs={"X-Client-Info":`gotrue-js/${nr}`},Vr=10;var Ct="X-Supabase-Api-Version",Br={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function ei(s){return Math.round(Date.now()/1e3)+s}function ti(){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",Ce={tested:!1,writable:!1},ve=()=>{if(!Z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ce.tested)return Ce.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Ce.tested=!0,Ce.writable=!0}catch{Ce.tested=!0,Ce.writable=!1}return Ce.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(()=>(ye(),Te)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},ri=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",zr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Pt=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 qn(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 Jr(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(qn(r))}async function si(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function ii(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 Fn(s){return("0"+s.toString(16)).substr(-2)}function Hn(){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,Fn).join("")}async function Wn(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 Vn(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Bn(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 Wn(s);return Vn(t)}async function Re(s,e,t=!1){let r=Hn(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await zr(s,`${e}-code-verifier`,i);let n=await Bn(r);return[n,r===n?"plain":"s256"]}var zn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ni(s){let e=s.headers.get(Ct);if(!e||!e.match(zn))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(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var cr=class extends Ot{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function oi(s){return E(s)&&s.name==="AuthApiError"}var Qe=class extends Ot{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},fe=class extends Ot{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},oe=class extends fe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ze=class extends fe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Pe=class extends fe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Oe=class extends fe{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 fe{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 fe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function dr(s){return E(s)&&s.name==="AuthRetryableFetchError"}var jt=class extends fe{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Jn=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=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Gn=[502,503,504];async function ai(s){var e;if(!ri(s))throw new et(Ie(s),0);if(Gn.includes(s.status))throw new et(Ie(s),s.status);let t;try{t=await s.json()}catch(n){throw new Qe(Ie(n),n)}let r,i=ni(s);if(i&&i.getTime()>=Br["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(Ie(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(Ie(t),s.status,t.weak_password.reasons);throw new cr(Ie(t),s.status||500,r)}var Kn=(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 T(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Ct]||(n[Ct]=Br["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 Yn(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 Yn(s,e,t,r,i,n){let o=Kn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new et(Ie(l),0)}if(a.ok||await ai(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await ai(l)}}function pe(s){var e;let t=null;Xn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=ei(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Gr(s){let e=pe(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 li(s){return{data:s,error:null}}function ci(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Jn(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 di(s){return s}function Xn(s){return s.access_token&&s.refresh_token&&s.expires_in}var Qn=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},je=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 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=Qn(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ci,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,i,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=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:di});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 k=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);c[`${b}Page`]=k}),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: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 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 ui={getItem:s=>ve()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{ve()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{ve()&&globalThis.localStorage.removeItem(s)}};function Kr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function hi(){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 $e={debug:!!(globalThis&&ve()&&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 Yr(s,e,t){$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),$e.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){$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw $e.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ur(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if($e.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()}})}hi();var Zn={url:Xs,storageKey:Qs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Zs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ut=30*1e3,fi=3;async function pi(s,e,t){return await t()}var Ue=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({},Zn),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 je({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||pi,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=Yr:this.lock=pi,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:ve()?this.storage=ui:(this.memoryStorage={},this.storage=Kr(this.memoryStorage)):(this.memoryStorage={},this.storage=Kr(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 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:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:pe}),{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 Re(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:pe})}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:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:pe})}else throw new Pe("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:Gr})}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:Gr})}else throw new Pe("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 Pt(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(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:pe});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 T(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:pe}),{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 Re(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:(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 Pe("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 T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:pe});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 Re(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}),!((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:li})}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 T(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 T(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 T(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 Pe("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 Pt(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 T(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 T(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 Re(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 Jr(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=Jr(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:k,error:b}=await this._getUser(n);if(b)throw b;let R={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:p,refresh_token:o,token_type:c,user:k.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:R,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 Pt(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&&!(oi(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=ti(),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 Re(this.storage,this.storageKey,!0));try{return await T(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 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(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 T(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 ii(async i=>(i>0&&await si(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:pe})),(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 Pt(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+Vr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Vr}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 zr(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 ${fi} ticks`),i<=fi&&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 Re(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 T(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 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}:(!((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 T(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 T(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}}))}};Ue.nextInstanceID=0;var eo=Ue,Xr=eo;var hr=class extends Xr{constructor(e){super(e)}};var to=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=Ks(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:Bs,realtime:Js,auth:Object.assign(Object.assign({},zs),{storageKey:l}),global:Vs},d=Ys(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=Gs(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},d.realtime)),this.rest=new Rs(`${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 to(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 mi=(s,e,t)=>new Mt(s,e,t);var me={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var ro=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:ro(t)},gi=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 so="https://api.workos.com",io=60,tt=(s,e)=>typeof s[e]=="string"?s[e]:void 0,_i=(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}},no=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):so,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()},yi=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<io&&n){let l=await no(e,n,tt(t,"iss"),tt(t,"org_id")),c=_i(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=_i(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var rt=class{constructor(){this.sessionData=null;this.supabase=mi(me.supaBaseUrl,me.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||me.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||me.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||me.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(gi(t)==="workos"){this.sessionData=await yi(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||me.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=o?.deviceCode,l=a&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?a:void 0,c=await U.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,device_code:l,redirect_url:i||me.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),c}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 U.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 U.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||me.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,wi=(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 vi(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,k=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")))},b=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,k(!0),t.forEach(g=>g.setAttribute("disabled","true")),p();try{await s.onVerify(h),p(),i&&(i.textContent="Verified \u2705")}catch(g){m=!1,k(!1),t.forEach(L=>{L.value="",L.removeAttribute("disabled")}),u(wi(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(),b())},h.onpaste=L=>{L.preventDefault();let O=(L.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);O.split("").forEach((J,se)=>{t[se]&&(t[se].value=J)});let ce=Math.min(O.length,t.length-1);t[ce]?.focus(),p()}}),i&&(i.onclick=h=>{h.preventDefault(),b()});let R=()=>{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(),R();try{await s.onResend?.()}catch(g){u(wi(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,bi=(s,e)=>s instanceof re?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,ki=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(),vi({email:e.email,onVerify:async i=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await U.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 Qr(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 Si(){le&&(clearInterval(le),le=null)}var Ei=/^[\p{L}\p{M}\s\-'.]+$/u;function oo(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Ei.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 Zr(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Ei.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 Ti(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=oo(e.value,s.value);l?i(l):n()},a=()=>{let l=Zr(e.value,s.value);l?i(l):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var xi="password-rejection-error",Ai=s=>s instanceof re?s.passwordRejectionMessage:null,Dt=s=>{s.classList.remove("error"),document.getElementById(xi)?.remove()},es=(s,e)=>{if(Dt(s),e.length===0)return;s.classList.add("error");let t=document.createElement("div");t.id=xi,t.style.fontSize="0.875rem",t.textContent=e,s.insertAdjacentElement("afterend",t)};var ao="wispr_workos_capable";var Li=()=>{try{return window.sessionStorage.getItem(ao)==="true"}catch{return!1}};function Ci(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]"),k=document.querySelector("[different-provider-name]"),b=document.querySelector("[different-provider-reset]"),R=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]"),J=document.querySelector("[scim-div]"),se=document.querySelector("[scim-reset]"),F=document.querySelector("[forgot-password]"),be=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]"),ke=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 Y=()=>{n(),y&&(y.style.display="none"),R&&(R.style.display="none"),h&&(h.style.display="none"),ee&&(ee.style.display="none"),J&&(J.style.display="none"),F&&(F.style.display="none"),be&&(be.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"),Dt(l)),c&&(c.value="",c.style.display="none",c.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");v&&(v.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]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),F&&(F.style.display="block",F.onclick=async()=>{let A=a?.value||"",x=F.textContent||"";try{let{hcaptcha:H}=window;if(!H)throw new Error("Verification system not loaded. Please refresh the page.");F.style.pointerEvents="none",F.textContent="Sending...";let{response:I}=await H.execute({async:!0});if(!I)throw new Error("Verification cancelled");await U.requestPasswordReset(A,I),H.reset(),m&&(m.style.display="none"),F&&(F.style.display="none"),be&&(be.style.display="block"),it&&(it.textContent=A)}catch(H){console.error("Error sending password reset email:",H),F.textContent=x,F.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",g&&(g.textContent=H instanceof Error?H.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]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),r="signup"},at=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),J&&(J.style.display="block"),se&&(se.onclick=()=>{J&&(J.style.display="none"),_&&(_.style.display="block"),Y()})},Ne=_=>{n();let v=hs(_);m&&(m.style.display="none"),y&&(y.style.display="block"),k&&(k.textContent=v),b&&(b.onclick=()=>{y&&(y.style.display="none"),Y()}),r="oauth_user"};i=ki({client:t,redirectUrl:s,isWorkosCapable:()=>!0,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 v=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,v):window.location.href=s},onMissingChallenge:Se,onReset:Y});let De=_=>{m&&(m.style.display="none"),ee&&(ee.style.display="block"),nt&&(nt.textContent=_),de&&(de.onclick=async()=>{let v=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=v,h&&(h.style.display="block"),g&&(g.textContent=Nt(A,"Unable to resend verification."))}finally{Me()?.reset()}}),ke&&(ke.onclick=()=>{ee&&(ee.style.display="none"),Y()}),r="unverified_email"},qe=_=>bi(_,{showSso:()=>Ne("workos"),showScim:at,showLogin:Se,showError:v=>{h&&(h.style.display="block"),g&&(g.textContent=v)}}),Fe=async(_,v)=>{let A=v.value;v.classList.add("loading"),v.value="";try{let x=await U.checkUserStatus(_);v.classList.remove("loading"),v.value=A,!x.exists&&x.scim_managed?at():x.enforce_sso?Ne("workos"):x.exists&&x.provider&&x.provider!=="email"&&x.provider!=="workos"?Ne(x.provider):x.exists&&x.provider==="workos"?Se():x.exists&&x.provider==="email"&&!x.verified?De(_):x.exists&&x.provider==="email"?Se():ot()}catch(x){console.error("Error checking user status:",x),v.classList.remove("loading"),v.value=A,qe(x)||ot()}},qt=async(_,v,A,x)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}let H=window.hcaptcha?.getResponse()||"";if(!H){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let D=await U.signInWithEmail({email:_,password:v,mcp_login_state:e.mcpLoginState,workos_capable:Li()});if(!D.redirect_url)throw new Error(D.error||"Unable to continue connector login. Please try again.");C("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=D.redirect_url;return}let I=Li(),N=await t.signInWithPassword(_,v,H,{workosCapable:I,provision:!1});if(N.kind==="otp"){if(!I)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let D={pendingAuthenticationToken:N.challenge.pending_authentication_token,email:X(N.challenge.email||_)};Me()?.reset(),A.classList.remove("loading"),A.value=x,i?.show(D);return}t.setCookies(N.accessToken,N.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(N.accessToken,N.refreshToken,N.fullName):window.location.href=s}catch(I){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=x,!qe(I)&&h&&(h.style.display="block",g&&(g.textContent=Nt(I,"Unable to sign in. Please try again.")))}},lt=async(_,v,A,x,H)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}if(v.trim().toLowerCase()===_.trim().toLowerCase()){es(l,"Password can't be the same as your email address.");return}if(!A||A.trim().length<2){h&&(h.style.display="block",g&&(g.textContent="Please enter your full name"));return}let I=Zr(A,v);if(I){h&&(h.style.display="block",g&&(g.textContent=I));return}let N=window.hcaptcha?.getResponse()||"";if(!N){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{let D=await t.signUpWithPassword(_,v,A,s,N,{workosCapable:!0,deviceCode:e?.deviceCode});if(window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=H,m&&(m.style.display="none"),h&&(h.style.display="none"),Vt(D)){let j={pendingAuthenticationToken:D.pending_authentication_token,email:X(D.email||_)};i?.show(j);return}R&&(R.style.display="block"),L&&(L.textContent=_),O&&(Qr(O,30),O.onclick=async()=>{if(O.style.pointerEvents!=="none")try{let j=await gr();await t.resendVerificationEmail(_,s,j,{workosCapable:!0}),Qr(O,30)}catch(j){h&&(h.style.display="block"),g&&(g.textContent=Nt(j,"Unable to resend verification. Please try again."))}finally{Me()?.reset()}}),ce&&(ce.onclick=()=>{R&&(R.style.display="none"),Si(),Y()})}catch(D){x.classList.remove("loading"),x.value=H,Me()?.reset();let j=Ai(D);j&&l?es(l,j):!qe(D)&&h&&(h.style.display="block",g&&(g.textContent=Nt(D,"Unable to create the account. Please try again.")))}};return o&&l&&c&&(Ti(l,c,o.querySelector('[type="submit"]')),l.addEventListener("input",()=>Dt(l))),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let v=X(a?.value||"");a&&(a.value=v);let A=l?.value||"",x=c?.value||"";if(!v||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){h&&(h.style.display="block",g&&(g.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),g&&(g.textContent=""),l&&Dt(l);let I=o.querySelector('[type="submit"]'),N=I?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await Fe(v,I):r==="login"?await qt(v,A,I,N):r==="signup"&&await lt(v,A,x,I,N)}catch(D){console.error("Auth flow error:",D),I&&(I.classList.remove("loading"),I.value=N),h&&(h.style.display="block")}}),{reset:Y}}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)},Ri=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,k=a.length;y<k;++y)i.options.useIndianSeparators&&y===4&&(p=2,m=1),y!==0&&m%p==0&&(c=i.options.separator+c),m++,c=a[k-y-1]+c;a=c}return i.options.numerals&&i.options.numerals.length&&(a=a.replace(/[0-9]/g,function(b){return i.options.numerals[+b]}),l=l.replace(/[0-9]/g,function(b){return i.options.numerals[+b]})),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 Pi=!1;function Oi(){if(Pi)return;Pi=!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 Ri(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)})}async function lo(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}=ms(),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]"),k=document.querySelector("[desktop-bonus-remaining]"),b=document.querySelector("[desktop-bonus-complete]"),R=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]"),J=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),F=document.querySelector("[sms-bonus-complete]"),be=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]"),ke=document.querySelector("[file-input]"),Y=document.querySelector("[file-validation-error]"),Se=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]"),De=document.querySelector("[woohoo-button]"),qe=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]"),v=document.querySelector("[share-on-whatsapp]"),A=document.querySelector("[share-on-slack]"),x=document.querySelector("[share-on-discord]"),H=document.querySelector("[social-media-bonus-remaining]"),I=document.querySelector("[social-media-bonus-complete]"),N=document.querySelector("[share-on-other-channel]");it&&it.addEventListener("click",()=>{C("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),ee&&ee.addEventListener("click",()=>{C("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"}),C("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let D=async()=>{clearTimeout(s),document.body.style.visibility="visible",o.forEach(wr=>{wr.style.display="none"}),n&&(n.style.display="block");let j=window.__abVariantPromise?await window.__abVariantPromise:"control",te=document.querySelector("[auth-hero-default]"),He=document.querySelector("[auth-hero-v1]"),Ee=document.querySelector("[auth-hero-v2]");te&&(te.style.display="none"),He&&(He.style.display="none"),Ee&&(Ee.style.display="none"),j==="dictation-broken"&&He?He.style.display="block":j==="smartest"&&Ee?Ee.style.display="block":te&&(te.style.display="block"),n&&(n.style.display="none"),i&&(i.style.display="block");let ct=document.querySelector("[reusable-section-wrap]");ct&&i&&i.appendChild(ct);let ge=document.querySelector(".wl_cohort-spot-wrap");ge&&(ge.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),C("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),Ci(`${window.location.origin}/android-waitlist`)};if(!t||!r){await D();return}try{e.setCookies(t,r),await e.checkAndSetSession(),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 S=>{S.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,te=e.sessionData?.user.email,He=e.sessionData?.user.user_metadata.full_name||" ",[Ee,ct]=us(He),ge=e.sessionData?.user.id;localStorage.setItem("email",te),ge&&localStorage.setItem("user_id",ge),ge&&as(ge,{email:te,firstName:Ee,lastName:ct});let wr=ut(),{dub_id:vr,referral:br,promo_code:ts}=wr,Ii=!!localStorage.getItem("conversion_sent"),We=!localStorage.getItem("android_waitlist_joined"),M={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},ji={access_token:j,first_name:Ee,last_name:ct,dub_click_id:vr||void 0,referral:br||void 0,promo_code:ts||void 0};try{await U.signupUser(ji),M.signup.success=!0}catch(f){M.signup.success=!1,M.signup.error=f instanceof Error?f.message:"Unknown error"}try{let f=await U.ensureReferralCode(j);if(M.referral.success=f.ok,!f.ok){let S=await f.json().catch(()=>({}));M.referral.error=S.detail||S.message||`Status ${f.status}`}}catch(f){M.referral.success=!1,M.referral.error=f instanceof Error?f.message:"Network error"}Ii||(C("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:vr||void 0,referral:br||void 0,email:te,user_id:ge||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 $i={email:te,device_type:"android"},rs=!1;try{await U.addToWaitlist($i),M.waitlist.success=!0,rs=!0}catch(f){M.waitlist.success=!1,M.waitlist.error=f instanceof Error?f.message:"Unknown error"}We&&rs&&(localStorage.setItem("android_waitlist_joined","true"),C("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 U.getAndroidWaitlistStats(j);if(G.status===404&&!We){C("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:te,device_type:"android"};await U.addToWaitlist(f),localStorage.setItem("android_waitlist_joined","true"),G=await U.getAndroidWaitlistStats(j),G.ok&&(C("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 Ui=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if(M.stats.success=G.ok,G.status===401||G.status===429||!G.ok){let f="";try{let S=await G.json();f=JSON.stringify(S),M.stats.error=S.detail||S.message||f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}catch{f="Could not parse response",M.stats.error=f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}C("android_waitlist_api_error",{status:G.status,error:f,signup_success:M.signup.success,signup_error:M.signup.error,referral_success:M.referral.success,referral_error:M.referral.error,waitlist_success:M.waitlist.success,waitlist_error:M.waitlist.error,stats_error:M.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 W=await G.json();if(We){let f=await lo(te);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:W.current_rank,user_email_hash:f})}let ss=localStorage.getItem("android_waitlist_last_rank");if(ss&&!We){let f=parseInt(ss,10);W.current_rank<f&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:W.current_rank,positions_gained:f-W.current_rank,referral_count:W.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",W.current_rank.toString());let kr=f=>{let S=f.current_rank;if(u){let w=S.toLocaleString("en-US");u.textContent=w,u instanceof HTMLElement&&(u.dataset.countTarget=w)}if(f.starting_rank!==null){let w=f.starting_rank-S;p&&(p.textContent=Math.abs(w).toLocaleString()),w<0?(R&&(R.textContent="fell"),h&&(h.style.display="none"),g&&g.classList.add("invert")):(R&&(R.textContent="climbed"),h&&(h.style.display="inline-block"),g&&g.classList.remove("invert"))}if(O&&O.classList.remove("active"),ce&&ce.classList.remove("active"),J&&J.classList.remove("active"),S<=100?O&&O.classList.add("active"):S<=1e3?ce&&ce.classList.add("active"):S<=1e5&&J&&J.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(w=>{w.style.display="none"}),S<=100){let w=document.querySelector('[cohort-wins="top-100"]');w&&(w.style.display="block")}else if(S<=1e3){let w=document.querySelector('[cohort-wins="top-1000"]');w&&(w.style.display="block")}else if(S<=1e5){let w=document.querySelector('[cohort-wins="top-100k"]');w&&(w.style.display="block")}if(L)if(S<=100)L.innerHTML="You're in the <strong>top 100!</strong>";else if(S<=1e3){let w=S-100;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100`}else if(S<=1e5){let w=S-1e3;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 1,000`}else{let w=S-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?(k&&(k.style.display="none"),b&&(b.style.display="block")):(k&&(k.style.display="block"),b&&(b.style.display="none")),f.phone_number_bonus_earned?(se&&(se.style.display="none"),F&&(F.style.display="block")):(se&&(se.style.display="block"),F&&(F.style.display="none")),f.verified_share_twitter&&lt&&lt.classList.add("verified"),f.verified_share_linkedin&&_&&_.classList.add("verified"),f.verified_share_whatsapp&&v&&v.classList.add("verified"),f.verified_share_slack&&A&&A.classList.add("verified"),f.verified_share_discord&&x&&x.classList.add("verified");let B=f.verified_share_twitter&&f.verified_share_linkedin&&f.verified_share_whatsapp&&f.verified_share_slack&&f.verified_share_discord;if(B&&(H&&(H.style.display="none"),I&&(I.style.display="block")),be){let w=[f.phone_number_bonus_earned,f.desktop_dictation_bonus_earned,B].filter(Boolean).length;be.textContent=`${w} of 3`}};kr(W);let is=f=>f<=100?"top-100":f<=1e3?"top-1000":f<=1e5?"top-100k":"below-100k";C("android_waitlist_page_view",{rank:W.current_rank,total_boost:W.total_boost,referrals_count:W.referrals_count,cohort:is(W.current_rank),is_first_visit:We}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:W.current_rank,total_boost:W.total_boost,referrals_count:W.referrals_count,cohort:is(W.current_rank),is_first_visit:We});let Mi=`https://wisprflow.ai/waitlist?${W.referral_code}`;document.querySelectorAll("[share]").forEach(f=>{let S=f.getAttribute("share");if(!S)return;let w=document.querySelector(`[share-content="${S}"]`)?.textContent||"";f.addEventListener("click",async()=>{switch(C("android_waitlist_share_clicked",{platform:S}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:S}),S){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(Mi)}`,"_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 S=f,{phoneNumber:B}=S.detail;try{let w=await U.submitPhoneNumber(B,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}})),C("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 U.getAndroidWaitlistStats(j);he.ok&&kr(await he.json()),C("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."}})),C("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"),at&&(at.style.display=f==="verified"?"block":"none"),qe&&(qe.style.display=f==="failed"?"block":"none"),Y&&(Y.style.display="none")},Ni=f=>{let B=["image/png","image/jpeg","image/jpg"];return f.size>20971520?"File too large. Maximum size is 20MB.":B.includes(f.type)?null:"Please upload a PNG or JPEG image."},Di={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},qi=f=>Di[f]||"Social Media",Fi={social_share_x:lt,social_share_linkedin:_,social_share_whatsapp:v,social_share_slack:A,social_share_discord:x},Hi=f=>{let S=Fi[f];S&&S.classList.add("verified")},Wi=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 S=Ni(f);if(S){Y&&(Y.textContent=S,Y.style.display="block"),C("android_waitlist_social_validation_error",{error:S}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:S});return}C("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 B=await U.submitSocialShare(f,j,dt.signal),w=await B.json();if(!B.ok||!w.success){_e("failed"),Fe&&(Fe.textContent=Wi(w.error)),C("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"),Ne&&(Ne.textContent=w.boost_earned.toLocaleString()),yr&&(yr.textContent=qi(w.action)),Hi(w.action);let ue=await U.getAndroidWaitlistStats(j);if(ue.ok){let he=await ue.json();kr(he),he.verified_share_twitter&&he.verified_share_linkedin&&he.verified_share_whatsapp&&he.verified_share_slack&&he.verified_share_discord&&(De&&(De.style.display="none"),N&&(N.style.display="none"),C("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}C("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(B){if(B instanceof Error&&B.name==="AbortError"){_e("idle");return}console.error("Social share upload error:",B),_e("failed"),Fe&&(Fe.textContent="Network error. Please try again."),C("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}}),ot&&ot.addEventListener("click",()=>{dt&&dt.abort(),_e("idle"),C("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),De&&De.addEventListener("click",()=>{_e("idle")}),qt&&qt.addEventListener("click",()=>{_e("idle")}),Ui(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Oi()}catch(j){console.error("Error on android-waitlist page:",j),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await D()}});})();